]> git.giacomolli.uk - onechat/blob - whatsapp_test.go
Name timeouts for the operations they limit
[onechat] / whatsapp_test.go
1 package main
2
3 import (
4 "errors"
5 "os"
6 "path/filepath"
7 "strings"
8 "testing"
9 "testing/synctest"
10 "time"
11
12 "github.com/stretchr/testify/require"
13 "go.mau.fi/whatsmeow"
14 "go.mau.fi/whatsmeow/types"
15 "go.mau.fi/whatsmeow/types/events"
16 )
17
18 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
19 dir := t.TempDir()
20 whatsappTestSession(t, dir, true)
21
22 clock := newTestClock()
23 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
24 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
25
26 <-fake.connects
27 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
28
29 require.True(t, fake.Emit(&events.Connected{}))
30 require.Equal(t, "WhatsApp is linked and connected since 2026-01-01 12:00.", whatsapp.Status())
31
32 clock.now = clock.now.Add(20 * time.Minute)
33
34 require.True(t, fake.Emit(&events.Disconnected{}))
35
36 clock.now = clock.now.Add(time.Minute)
37
38 require.True(t, fake.Emit(&events.Disconnected{}))
39 require.Equal(t, "WhatsApp is linked and disconnected since 2026-01-01 12:20. The last connection started at 2026-01-01 12:00.", whatsapp.Status())
40 }
41
42 func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
43 synctest.Test(t, func(t *testing.T) {
44 test := whatsappRetryTest(t)
45 test.fake.connectErr = errors.New("network unavailable")
46 test.start(t)
47 synctest.Wait()
48
49 require.Equal(t, "WhatsApp is linked and disconnected since "+time.Now().Format(whatsappTimeLayout)+".", test.whatsapp.Status())
50 require.Equal(t, "<4>first connect failed, retrying: network unavailable\n", test.logs.String())
51 })
52 }
53
54 func TestWhatsAppRetriesTheFirstConnectionWithCappedBackoff(t *testing.T) {
55 synctest.Test(t, func(t *testing.T) {
56 test := whatsappRetryTest(t)
57 for range 10 {
58 test.fake.connectErrors = append(test.fake.connectErrors, errors.New("network unavailable"))
59 }
60
61 test.start(t)
62 synctest.Wait()
63 require.Len(t, test.fake.Connections(), 1)
64 require.True(t, test.fake.Emit(&events.Disconnected{}))
65 require.True(t, test.fake.Emit(&events.Disconnected{}))
66
67 delays := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 32 * time.Second, 64 * time.Second, 128 * time.Second, 256 * time.Second, 5 * time.Minute, 5 * time.Minute}
68
69 var outage time.Duration
70
71 for index, delay := range delays {
72 time.Sleep(delay - time.Nanosecond)
73 synctest.Wait()
74 require.Len(t, test.fake.Connections(), index+1)
75 time.Sleep(time.Nanosecond)
76 synctest.Wait()
77 require.Len(t, test.fake.Connections(), index+2)
78
79 outage += delay
80 }
81
82 times := test.fake.ConnectionTimes()
83 for index, delay := range delays {
84 require.Equal(t, delay, times[index+1].Sub(times[index]))
85 }
86
87 require.True(t, test.fake.Emit(&events.Connected{}))
88 require.True(t, test.fake.Emit(&events.OfflineSyncCompleted{}))
89 synctest.Wait()
90 time.Sleep(10 * time.Minute)
91 synctest.Wait()
92 require.Len(t, test.fake.Connections(), 11)
93 require.Equal(t, "<4>first connect failed, retrying: network unavailable\n<6>connected again after="+durationText(outage)+"\n", test.logs.String())
94 })
95 }
96
97 func TestWhatsAppFirstConnectionRetriesStopWhenContextEnds(t *testing.T) {
98 synctest.Test(t, func(t *testing.T) {
99 test := whatsappRetryTest(t)
100 test.fake.connectErr = errors.New("network unavailable")
101 test.start(t)
102 synctest.Wait()
103 time.Sleep(2 * time.Second)
104 synctest.Wait()
105 require.Len(t, test.fake.Connections(), 2)
106
107 test.cancel()
108 require.NoError(t, <-test.done)
109 time.Sleep(10 * time.Minute)
110 synctest.Wait()
111 require.Len(t, test.fake.Connections(), 2)
112 })
113 }
114
115 func TestWhatsAppLinkedPairRequestKeepsFirstConnectionRetries(t *testing.T) {
116 synctest.Test(t, func(t *testing.T) {
117 test := whatsappRetryTest(t)
118 test.fake.connectErr = errors.New("network unavailable")
119 test.start(t)
120 synctest.Wait()
121
122 answers := make(chan string, 1)
123 test.whatsapp.Command("pair 15550001111", func(text string) {
124 answers <- text
125 })
126 require.Equal(t, "WhatsApp is linked already. Run /whatsapp unlink first.", <-answers)
127 synctest.Wait()
128 test.fake.mutex.Lock()
129
130 test.fake.connectErr = nil
131 test.fake.mutex.Unlock()
132 time.Sleep(whatsappRetryDelay)
133 synctest.Wait()
134 require.Len(t, test.fake.Connections(), 2)
135 require.True(t, test.fake.Emit(&events.Connected{}))
136 require.True(t, test.fake.Emit(&events.OfflineSyncCompleted{}))
137 require.Contains(t, test.whatsapp.Status(), "linked and connected since")
138 time.Sleep(whatsappRetryLimit)
139 synctest.Wait()
140 require.Len(t, test.fake.Connections(), 2)
141 require.Equal(t, "<4>first connect failed, retrying: network unavailable\n<6>connected again after=2s\n", test.logs.String())
142 })
143 }
144
145 func TestWhatsAppFirstConnectionRetriesStopForLinkChanges(t *testing.T) {
146 testCases := []struct {
147 name string
148 stop func(test *WhatsAppRetryTest)
149 }{
150 {
151 name: "unlink",
152 stop: func(test *WhatsAppRetryTest) {
153 test.whatsapp.Command("unlink", func(_ string) {
154 })
155 },
156 },
157 {
158 name: "logout",
159 stop: func(test *WhatsAppRetryTest) {
160 test.fake.Emit(&events.LoggedOut{})
161 },
162 },
163 {
164 name: "permanent disconnect",
165 stop: func(test *WhatsAppRetryTest) {
166 test.fake.Emit(&events.StreamReplaced{})
167 },
168 },
169 }
170
171 for _, tc := range testCases {
172 t.Run(tc.name, func(t *testing.T) {
173 synctest.Test(t, func(t *testing.T) {
174 test := whatsappRetryTest(t)
175 test.fake.connectErr = errors.New("network unavailable")
176 test.start(t)
177 synctest.Wait()
178 tc.stop(test)
179 synctest.Wait()
180 time.Sleep(10 * time.Minute)
181 synctest.Wait()
182 require.Len(t, test.fake.Connections(), 1)
183 })
184 })
185 }
186 }
187
188 func TestWhatsAppPairsAfterFirstConnectionRetriesStop(t *testing.T) {
189 synctest.Test(t, func(t *testing.T) {
190 test := whatsappRetryTest(t)
191 test.fake.connectErr = errors.New("network unavailable")
192 test.start(t)
193 synctest.Wait()
194 test.whatsapp.Command("unlink", func(_ string) {
195 })
196 synctest.Wait()
197 require.False(t, test.whatsapp.isLinked())
198
199 test.fake.mutex.Lock()
200
201 test.fake.connectErr = nil
202 test.fake.mutex.Unlock()
203 test.whatsapp.Command("pair 15550001111", func(_ string) {
204 })
205
206 items := <-test.fake.pairings
207 items <- whatsmeow.QRChannelItem{Event: whatsmeow.QRChannelEventCode}
208
209 synctest.Wait()
210 require.True(t, test.fake.Emit(&events.PairSuccess{
211 ID: types.NewADJID(whatsappTestNumber, 0, 1),
212 LID: types.NewADJID(whatsappTestLID, 0, 1),
213 }))
214
215 items <- whatsmeow.QRChannelSuccess
216
217 synctest.Wait()
218 require.True(t, test.whatsapp.isLinked())
219 time.Sleep(10 * time.Minute)
220 synctest.Wait()
221 require.Len(t, test.fake.Connections(), 2)
222 require.Equal(t, []string{whatsappTestNumber}, test.fake.Phones())
223 })
224 }
225
226 func TestWhatsAppInboxFailureStopsFirstConnectionRetries(t *testing.T) {
227 synctest.Test(t, func(t *testing.T) {
228 test := whatsappRetryTest(t)
229 test.fake.connectErr = errors.New("network unavailable")
230 test.start(t)
231 synctest.Wait()
232
233 failure := errors.New("state write failed")
234 test.whatsapp.inbox.failures <- failure
235
236 require.ErrorIs(t, <-test.done, failure)
237 time.Sleep(10 * time.Minute)
238 synctest.Wait()
239 require.Len(t, test.fake.Connections(), 1)
240 })
241 }
242
243 func TestWhatsAppLongFirstConnectionOutageGivesOneNotice(t *testing.T) {
244 synctest.Test(t, func(t *testing.T) {
245 test := whatsappRetryTest(t)
246 test.fake.connectErr = errors.New("network unavailable")
247 test.start(t)
248 synctest.Wait()
249
250 since := time.Now().Format(whatsappTimeLayout)
251
252 time.Sleep(whatsappOutageNoticeDelay)
253 synctest.Wait()
254 require.Equal(t, 1, test.events.Count("notice"))
255 require.Equal(t, "WhatsApp is disconnected since "+since+". OneChat tries again.", test.events.Last("notice"))
256
257 time.Sleep(whatsappOutageNoticeDelay)
258 synctest.Wait()
259 require.Equal(t, 1, test.events.Count("notice"))
260 test.fake.mutex.Lock()
261
262 test.fake.connectErr = nil
263 test.fake.mutex.Unlock()
264 time.Sleep(whatsappRetryLimit)
265 synctest.Wait()
266 require.True(t, test.fake.Emit(&events.Connected{}))
267 require.True(t, test.fake.Emit(&events.OfflineSyncCompleted{}))
268 synctest.Wait()
269 require.Equal(t, 2, test.events.Count("notice"))
270 require.Equal(t, "WhatsApp is connected again.", test.events.Last("notice"))
271 })
272 }
273
274 func TestWhatsAppStartingRetriesDoNotDuplicateLibraryRetries(t *testing.T) {
275 dir := t.TempDir()
276 whatsappTestSession(t, dir, true)
277
278 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
279 client, ok := whatsappNewClient(whatsapp.device, whatsapp.handle).(*whatsmeow.Client)
280 require.True(t, ok)
281 require.False(t, client.InitialAutoReconnect)
282 require.True(t, client.EnableAutoReconnect)
283
284 device := whatsapp.container.NewDevice()
285 client, ok = whatsappNewClient(device, whatsapp.handle).(*whatsmeow.Client)
286 require.True(t, ok)
287 require.True(t, client.InitialAutoReconnect)
288 }
289
290 func TestWhatsAppLogsEachChangeOfTheConnectionOnce(t *testing.T) {
291 dir := t.TempDir()
292 whatsappTestSession(t, dir, true)
293
294 clock := newTestClock()
295 whatsapp, fake, logs := whatsappStartTest(t, dir, clock)
296 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
297
298 <-fake.connects
299 require.True(t, fake.Emit(&events.Connected{}))
300
301 clock.now = clock.now.Add(time.Minute)
302
303 require.True(t, fake.Emit(&events.Disconnected{}))
304
305 clock.now = clock.now.Add(time.Minute)
306
307 require.True(t, fake.Emit(&events.Disconnected{}))
308
309 clock.now = clock.now.Add(25 * time.Second)
310
311 require.True(t, fake.Emit(&events.Connected{}))
312
313 require.Equal(t, []string{
314 "<6>connected",
315 "<4>disconnected, retrying",
316 "<6>connected again after=1m25s",
317 }, strings.Split(strings.TrimSuffix(logs.String(), "\n"), "\n"))
318 require.NotContains(t, logs.String(), whatsappTestNumber)
319 require.NotContains(t, logs.String(), whatsappTestLID)
320 }
321
322 func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
323 testCases := []struct {
324 name string
325 session func(t *testing.T, dir string)
326 }{
327 {
328 name: "no session file",
329 session: func(_ *testing.T, _ string) {
330 },
331 },
332 {
333 name: "a session of a pairing that did not end",
334 session: func(t *testing.T, dir string) {
335 whatsappTestSession(t, dir, false)
336 },
337 },
338 }
339
340 for _, tc := range testCases {
341 t.Run(tc.name, func(t *testing.T) {
342 dir := t.TempDir()
343 tc.session(t, dir)
344
345 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
346 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
347 })
348 }
349 }
350
351 func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
352 dir := t.TempDir()
353 whatsappTestSession(t, dir, true)
354 require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
355
356 _, err := openWhatsApp(t.Context(), dir, time.Now, whatsappDiscardLog(), whatsappNewClient)
357 require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600")
358 }
359
360 func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) {
361 server := newModelFake(t)
362 telegram := newTelegramFake(t)
363 bot, _ := telegramStartTestBot(t, telegram)
364 socket := daemonStartTestWithBot(t, server, bot)
365 asking := terminalStartTestClient(t, socket)
366 other := terminalStartTestClient(t, socket)
367 asking.WaitFor(t, "[connected to OneChat]")
368 other.WaitFor(t, "[connected to OneChat]")
369
370 asking.Type("/whatsapp status")
371 asking.WaitFor(t, "WhatsApp is not linked.")
372 asking.Type(" /whatsapp unknown ")
373 asking.WaitFor(t, whatsappUsage)
374 asking.Type("/whatsapp pair 0123")
375 asking.WaitFor(t, "PHONE must be the number of your WhatsApp account")
376
377 telegram.Add(TelegramUpdate{
378 UpdateID: 1,
379 Message: telegramOwnerMessage("/whatsapp status"),
380 })
381
382 telegramWaitForSent(t, telegram, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.")
383 require.Len(t, telegram.Sent(), 1)
384 require.Equal(t, "[connected to OneChat]\n", other.Output())
385 require.Zero(t, server.Calls())
386 }
387
388 func TestWhatsAppPairsWithACode(t *testing.T) {
389 dir := t.TempDir()
390 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
391 server := newModelFake(t)
392 socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
393 asking := terminalStartTestClient(t, socket)
394 other := terminalStartTestClient(t, socket)
395 asking.WaitFor(t, "[connected to OneChat]")
396 other.WaitFor(t, "[connected to OneChat]")
397
398 asking.Type("/whatsapp pair +1 555-000-1111")
399
400 items := <-fake.pairings
401 items <- whatsmeow.QRChannelItem{
402 Event: whatsmeow.QRChannelEventCode,
403 }
404
405 asking.WaitFor(t, whatsappPairSteps+"\n"+whatsappTestCode+"\n")
406 require.True(t, fake.Emit(&events.PairSuccess{
407 ID: types.NewADJID(whatsappTestNumber, 0, 1),
408 LID: types.NewADJID(whatsappTestLID, 0, 1),
409 }))
410
411 items <- whatsmeow.QRChannelSuccess
412
413 asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
414
415 // The library connects again after the link with the context of the
416 // connection, so the end of the pairing must not end it.
417 connections := fake.Connections()
418 require.Len(t, connections, 1)
419 require.Never(t, func() bool {
420 return connections[0].Err() != nil
421 }, 200*time.Millisecond, time.Millisecond)
422
423 require.Equal(t, []string{whatsappTestNumber}, fake.Phones())
424 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
425 require.Equal(t, "[connected to OneChat]\n", other.Output())
426 require.Zero(t, server.Calls())
427 require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory))
428 require.Equal(t, "<6>linked\n", logs.String())
429
430 info, err := os.Stat(filepath.Join(dir, whatsappDirName))
431 require.NoError(t, err)
432 require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
433
434 info, err = os.Stat(filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
435 require.NoError(t, err)
436 require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
437 }
438
439 func TestWhatsAppPairingCodeIsATelegramMessageAlone(t *testing.T) {
440 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
441 telegram := newTelegramFake(t)
442 bot, _ := telegramStartTestBot(t, telegram)
443 daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
444
445 telegram.Add(TelegramUpdate{
446 UpdateID: 1,
447 Message: telegramOwnerMessage("/whatsapp pair 15550001111"),
448 })
449
450 items := <-fake.pairings
451 items <- whatsmeow.QRChannelItem{
452 Event: whatsmeow.QRChannelEventCode,
453 }
454
455 telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode)
456 }
457
458 func TestWhatsAppPairingEnds(t *testing.T) {
459 testCases := []struct {
460 name string
461 end func(items chan whatsmeow.QRChannelItem)
462 answer string
463 }{
464 {
465 name: "the code expires",
466 end: func(items chan whatsmeow.QRChannelItem) {
467 items <- whatsmeow.QRChannelTimeout
468 },
469 answer: whatsappPairExpired,
470 },
471 {
472 name: "the library closes the pairing",
473 end: func(items chan whatsmeow.QRChannelItem) {
474 close(items)
475 },
476 answer: whatsappPairExpired,
477 },
478 {
479 name: "the pairing fails",
480 end: func(items chan whatsmeow.QRChannelItem) {
481 items <- whatsmeow.QRChannelItem{
482 Event: whatsmeow.QRChannelEventError,
483 Error: errors.New("bad handshake"),
484 }
485 },
486 answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.",
487 },
488 }
489
490 for _, tc := range testCases {
491 t.Run(tc.name, func(t *testing.T) {
492 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
493 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
494 client := terminalStartTestClient(t, socket)
495 client.Type("/whatsapp pair 15550001111")
496
497 items := <-fake.pairings
498 items <- whatsmeow.QRChannelItem{
499 Event: whatsmeow.QRChannelEventCode,
500 }
501
502 client.WaitFor(t, whatsappTestCode)
503 tc.end(items)
504 client.WaitFor(t, tc.answer)
505 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
506 })
507 }
508 }
509
510 func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) {
511 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
512 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
513 client := terminalStartTestClient(t, socket)
514
515 client.Type("/whatsapp pair 15550001111")
516 <-fake.pairings
517 client.Type("/whatsapp pair 15550002222")
518
519 items := <-fake.pairings
520 items <- whatsmeow.QRChannelItem{
521 Event: whatsmeow.QRChannelEventCode,
522 }
523
524 client.WaitFor(t, whatsappTestCode)
525 require.Equal(t, []string{"15550002222"}, fake.Phones())
526 require.NotContains(t, client.Output(), "did not start the pairing")
527 }
528
529 func TestWhatsAppPairWhenLinked(t *testing.T) {
530 dir := t.TempDir()
531 whatsappTestSession(t, dir, true)
532
533 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
534 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
535 client := terminalStartTestClient(t, socket)
536
537 client.Type("/whatsapp pair 15550001111")
538 client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.")
539 }
540
541 func TestWhatsAppUnlink(t *testing.T) {
542 testCases := []struct {
543 name string
544 logoutErr error
545 answer string
546 }{
547 {
548 name: "with a logout",
549 answer: "WhatsApp is unlinked.",
550 },
551 {
552 name: "with no logout",
553 logoutErr: errors.New("not connected"),
554 answer: "WhatsApp is unlinked here, but the phone did not get the logout. In WhatsApp on your phone, open Linked devices and remove the device.",
555 },
556 }
557
558 for _, tc := range testCases {
559 t.Run(tc.name, func(t *testing.T) {
560 dir := t.TempDir()
561 whatsappTestSession(t, dir, true)
562
563 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
564 fake.logoutErr = tc.logoutErr
565 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
566 client := terminalStartTestClient(t, socket)
567
568 <-fake.connects
569
570 client.Type("/whatsapp unlink")
571 client.WaitFor(t, tc.answer)
572 require.Equal(t, 1, fake.Logouts())
573 require.Equal(t, "<6>unlinked\n", logs.String())
574 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
575 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
576 require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory))
577
578 client.Type("/whatsapp unlink")
579 client.WaitFor(t, "WhatsApp is not linked.\n")
580 })
581 }
582 }
583
584 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
585 dir := t.TempDir()
586 whatsappTestSession(t, dir, true)
587
588 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
589 telegram := newTelegramFake(t)
590 bot, _ := telegramStartTestBot(t, telegram)
591 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
592 client := terminalStartTestClient(t, socket)
593 client.WaitFor(t, "[connected to OneChat]")
594 <-fake.connects
595
596 require.True(t, fake.Emit(&events.LoggedOut{}))
597
598 notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again."
599 client.WaitFor(t, notice)
600 telegramWaitForSent(t, telegram, notice)
601 require.Equal(t, "<3>logged out by the phone, run /whatsapp pair PHONE\n", logs.String())
602 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
603 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
604 require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory))
605 }
606
607 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
608 synctest.Test(t, func(t *testing.T) {
609 test := whatsappRetryTest(t)
610 test.start(t)
611 synctest.Wait()
612
613 require.True(t, test.fake.Emit(&events.Connected{}))
614 require.True(t, test.fake.Emit(&events.Disconnected{}))
615 require.True(t, test.fake.Emit(&events.Connected{}))
616 time.Sleep(whatsappOutageNoticeDelay + time.Second)
617 synctest.Wait()
618 require.Zero(t, test.events.Count("notice"))
619
620 require.True(t, test.fake.Emit(&events.Disconnected{}))
621 require.True(t, test.fake.Emit(&events.Disconnected{}))
622 time.Sleep(whatsappOutageNoticeDelay)
623 synctest.Wait()
624 require.Equal(t, 1, test.events.Count("notice"))
625 require.Contains(t, test.events.Last("notice"), "OneChat tries again.")
626 require.True(t, test.fake.Emit(&events.Disconnected{}))
627 time.Sleep(whatsappOutageNoticeDelay)
628 synctest.Wait()
629 require.Equal(t, 1, test.events.Count("notice"))
630
631 require.True(t, test.fake.Emit(&events.Connected{}))
632 require.Equal(t, 2, test.events.Count("notice"))
633 require.Equal(t, "WhatsApp is connected again.", test.events.Last("notice"))
634 })
635 }
636
637 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
638 dir := t.TempDir()
639 whatsappTestSession(t, dir, true)
640
641 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
642 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
643 client := terminalStartTestClient(t, socket)
644 client.WaitFor(t, "[connected to OneChat]")
645 <-fake.connects
646
647 require.True(t, fake.Emit(&events.StreamReplaced{}))
648 client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.")
649 require.Equal(t, "<3>disconnected for good, restart to retry: stream replaced\n", logs.String())
650 }
651
652 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
653 dir := t.TempDir()
654 whatsappTestSession(t, dir, true)
655
656 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
657 fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid")
658
659 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
660 <-fake.connects
661
662 require.Eventually(t, func() bool {
663 return logs.String() != ""
664 }, 10*time.Second, time.Millisecond)
665 require.Equal(t, "<4>first connect failed, retrying: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String())
666 }
667
668 func TestWhatsAppPhone(t *testing.T) {
669 testCases := []struct {
670 name string
671 phone string
672 valid bool
673 }{
674 {
675 name: "a number with a plus and dashes",
676 phone: "+1-555-000-1111",
677 valid: true,
678 },
679 {
680 name: "a number with no country code",
681 phone: "0115550001111",
682 valid: false,
683 },
684 {
685 name: "a short number",
686 phone: "123456",
687 valid: false,
688 },
689 {
690 name: "a long number",
691 phone: "1234567890123456",
692 valid: false,
693 },
694 {
695 name: "a number with letters",
696 phone: "1555ABC1111",
697 valid: false,
698 },
699 }
700
701 for _, tc := range testCases {
702 t.Run(tc.name, func(t *testing.T) {
703 _, valid := whatsappPhone(tc.phone)
704 require.Equal(t, tc.valid, valid)
705 })
706 }
707 }
708
709 func TestWhatsAppCommandArgs(t *testing.T) {
710 testCases := []struct {
711 name string
712 line string
713 args string
714 found bool
715 }{
716 {
717 name: "a command with its arguments",
718 line: " /whatsapp pair +1 555 ",
719 args: "pair +1 555",
720 found: true,
721 },
722 {
723 name: "the command alone",
724 line: "/whatsapp",
725 args: "",
726 found: true,
727 },
728 {
729 name: "a word that starts with the command",
730 line: "/whatsappstatus",
731 args: "",
732 found: false,
733 },
734 {
735 name: "a message that names the command",
736 line: "what does /whatsapp status do?",
737 args: "",
738 found: false,
739 },
740 }
741
742 for _, tc := range testCases {
743 t.Run(tc.name, func(t *testing.T) {
744 args, found := whatsappCommandArgs(tc.line)
745 require.Equal(t, tc.args, args)
746 require.Equal(t, tc.found, found)
747 })
748 }
749 }
750
751 func TestSubagentHasNoWhatsAppTools(t *testing.T) {
752 box := &Toolbox{}
753 require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`))
754 require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`))
755 }