]> git.giacomolli.uk - onechat/blob - whatsapp_fake_helper_test.go
Separate returns from longer statement blocks
[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
109 return err
110 }
111
112 return f.connectErr
113 }
114
115 // Connections returns the contexts of the connections, in order.
116 func (f *WhatsAppFake) Connections() []context.Context {
117 f.mutex.Lock()
118 defer f.mutex.Unlock()
119
120 return slices.Clone(f.connections)
121 }
122
123 // ConnectionTimes returns the time of each connection call, in order.
124 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
125 f.mutex.Lock()
126 defer f.mutex.Unlock()
127
128 return slices.Clone(f.connectTimes)
129 }
130
131 // Disconnect does nothing.
132 func (f *WhatsAppFake) Disconnect() {
133 }
134
135 // GetQRChannel gives a new channel of pairing items to the test.
136 func (f *WhatsAppFake) GetQRChannel(_ context.Context) (<-chan whatsmeow.QRChannelItem, error) {
137 items := make(chan whatsmeow.QRChannelItem, 8)
138 f.pairings <- items
139
140 return items, nil
141 }
142
143 // PairPhone keeps phone and returns whatsappTestCode.
144 func (f *WhatsAppFake) PairPhone(_ context.Context, phone string, _ bool, _ whatsmeow.PairClientType, _ string) (string, error) {
145 f.mutex.Lock()
146 defer f.mutex.Unlock()
147
148 f.phones = append(f.phones, phone)
149
150 return whatsappTestCode, nil
151 }
152
153 // Logout counts the logouts and returns logoutErr.
154 func (f *WhatsAppFake) Logout(_ context.Context) error {
155 f.mutex.Lock()
156 defer f.mutex.Unlock()
157
158 f.logouts++
159
160 return f.logoutErr
161 }
162
163 // GetJoinedGroups returns groups.
164 func (f *WhatsAppFake) GetJoinedGroups(_ context.Context) ([]*types.GroupInfo, error) {
165 f.mutex.Lock()
166 defer f.mutex.Unlock()
167
168 return f.groups, nil
169 }
170
171 // GenerateMessageID returns a new message ID.
172 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
173 f.mutex.Lock()
174 defer f.mutex.Unlock()
175
176 return fmt.Sprintf("MSG%d", len(f.sent)+1)
177 }
178
179 // SendMessage keeps the send and returns sendErr.
180 func (f *WhatsAppFake) SendMessage(_ context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
181 f.mutex.Lock()
182 defer f.mutex.Unlock()
183
184 f.sent = append(f.sent, WhatsAppFakeSend{
185 to: to.String(),
186 text: message.GetConversation(),
187 id: extra[0].ID,
188 })
189
190 if f.sendErr != nil {
191 return whatsmeow.SendResponse{}, f.sendErr
192 }
193
194 return whatsmeow.SendResponse{
195 Timestamp: whatsappTestSendTime,
196 }, nil
197 }
198
199 // Sent returns the sends.
200 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
201 f.mutex.Lock()
202 defer f.mutex.Unlock()
203
204 return slices.Clone(f.sent)
205 }
206
207 // Phones returns the phone numbers of the pairings.
208 func (f *WhatsAppFake) Phones() []string {
209 f.mutex.Lock()
210 defer f.mutex.Unlock()
211
212 return append([]string{}, f.phones...)
213 }
214
215 // Logouts returns the number of logouts.
216 func (f *WhatsAppFake) Logouts() int {
217 f.mutex.Lock()
218 defer f.mutex.Unlock()
219
220 return f.logouts
221 }
222
223 // Emit gives event to the handler of the daemon and returns its answer.
224 func (f *WhatsAppFake) Emit(event any) bool {
225 f.mutex.Lock()
226 handle := f.handle
227 f.mutex.Unlock()
228
229 return handle(event)
230 }
231
232 // newClient keeps handle and returns the fake as the client of device.
233 func (f *WhatsAppFake) newClient(_ *store.Device, handle func(event any) bool) WhatsAppClient {
234 f.mutex.Lock()
235 defer f.mutex.Unlock()
236
237 f.handle = handle
238
239 return f
240 }
241
242 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
243 // ID.
244 type WhatsAppFakeSend struct {
245 to string
246 text string
247 id string
248 }
249
250 // whatsappStartTest opens the WhatsApp of the data directory dir with a fake
251 // client and the test clock, and closes it at the end of the test. The daemon
252 // log goes to the returned buffer.
253 func whatsappStartTest(t *testing.T, dir string, clock *TestClock) (*WhatsApp, *WhatsAppFake, *SyncBuffer) {
254 t.Helper()
255
256 fake := &WhatsAppFake{
257 connects: make(chan struct{}, 16),
258 pairings: make(chan chan whatsmeow.QRChannelItem, 16),
259 }
260
261 logs := &SyncBuffer{}
262 whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, log.New(logs, "", 0), fake.newClient)
263 require.NoError(t, err)
264
265 t.Cleanup(func() {
266 require.NoError(t, whatsapp.Close())
267 })
268
269 return whatsapp, fake, logs
270 }
271
272 // whatsappTestSession writes a session database with mode 0600 to the data
273 // directory dir. When linked is true, it holds a device linked to
274 // whatsappTestNumber and whatsappTestLID, and else no device.
275 func whatsappTestSession(t *testing.T, dir string, linked bool) {
276 t.Helper()
277
278 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
279 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
280 require.NoError(t, os.WriteFile(path, nil, 0o600))
281
282 address, err := whatsappSessionAddress(path)
283 require.NoError(t, err)
284
285 container, err := sqlstore.New(t.Context(), "sqlite", address, waLog.Noop)
286 require.NoError(t, err)
287
288 if linked {
289 device := container.NewDevice()
290 jid := types.NewADJID(whatsappTestNumber, 0, 1)
291 device.ID = &jid
292 device.LID = types.NewADJID(whatsappTestLID, 0, 1)
293 device.LID.Server = types.HiddenUserServer
294 device.Account = &waAdv.ADVSignedDeviceIdentity{
295 Details: []byte{},
296 AccountSignature: make([]byte, 64),
297 AccountSignatureKey: make([]byte, 32),
298 DeviceSignature: make([]byte, 64),
299 }
300 require.NoError(t, device.Save(t.Context()))
301 }
302
303 require.NoError(t, container.Close())
304 }
305
306 // whatsappDiscardLog is a logger for a WhatsApp whose log a test does not read.
307 func whatsappDiscardLog() *log.Logger {
308 return log.New(io.Discard, "", 0)
309 }
310
311 // whatsappTestMessage returns the event of the text message id of sender in
312 // chat at the time at. A sender with whatsappTestNumber is the user.
313 func whatsappTestMessage(chat, sender types.JID, id, text string, at time.Time) *events.Message {
314 return &events.Message{
315 Info: types.MessageInfo{
316 MessageSource: types.MessageSource{
317 Chat: chat,
318 Sender: sender,
319 IsFromMe: sender.User == whatsappTestNumber,
320 IsGroup: chat.Server == types.GroupServer,
321 },
322 ID: id,
323 Timestamp: at,
324 },
325 Message: &waE2E.Message{
326 Conversation: new(text),
327 },
328 }
329 }
330
331 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
332 // after the log holds at least one message.
333 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
334 t.Helper()
335
336 require.Eventually(t, func() bool {
337 return memory.Len() > 0
338 }, 10*time.Second, time.Millisecond)
339
340 var texts []string
341 for id := range memory.Len() {
342 message, err := memory.Message(id)
343 require.NoError(t, err)
344
345 texts = append(texts, message.Text)
346 }
347
348 return texts
349 }
350
351 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
352 // directory, with a quiet time of 50 ms for its batches.
353 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
354 t.Helper()
355
356 dir := t.TempDir()
357 whatsappTestSession(t, dir, true)
358 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
359 whatsapp.state.quiet = 50 * time.Millisecond
360
361 return whatsapp, fake
362 }
363
364 // whatsappTestConnect waits for the connection of the daemon and gives it the
365 // events of a connection with an empty catch-up.
366 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
367 t.Helper()
368
369 <-fake.connects
370 require.True(t, fake.Emit(&events.Connected{}))
371 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
372 }
373
374 // whatsappTestContacts puts the contacts of the tests into the session of
375 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
376 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
377 t.Helper()
378
379 contacts := whatsapp.device.Contacts
380 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
381 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
382 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
383 require.NoError(t, err)
384 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))
385 }