Skip to content

Commit

Permalink
test(webhook-token): added additional tests for wrong tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
dharsanb committed Jun 19, 2024
1 parent df8ce19 commit 1e8048d
Showing 1 changed file with 98 additions and 1 deletion.
99 changes: 98 additions & 1 deletion bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ func TestNew(t *testing.T) {
}
}

func TestBot_StartWebhook(t *testing.T) {
func TestBot_StartWebhookWithCorrectSecret(t *testing.T) {
s := newServerMock("xxx")
defer s.Close()

Expand Down Expand Up @@ -213,6 +213,103 @@ func TestBot_StartWebhook(t *testing.T) {
mx.Unlock()
}

func TestBot_StartWebhookWithNoSecret(t *testing.T) {
s := newServerMock("xxx")
defer s.Close()

opts := []Option{WithServerURL(s.URL())}
b, err := New("xxx", opts...)
if err != nil {
t.Fatalf("unexpected error %q", err)
}

mx := sync.Mutex{}
var called bool

b.defaultHandlerFunc = func(ctx context.Context, bot *Bot, update *models.Update) {
if update.Message.ID != 1 {
t.Errorf("unexpected message id")
}
mx.Lock()
called = true
mx.Unlock()
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go b.StartWebhook(ctx)

time.Sleep(time.Millisecond * 100)

req, errReq := http.NewRequest(http.MethodPost, "", strings.NewReader(`{"update_id":1,"message":{"message_id":1}}`))
if errReq != nil {
t.Error(errReq)
return
}

b.WebhookHandler().ServeHTTP(nil, req)

cancel()

time.Sleep(time.Millisecond * 100)

mx.Lock()
if !called {
t.Errorf("not called default handler")
}
mx.Unlock()
}

func TestBot_StartWebhookWithWrongSecret(t *testing.T) {
s := newServerMock("xxx")
defer s.Close()

opts := []Option{WithServerURL(s.URL()), WithWebhookSecretToken("zzzz")}
b, err := New("xxx", opts...)
if err != nil {
t.Fatalf("unexpected error %q", err)
}

mx := sync.Mutex{}
var called bool

b.defaultHandlerFunc = func(ctx context.Context, bot *Bot, update *models.Update) {
if update.Message.ID != 1 {
t.Errorf("unexpected message id")
}
mx.Lock()
called = true
mx.Unlock()
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go b.StartWebhook(ctx)

time.Sleep(time.Millisecond * 100)

req, errReq := http.NewRequest(http.MethodPost, "", strings.NewReader(`{"update_id":1,"message":{"message_id":1}}`))
if errReq != nil {
t.Error(errReq)
return
}
req.Header.Set("X-Telegram-Bot-Api-Secret-Token", "wrong_secret")

b.WebhookHandler().ServeHTTP(nil, req)

cancel()

time.Sleep(time.Millisecond * 100)

mx.Lock()
if called {
t.Errorf("not supposed to call the default handler with wrong token")
}
mx.Unlock()
}

func TestBot_Start(t *testing.T) {
s := newServerMock("xxx")
defer s.Close()
Expand Down

0 comments on commit 1e8048d

Please sign in to comment.