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