forked from go-telegram/bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot_test.go
247 lines (200 loc) · 4.71 KB
/
bot_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package bot
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gokhanaltun/go-telegram-bot/models"
)
type serverMock struct {
s *httptest.Server
custom map[string]any
hooks map[string]func(body []byte) any
hooksCalls map[string]int
updateIdx int
updates []*models.Update
token string
}
type getUpdatesResponse struct {
OK bool `json:"ok"`
Result []*models.Update `json:"result"`
}
func (s *serverMock) handler(rw http.ResponseWriter, req *http.Request) {
if req.URL.String() == "/bot"+s.token+"/getMe" {
_, err := rw.Write([]byte(`{"ok":true,"result":{}}`))
if err != nil {
panic(err)
}
return
}
if req.URL.String() == "/bot"+s.token+"/getUpdates" {
s.handlerGetUpdates(rw)
return
}
reqBody, errReadBody := io.ReadAll(req.Body)
if errReadBody != nil {
panic(errReadBody)
}
defer req.Body.Close()
hook, okHook := s.hooks[req.URL.String()]
if okHook {
s.hooksCalls[req.URL.String()]++
resp, errData := json.Marshal(hook(reqBody))
if errData != nil {
panic(errData)
}
_, err := rw.Write(resp)
if err != nil {
panic(err)
}
return
}
d, ok := s.custom[req.URL.String()]
if !ok {
panic("answer not found for request: " + req.URL.String())
}
resp, errData := json.Marshal(d)
if errData != nil {
panic(errData)
}
_, err := rw.Write(resp)
if err != nil {
panic(err)
}
}
func (s *serverMock) Close() {
s.s.Close()
}
func (s *serverMock) handlerGetUpdates(rw http.ResponseWriter) {
if s.updateIdx >= len(s.updates) {
_, err := rw.Write([]byte(`{"ok":true,"result":[]}`))
if err != nil {
panic(err)
}
return
}
s.updates[s.updateIdx].ID = int64(s.updateIdx + 1)
r := getUpdatesResponse{
OK: true,
Result: []*models.Update{s.updates[s.updateIdx]},
}
s.updateIdx++
d, err := json.Marshal(r)
if err != nil {
panic(err)
}
_, err = rw.Write(d)
if err != nil {
panic(err)
}
}
func (s *serverMock) URL() string {
return s.s.URL
}
func newServerMock(token string) *serverMock {
s := &serverMock{
token: token,
custom: map[string]any{},
hooks: map[string]func([]byte) any{},
hooksCalls: map[string]int{},
}
s.s = httptest.NewServer(http.HandlerFunc(s.handler))
return s
}
func TestNew_error_getMe(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
_, err := rw.Write([]byte(`{"ok":false,"description":"err1","error_code":400}`))
if err != nil {
panic(err)
}
}))
defer server.Close()
_, err := New("xxx", WithServerURL(server.URL))
if err == nil {
t.Fatal("unexpected nil error")
}
if err.Error() != "error call getMe, bad request, err1" {
t.Fatalf("wrong error message %q", err.Error())
}
}
func TestNew_emptyToken(t *testing.T) {
_, err := New("")
if err == nil {
t.Fatalf("expect error %q", err)
}
if err.Error() != "empty token" {
t.Fatalf("exexpected error %q", err)
}
}
func TestNew(t *testing.T) {
s := newServerMock("xxx")
defer s.Close()
_, err := New("xxx", WithServerURL(s.URL()))
if err != nil {
t.Fatalf("unexpected error %q", err)
}
}
func TestBot_StartWebhook(t *testing.T) {
s := newServerMock("xxx")
defer s.Close()
b, err := New("xxx", WithServerURL(s.URL()))
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_Start(t *testing.T) {
s := newServerMock("xxx")
defer s.Close()
s.updates = append(s.updates, &models.Update{Message: &models.Message{ID: 42}})
b, err := New("xxx", WithServerURL(s.URL()))
if err != nil {
t.Fatalf("unexpected error %q", err)
}
var called bool
b.defaultHandlerFunc = func(ctx context.Context, bot *Bot, update *models.Update) {
if update.Message.ID != 42 {
t.Errorf("unexpected message id %d", update.Message.ID)
}
called = true
}
ctx, cancel := context.WithCancel(context.Background())
go b.Start(ctx)
time.Sleep(time.Millisecond * 100)
cancel()
time.Sleep(time.Millisecond * 100)
if !called {
t.Errorf("not called default handler")
}
}