]> git.giacomolli.uk - onechat/blob - whatsapp_test.go
Link WhatsApp with a pairing code
[onechat] / whatsapp_test.go
1 package main
2
3 import (
4 "errors"
5 "os"
6 "path/filepath"
7 "strings"
8 "testing"
9 "time"
10
11 "github.com/stretchr/testify/require"
12 "go.mau.fi/whatsmeow"
13 "go.mau.fi/whatsmeow/types"
14 "go.mau.fi/whatsmeow/types/events"
15 )
16
17 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
18 dir := t.TempDir()
19 whatsappTestSession(t, dir, true)
20 clock := newTestClock()
21 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
22 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
23
24 <-fake.connects
25 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
26
27 require.True(t, fake.Emit(&events.Connected{}))
28 require.Equal(t, "WhatsApp is linked and connected since 2026-01-01 12:00.", whatsapp.Status())
29
30 clock.now = clock.now.Add(20 * time.Minute)
31 require.True(t, fake.Emit(&events.Disconnected{}))
32 clock.now = clock.now.Add(time.Minute)
33 require.True(t, fake.Emit(&events.Disconnected{}))
34 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())
35 }
36
37 func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
38 dir := t.TempDir()
39 whatsappTestSession(t, dir, true)
40 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
41 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
42
43 <-fake.connects
44 require.True(t, fake.Emit(&events.Disconnected{}))
45 require.Equal(t, "WhatsApp is linked and disconnected since 2026-01-01 12:00.", whatsapp.Status())
46 }
47
48 func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
49 testCases := []struct {
50 name string
51 session func(t *testing.T, dir string)
52 }{
53 {
54 name: "no session file",
55 session: func(t *testing.T, dir string) {
56 },
57 },
58 {
59 name: "a session of a pairing that did not end",
60 session: func(t *testing.T, dir string) {
61 whatsappTestSession(t, dir, false)
62 },
63 },
64 }
65
66 for _, tc := range testCases {
67 t.Run(tc.name, func(t *testing.T) {
68 dir := t.TempDir()
69 tc.session(t, dir)
70 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
71 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
72 })
73 }
74 }
75
76 func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
77 dir := t.TempDir()
78 whatsappTestSession(t, dir, true)
79 require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
80
81 _, err := openWhatsApp(t.Context(), dir, time.Now, whatsappDiscardLog(), whatsappNewClient)
82 require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600")
83 }
84
85 func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) {
86 server := newModelFake(t)
87 telegram := newTelegramFake(t)
88 bot, _ := telegramStartTestBot(t, telegram)
89 socket := daemonStartTestWithBot(t, server, bot)
90 asking := terminalStartTestClient(t, socket)
91 other := terminalStartTestClient(t, socket)
92 asking.WaitFor(t, "[connected to OneChat]")
93 other.WaitFor(t, "[connected to OneChat]")
94
95 asking.Type("/whatsapp status")
96 asking.WaitFor(t, "WhatsApp is not linked.")
97 asking.Type(" /whatsapp unknown ")
98 asking.WaitFor(t, whatsappUsage)
99 asking.Type("/whatsapp pair 0123")
100 asking.WaitFor(t, "PHONE must be the number of your WhatsApp account")
101
102 telegram.Add(TelegramUpdate{
103 UpdateID: 1,
104 Message: telegramOwnerMessage("/whatsapp status"),
105 })
106
107 telegramWaitForSent(t, telegram, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.")
108 require.Len(t, telegram.Sent(), 1)
109 require.Equal(t, "[connected to OneChat]\n", other.Output())
110 require.Zero(t, server.Calls())
111 }
112
113 func TestWhatsAppPairsWithACode(t *testing.T) {
114 dir := t.TempDir()
115 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
116 server := newModelFake(t)
117 socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
118 asking := terminalStartTestClient(t, socket)
119 other := terminalStartTestClient(t, socket)
120 asking.WaitFor(t, "[connected to OneChat]")
121 other.WaitFor(t, "[connected to OneChat]")
122
123 asking.Type("/whatsapp pair +1 555-000-1111")
124 items := <-fake.pairings
125 items <- whatsmeow.QRChannelItem{
126 Event: whatsmeow.QRChannelEventCode,
127 }
128
129 asking.WaitFor(t, whatsappPairSteps+"\n"+whatsappTestCode+"\n")
130 require.True(t, fake.Emit(&events.PairSuccess{
131 ID: types.NewADJID(whatsappTestNumber, 0, 1),
132 LID: types.NewADJID(whatsappTestLID, 0, 1),
133 }))
134 items <- whatsmeow.QRChannelSuccess
135 asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
136
137 require.Equal(t, []string{whatsappTestNumber}, fake.Phones())
138 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
139 require.Equal(t, "[connected to OneChat]\n", other.Output())
140 require.Zero(t, server.Calls())
141 require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory))
142
143 info, err := os.Stat(filepath.Join(dir, whatsappDirName))
144 require.NoError(t, err)
145 require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
146
147 info, err = os.Stat(filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
148 require.NoError(t, err)
149 require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
150 }
151
152 func TestWhatsAppPairingCodeIsATelegramMessageAlone(t *testing.T) {
153 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
154 telegram := newTelegramFake(t)
155 bot, _ := telegramStartTestBot(t, telegram)
156 daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
157
158 telegram.Add(TelegramUpdate{
159 UpdateID: 1,
160 Message: telegramOwnerMessage("/whatsapp pair 15550001111"),
161 })
162
163 items := <-fake.pairings
164 items <- whatsmeow.QRChannelItem{
165 Event: whatsmeow.QRChannelEventCode,
166 }
167
168 telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode)
169 }
170
171 func TestWhatsAppPairingEnds(t *testing.T) {
172 testCases := []struct {
173 name string
174 end func(items chan whatsmeow.QRChannelItem)
175 answer string
176 }{
177 {
178 name: "the code expires",
179 end: func(items chan whatsmeow.QRChannelItem) {
180 items <- whatsmeow.QRChannelTimeout
181 },
182 answer: whatsappPairExpired,
183 },
184 {
185 name: "the library closes the pairing",
186 end: func(items chan whatsmeow.QRChannelItem) {
187 close(items)
188 },
189 answer: whatsappPairExpired,
190 },
191 {
192 name: "the pairing fails",
193 end: func(items chan whatsmeow.QRChannelItem) {
194 items <- whatsmeow.QRChannelItem{
195 Event: whatsmeow.QRChannelEventError,
196 Error: errors.New("bad handshake"),
197 }
198 },
199 answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.",
200 },
201 }
202
203 for _, tc := range testCases {
204 t.Run(tc.name, func(t *testing.T) {
205 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
206 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
207 client := terminalStartTestClient(t, socket)
208 client.Type("/whatsapp pair 15550001111")
209
210 items := <-fake.pairings
211 items <- whatsmeow.QRChannelItem{
212 Event: whatsmeow.QRChannelEventCode,
213 }
214
215 client.WaitFor(t, whatsappTestCode)
216 tc.end(items)
217 client.WaitFor(t, tc.answer)
218 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
219 })
220 }
221 }
222
223 func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) {
224 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
225 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
226 client := terminalStartTestClient(t, socket)
227
228 client.Type("/whatsapp pair 15550001111")
229 <-fake.pairings
230 client.Type("/whatsapp pair 15550002222")
231 items := <-fake.pairings
232 items <- whatsmeow.QRChannelItem{
233 Event: whatsmeow.QRChannelEventCode,
234 }
235
236 client.WaitFor(t, whatsappTestCode)
237 require.Equal(t, []string{"15550002222"}, fake.Phones())
238 require.NotContains(t, client.Output(), "did not start the pairing")
239 }
240
241 func TestWhatsAppPairWhenLinked(t *testing.T) {
242 dir := t.TempDir()
243 whatsappTestSession(t, dir, true)
244 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
245 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
246 client := terminalStartTestClient(t, socket)
247
248 client.Type("/whatsapp pair 15550001111")
249 client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.")
250 }
251
252 func TestWhatsAppUnlink(t *testing.T) {
253 testCases := []struct {
254 name string
255 logoutErr error
256 answer string
257 }{
258 {
259 name: "with a logout",
260 answer: "WhatsApp is unlinked.",
261 },
262 {
263 name: "with no logout",
264 logoutErr: errors.New("not connected"),
265 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.",
266 },
267 }
268
269 for _, tc := range testCases {
270 t.Run(tc.name, func(t *testing.T) {
271 dir := t.TempDir()
272 whatsappTestSession(t, dir, true)
273 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
274 fake.logoutErr = tc.logoutErr
275 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
276 client := terminalStartTestClient(t, socket)
277 <-fake.connects
278
279 client.Type("/whatsapp unlink")
280 client.WaitFor(t, tc.answer)
281 require.Equal(t, 1, fake.Logouts())
282 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
283 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
284 require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory))
285
286 client.Type("/whatsapp unlink")
287 client.WaitFor(t, "WhatsApp is not linked.\n")
288 })
289 }
290 }
291
292 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
293 dir := t.TempDir()
294 whatsappTestSession(t, dir, true)
295 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
296 telegram := newTelegramFake(t)
297 bot, _ := telegramStartTestBot(t, telegram)
298 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
299 client := terminalStartTestClient(t, socket)
300 client.WaitFor(t, "[connected to OneChat]")
301 <-fake.connects
302
303 require.True(t, fake.Emit(&events.LoggedOut{}))
304 notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again."
305 client.WaitFor(t, notice)
306 telegramWaitForSent(t, telegram, notice)
307 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
308 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
309 require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory))
310 }
311
312 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
313 dir := t.TempDir()
314 whatsappTestSession(t, dir, true)
315 clock := newTestClock()
316 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
317 whatsapp.noticeDelay = 50 * time.Millisecond
318 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
319 client := terminalStartTestClient(t, socket)
320 client.WaitFor(t, "[connected to OneChat]")
321 <-fake.connects
322
323 require.True(t, fake.Emit(&events.Connected{}))
324 require.True(t, fake.Emit(&events.Disconnected{}))
325 require.True(t, fake.Emit(&events.Connected{}))
326 time.Sleep(100 * time.Millisecond)
327 require.Equal(t, "[connected to OneChat]\n", client.Output())
328
329 clock.now = clock.now.Add(time.Hour)
330 require.True(t, fake.Emit(&events.Disconnected{}))
331 require.True(t, fake.Emit(&events.Disconnected{}))
332 client.WaitFor(t, "WhatsApp is disconnected since 2026-01-01 13:00. OneChat tries again.\n")
333 require.True(t, fake.Emit(&events.Disconnected{}))
334 time.Sleep(100 * time.Millisecond)
335
336 require.True(t, fake.Emit(&events.Connected{}))
337 client.WaitFor(t, "WhatsApp is connected again.\n")
338 require.Equal(t, 1, strings.Count(client.Output(), "WhatsApp is disconnected since"))
339 }
340
341 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
342 dir := t.TempDir()
343 whatsappTestSession(t, dir, true)
344 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
345 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
346 client := terminalStartTestClient(t, socket)
347 client.WaitFor(t, "[connected to OneChat]")
348 <-fake.connects
349
350 require.True(t, fake.Emit(&events.StreamReplaced{}))
351 client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.")
352 }
353
354 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
355 dir := t.TempDir()
356 whatsappTestSession(t, dir, true)
357 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
358 fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid")
359 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
360 <-fake.connects
361
362 require.Eventually(t, func() bool {
363 return logs.String() != ""
364 }, 10*time.Second, time.Millisecond)
365 require.Equal(t, "connect: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String())
366 }
367
368 func TestWhatsAppPhone(t *testing.T) {
369 testCases := []struct {
370 name string
371 phone string
372 valid bool
373 }{
374 {
375 name: "a number with a plus and dashes",
376 phone: "+1-555-000-1111",
377 valid: true,
378 },
379 {
380 name: "a number with no country code",
381 phone: "0115550001111",
382 valid: false,
383 },
384 {
385 name: "a short number",
386 phone: "123456",
387 valid: false,
388 },
389 {
390 name: "a long number",
391 phone: "1234567890123456",
392 valid: false,
393 },
394 {
395 name: "a number with letters",
396 phone: "1555ABC1111",
397 valid: false,
398 },
399 }
400
401 for _, tc := range testCases {
402 t.Run(tc.name, func(t *testing.T) {
403 _, valid := whatsappPhone(tc.phone)
404 require.Equal(t, tc.valid, valid)
405 })
406 }
407 }
408
409 func TestWhatsAppCommandArgs(t *testing.T) {
410 testCases := []struct {
411 name string
412 line string
413 args string
414 found bool
415 }{
416 {
417 name: "a command with its arguments",
418 line: " /whatsapp pair +1 555 ",
419 args: "pair +1 555",
420 found: true,
421 },
422 {
423 name: "the command alone",
424 line: "/whatsapp",
425 args: "",
426 found: true,
427 },
428 {
429 name: "a word that starts with the command",
430 line: "/whatsappstatus",
431 args: "",
432 found: false,
433 },
434 {
435 name: "a message that names the command",
436 line: "what does /whatsapp status do?",
437 args: "",
438 found: false,
439 },
440 }
441
442 for _, tc := range testCases {
443 t.Run(tc.name, func(t *testing.T) {
444 args, found := whatsappCommandArgs(tc.line)
445 require.Equal(t, tc.args, args)
446 require.Equal(t, tc.found, found)
447 })
448 }
449 }
450
451 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
452 // after the log holds at least one message.
453 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
454 t.Helper()
455
456 require.Eventually(t, func() bool {
457 return memory.Len() > 0
458 }, 10*time.Second, time.Millisecond)
459
460 var texts []string
461 for id := range memory.Len() {
462 message, err := memory.Message(id)
463 require.NoError(t, err)
464
465 texts = append(texts, message.Text)
466 }
467
468 return texts
469 }