Skip to content

Commit

Permalink
test(telegram): add generator test (#190)
Browse files Browse the repository at this point in the history
  • Loading branch information
piksel authored Aug 10, 2021
1 parent db00936 commit 603fafc
Show file tree
Hide file tree
Showing 4 changed files with 131 additions and 11 deletions.
20 changes: 14 additions & 6 deletions pkg/services/telegram/telegram_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import (
f "github.com/containrrr/shoutrrr/pkg/format"
"github.com/containrrr/shoutrrr/pkg/types"
"github.com/containrrr/shoutrrr/pkg/util/generator"
"os/signal"
"syscall"

"fmt"
"io"
"os"
"os/signal"
"strconv"
"syscall"
)

// Generator is the telegram-specific URL generator
Expand All @@ -23,13 +24,20 @@ type Generator struct {
owner *User
statusMessage int64
botName string
Reader io.Reader
Writer io.Writer
}

// Generate a telegram Shoutrrr configuration from a user dialog
func (g *Generator) Generate(_ types.Service, props map[string]string, _ []string) (types.ServiceConfig, error) {
var config Config

g.ud = generator.NewUserDialog(os.Stdin, os.Stdout, props)
if g.Reader == nil {
g.Reader = os.Stdin
}
if g.Writer == nil {
g.Writer = os.Stdout
}
g.ud = generator.NewUserDialog(g.Reader, g.Writer, props)
ud := g.ud

ud.Writeln("To start we need your bot token. If you haven't created a bot yet, you can use this link:")
Expand All @@ -50,7 +58,7 @@ func (g *Generator) Generate(_ types.Service, props map[string]string, _ []strin
g.botName = botInfo.Username
ud.Writeln("")
ud.Writeln("Okay! %v will listen for any messages in PMs and group chats it is invited to.",
f.ColorizeString("@", g.botName, ":"))
f.ColorizeString("@", g.botName))

g.done = false
lastUpdate := 0
Expand Down Expand Up @@ -132,7 +140,7 @@ func (g *Generator) Generate(_ types.Service, props map[string]string, _ []strin
return &config, nil
}

func (g *Generator) addChat(chat *chat) (result string) {
func (g *Generator) addChat(chat *Chat) (result string) {
id := strconv.FormatInt(chat.ID, 10)
name := chat.Name()

Expand Down
112 changes: 112 additions & 0 deletions pkg/services/telegram/telegram_generator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package telegram_test

import (
"fmt"
"github.com/jarcoal/httpmock"
"github.com/mattn/go-colorable"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"io"
"strings"

"github.com/containrrr/shoutrrr/pkg/services/telegram"
)

const (
mockToken = `0:MockToken`
mockAPIBase = "https://api.telegram.org/bot" + mockToken + "/"
)

var (
userOut *gbytes.Buffer
userIn *gbytes.Buffer
userInMono io.Writer
)

func mockTyped(a ...interface{}) {
_, _ = fmt.Fprint(userOut, a...)
_, _ = fmt.Fprint(userOut, "\n")
}

func dumpBuffers() {
for _, line := range strings.Split(string(userIn.Contents()), "\n") {
println(">", line)
}
for _, line := range strings.Split(string(userOut.Contents()), "\n") {
println("<", line)
}
}

func mockAPI(endpoint string) string {
return mockAPIBase + endpoint
}

var _ = Describe("TelegramGenerator", func() {

BeforeEach(func() {
userOut = gbytes.NewBuffer()
userIn = gbytes.NewBuffer()
userInMono = colorable.NewNonColorable(userIn)
httpmock.Activate()
})
AfterEach(func() {
httpmock.DeactivateAndReset()
})
It("should return the ", func() {
gen := telegram.Generator{
Reader: userOut,
Writer: userInMono,
}

resultChannel := make(chan string, 1)

httpmock.RegisterResponder("GET", mockAPI(`getMe`), httpmock.NewJsonResponderOrPanic(200, &struct {
OK bool
Result *telegram.User
}{
true, &telegram.User{
ID: 1,
IsBot: true,
Username: "mockbot",
},
}))

httpmock.RegisterResponder("POST", mockAPI(`getUpdates`), httpmock.NewJsonResponderOrPanic(200, &struct {
OK bool
Result []telegram.Update
}{
true,
[]telegram.Update{
{
Message: &telegram.Message{
Text: "hi!",
From: &telegram.User{Username: `mockUser`},
Chat: &telegram.Chat{Type: `private`, ID: 667, Username: `mockUser`},
},
},
},
}))

go func() {
defer GinkgoRecover()
conf, err := gen.Generate(nil, nil, nil)

Expect(conf).ToNot(BeNil())
Expect(err).NotTo(HaveOccurred())
resultChannel <- conf.GetURL().String()
}()

defer dumpBuffers()

mockTyped(mockToken)
mockTyped(`no`)

Eventually(userIn).Should(gbytes.Say(`Got 1 chat ID\(s\) so far\. Want to add some more\?`))
Eventually(userIn).Should(gbytes.Say(`Selected chats:`))
Eventually(userIn).Should(gbytes.Say(`667 \(private\) @mockUser`))

Eventually(resultChannel).Should(Receive(Equal(`telegram://0:MockToken@telegram?chats=667&preview=No`)))
})

})
8 changes: 5 additions & 3 deletions pkg/services/telegram/telegram_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type Message struct {
MessageID int64 `json:"message_id"`
Text string `json:"text"`
From *User `json:"from"`
Chat *chat `json:"chat"`
Chat *Chat `json:"chat"`
}

type messageResponse struct {
Expand Down Expand Up @@ -133,14 +133,16 @@ type Update struct {
*/
}

type chat struct {
// Chat represents a telegram conversation
type Chat struct {
ID int64 `json:"id"`
Type string `json:"type"`
Title string `json:"title"`
Username string `json:"username"`
}

func (c *chat) Name() string {
// Name returns the name of the channel based on its type
func (c *Chat) Name() string {
if c.Type == "private" || c.Type == "channel" {
return "@" + c.Username
}
Expand Down
2 changes: 0 additions & 2 deletions pkg/services/telegram/telegram_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ var _ = Describe("the telegram service", func() {
Expect(err).NotTo(HaveOccurred())
err = telegram.Send(message, nil)
Expect(err).To(HaveOccurred())
fmt.Println(err.Error())
Expect(strings.Contains(err.Error(), "401 Unauthorized")).To(BeTrue())
})
})
Expand Down Expand Up @@ -160,7 +159,6 @@ func expectErrorAndEmptyObject(telegram *Service, rawURL string, logger *log.Log
err := telegram.Initialize(serviceURL, logger)
Expect(err).To(HaveOccurred())
config := telegram.GetConfig()
fmt.Printf("Token: \"%+v\" \"%s\" \n", config.Token, config.Token)
Expect(config.Token).To(BeEmpty())
Expect(len(config.Chats)).To(BeZero())
}
Expand Down

0 comments on commit 603fafc

Please sign in to comment.