]> git.giacomolli.uk - onechat/blob - whatsapp_fake_helper_test.go
Check error handling and common Go mistakes
[onechat] / whatsapp_fake_helper_test.go
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "log"
8 "os"
9 "path/filepath"
10 "slices"
11 "sync"
12 "testing"
13 "time"
14
15 "github.com/stretchr/testify/require"
16 "go.mau.fi/whatsmeow"
17 waAdv "go.mau.fi/whatsmeow/proto/waAdv"
18 "go.mau.fi/whatsmeow/proto/waE2E"
19 "go.mau.fi/whatsmeow/store"
20 "go.mau.fi/whatsmeow/store/sqlstore"
21 "go.mau.fi/whatsmeow/types"
22 "go.mau.fi/whatsmeow/types/events"
23 waLog "go.mau.fi/whatsmeow/util/log"
24 )
25
26 const (
27 // whatsappTestNumber is the phone number of the own account in the
28 // tests. It is a number for fiction.
29 whatsappTestNumber = "15550001111"
30
31 // whatsappTestLID is the LID of the own account in the tests.
32 whatsappTestLID = "987654321012345"
33
34 // whatsappTestCode is the pairing code of the fake.
35 whatsappTestCode = "ABCD-EFGH"
36 )
37
38 var (
39 // whatsappTestOwn is the own account in the tests.
40 whatsappTestOwn = types.NewJID(whatsappTestNumber, types.DefaultUserServer)
41
42 // whatsappTestAna is a contact in the tests.
43 whatsappTestAna = types.NewJID("15550002222", types.DefaultUserServer)
44
45 // whatsappTestBruno is a member of the test group.
46 whatsappTestBruno = types.NewJID("15550003333", types.DefaultUserServer)
47
48 // whatsappTestFamily is the test group.
49 whatsappTestFamily = types.NewJID("120363000000000001", types.GroupServer)
50
51 // whatsappTestChat is the private chat with whatsappTestAna.
52 whatsappTestChat = WhatsAppChat{
53 ID: whatsappTestAna.String(),
54 Name: "Ana Souza",
55 }
56
57 // whatsappTestSendTime is the time of the sends of the fake.
58 whatsappTestSendTime = time.Date(2026, 1, 1, 12, 5, 0, 0, time.UTC)
59
60 // whatsappTestGroup is the chat of whatsappTestFamily.
61 whatsappTestGroup = WhatsAppChat{
62 ID: whatsappTestFamily.String(),
63 Name: "Family",
64 Group: true,
65 }
66 )
67
68 // WhatsAppFake is a fake WhatsApp client. It keeps the event handler that the
69 // daemon gives it, and Emit gives events to the handler, as the library does.
70 // Each connection keeps its context and sends to connects, and each pairing
71 // sends its channel to pairings, so that the test gives the items of the
72 // pairing. A connection takes its error from connectErrors, then connectErr. A
73 // logout fails with logoutErr, and a send with sendErr. groups are the groups
74 // of the account. A send that does not fail gets the time whatsappTestSendTime.
75 type WhatsAppFake struct {
76 connects chan struct{}
77 pairings chan chan whatsmeow.QRChannelItem
78
79 mutex sync.Mutex
80 handle func(event any) bool
81 connectErr error
82 connectErrors []error
83 connectTimes []time.Time
84 logoutErr error
85 groups []*types.GroupInfo
86 sendErr error
87 phones []string
88 logouts int
89 sent []WhatsAppFakeSend
90 connections []context.Context
91 }
92
93 // ConnectContext keeps ctx and tells the test that the daemon connected.
94 func (f *WhatsAppFake) ConnectContext(ctx context.Context) error {
95 f.mutex.Lock()
96 f.connections = append(f.connections, ctx)
97 f.connectTimes = append(f.connectTimes, time.Now())
98 f.mutex.Unlock()
99
100 f.connects <- struct{}{}
101
102 f.mutex.Lock()
103 defer f.mutex.Unlock()
104
105 if len(f.connectErrors) > 0 {
106 err := f.connectErrors[0]
107 f.connectErrors = f.connectErrors[1:]
108 return err
109 }
110
111 return f.connectErr
112 }
113
114 // Connections returns the contexts of the connections, in order.
115 func (f *WhatsAppFake) Connections() []context.Context {
116 f.mutex.Lock()
117 defer f.mutex.Unlock()
118
119 return slices.Clone(f.connections)
120 }
121
122 // ConnectionTimes returns the time of each connection call, in order.
123 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
124 f.mutex.Lock()
125 defer f.mutex.Unlock()
126
127 return slices.Clone(f.connectTimes)
128 }
129
130 // Disconnect does nothing.
131 func (f *WhatsAppFake) Disconnect() {
132 }
133
134 // GetQRChannel gives a new channel of pairing items to the test.
135 func (f *WhatsAppFake) GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error) {
136 items := make(chan whatsmeow.QRChannelItem, 8)
137 f.pairings <- items
138
139 return items, nil
140 }
141
142 // PairPhone keeps phone and returns whatsappTestCode.
143 func (f *WhatsAppFake) PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error) {
144 f.mutex.Lock()
145 defer f.mutex.Unlock()
146
147 f.phones = append(f.phones, phone)
148
149 return whatsappTestCode, nil
150 }
151
152 // Logout counts the logouts and returns logoutErr.
153 func (f *WhatsAppFake) Logout(ctx context.Context) error {
154 f.mutex.Lock()
155 defer f.mutex.Unlock()
156
157 f.logouts++
158
159 return f.logoutErr
160 }
161
162 // GetJoinedGroups returns groups.
163 func (f *WhatsAppFake) GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error) {
164 f.mutex.Lock()
165 defer f.mutex.Unlock()
166
167 return f.groups, nil
168 }
169
170 // GenerateMessageID returns a new message ID.
171 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
172 f.mutex.Lock()
173 defer f.mutex.Unlock()
174
175 return fmt.Sprintf("MSG%d", len(f.sent)+1)
176 }
177
178 // SendMessage keeps the send and returns sendErr.
179 func (f *WhatsAppFake) SendMessage(ctx context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
180 f.mutex.Lock()
181 defer f.mutex.Unlock()
182
183 f.sent = append(f.sent, WhatsAppFakeSend{
184 to: to.String(),
185 text: message.GetConversation(),
186 id: extra[0].ID,
187 })
188
189 if f.sendErr != nil {
190 return whatsmeow.SendResponse{}, f.sendErr
191 }
192
193 return whatsmeow.SendResponse{
194 Timestamp: whatsappTestSendTime,
195 }, nil
196 }
197
198 // Sent returns the sends.
199 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
200 f.mutex.Lock()
201 defer f.mutex.Unlock()
202
203 return slices.Clone(f.sent)
204 }
205
206 // Phones returns the phone numbers of the pairings.
207 func (f *WhatsAppFake) Phones() []string {
208 f.mutex.Lock()
209 defer f.mutex.Unlock()
210
211 return append([]string{}, f.phones...)
212 }
213
214 // Logouts returns the number of logouts.
215 func (f *WhatsAppFake) Logouts() int {
216 f.mutex.Lock()
217 defer f.mutex.Unlock()
218
219 return f.logouts
220 }
221
222 // Emit gives event to the handler of the daemon and returns its answer.
223 func (f *WhatsAppFake) Emit(event any) bool {
224 f.mutex.Lock()
225 handle := f.handle
226 f.mutex.Unlock()
227
228 return handle(event)
229 }
230
231 // newClient keeps handle and returns the fake as the client of device.
232 func (f *WhatsAppFake) newClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
233 f.mutex.Lock()
234 defer f.mutex.Unlock()
235
236 f.handle = handle
237
238 return f
239 }
240
241 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
242 // ID.
243 type WhatsAppFakeSend struct {
244 to string
245 text string
246 id string
247 }
248
249 // whatsappStartTest opens the WhatsApp of the data directory dir with a fake
250 // client and the test clock, and closes it at the end of the test. The daemon
251 // log goes to the returned buffer.
252 func whatsappStartTest(t *testing.T, dir string, clock *TestClock) (*WhatsApp, *WhatsAppFake, *SyncBuffer) {
253 t.Helper()
254
255 fake := &WhatsAppFake{
256 connects: make(chan struct{}, 16),
257 pairings: make(chan chan whatsmeow.QRChannelItem, 16),
258 }
259
260 logs := &SyncBuffer{}
261 whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, log.New(logs, "", 0), fake.newClient)
262 require.NoError(t, err)
263
264 t.Cleanup(func() {
265 require.NoError(t, whatsapp.Close())
266 })
267
268 return whatsapp, fake, logs
269 }
270
271 // whatsappTestSession writes a session database with mode 0600 to the data
272 // directory dir. When linked is true, it holds a device linked to
273 // whatsappTestNumber and whatsappTestLID, and else no device.
274 func whatsappTestSession(t *testing.T, dir string, linked bool) {
275 t.Helper()
276
277 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
278 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
279 require.NoError(t, os.WriteFile(path, nil, 0o600))
280
281 address, err := whatsappSessionAddress(path)
282 require.NoError(t, err)
283
284 container, err := sqlstore.New(t.Context(), "sqlite", address, waLog.Noop)
285 require.NoError(t, err)
286
287 if linked {
288 device := container.NewDevice()
289 jid := types.NewADJID(whatsappTestNumber, 0, 1)
290 device.ID = &jid
291 device.LID = types.NewADJID(whatsappTestLID, 0, 1)
292 device.LID.Server = types.HiddenUserServer
293 device.Account = &waAdv.ADVSignedDeviceIdentity{
294 Details: []byte{},
295 AccountSignature: make([]byte, 64),
296 AccountSignatureKey: make([]byte, 32),
297 DeviceSignature: make([]byte, 64),
298 }
299 require.NoError(t, device.Save(t.Context()))
300 }
301
302 require.NoError(t, container.Close())
303 }
304
305 // whatsappDiscardLog is a logger for a WhatsApp whose log a test does not read.
306 func whatsappDiscardLog() *log.Logger {
307 return log.New(io.Discard, "", 0)
308 }
309
310 // whatsappTestMessage returns the event of the text message id of sender in
311 // chat at the time at. A sender with whatsappTestNumber is the user.
312 func whatsappTestMessage(chat, sender types.JID, id, text string, at time.Time) *events.Message {
313 return &events.Message{
314 Info: types.MessageInfo{
315 MessageSource: types.MessageSource{
316 Chat: chat,
317 Sender: sender,
318 IsFromMe: sender.User == whatsappTestNumber,
319 IsGroup: chat.Server == types.GroupServer,
320 },
321 ID: id,
322 Timestamp: at,
323 },
324 Message: &waE2E.Message{
325 Conversation: new(text),
326 },
327 }
328 }
329
330 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
331 // after the log holds at least one message.
332 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
333 t.Helper()
334
335 require.Eventually(t, func() bool {
336 return memory.Len() > 0
337 }, 10*time.Second, time.Millisecond)
338
339 var texts []string
340 for id := range memory.Len() {
341 message, err := memory.Message(id)
342 require.NoError(t, err)
343
344 texts = append(texts, message.Text)
345 }
346
347 return texts
348 }
349
350 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
351 // directory, with a quiet time of 50 ms for its batches.
352 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
353 t.Helper()
354
355 dir := t.TempDir()
356 whatsappTestSession(t, dir, true)
357 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
358 whatsapp.state.quiet = 50 * time.Millisecond
359
360 return whatsapp, fake
361 }
362
363 // whatsappTestConnect waits for the connection of the daemon and gives it the
364 // events of a connection with an empty catch-up.
365 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
366 t.Helper()
367
368 <-fake.connects
369 require.True(t, fake.Emit(&events.Connected{}))
370 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
371 }
372
373 // whatsappTestContacts puts the contacts of the tests into the session of
374 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
375 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
376 t.Helper()
377
378 contacts := whatsapp.device.Contacts
379 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
380 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
381 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
382 require.NoError(t, err)
383 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))
384 }