11 "github.com/stretchr/testify/require"
13 "go.mau.fi/whatsmeow/types"
14 "go.mau.fi/whatsmeow/types/events"
17 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
19 whatsappTestSession(t, dir, true)
20 clock := newTestClock()
21 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
22 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
25 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
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())
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())
37 func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
39 whatsappTestSession(t, dir, true)
40 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
41 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
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())
48 func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
49 testCases := []struct {
51 session func(t *testing.T, dir string)
54 name: "no session file",
55 session: func(t *testing.T, dir string) {
59 name: "a session of a pairing that did not end",
60 session: func(t *testing.T, dir string) {
61 whatsappTestSession(t, dir, false)
66 for _, tc := range testCases {
67 t.Run(tc.name, func(t *testing.T) {
70 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
71 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
76 func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
78 whatsappTestSession(t, dir, true)
79 require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
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")
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]")
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")
102 telegram.Add(TelegramUpdate{
104 Message: telegramOwnerMessage("/whatsapp status"),
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())
113 func TestWhatsAppPairsWithACode(t *testing.T) {
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]")
123 asking.Type("/whatsapp pair +1 555-000-1111")
124 items := <-fake.pairings
125 items <- whatsmeow.QRChannelItem{
126 Event: whatsmeow.QRChannelEventCode,
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),
134 items <- whatsmeow.QRChannelSuccess
135 asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
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))
143 info, err := os.Stat(filepath.Join(dir, whatsappDirName))
144 require.NoError(t, err)
145 require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
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())
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)
158 telegram.Add(TelegramUpdate{
160 Message: telegramOwnerMessage("/whatsapp pair 15550001111"),
163 items := <-fake.pairings
164 items <- whatsmeow.QRChannelItem{
165 Event: whatsmeow.QRChannelEventCode,
168 telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode)
171 func TestWhatsAppPairingEnds(t *testing.T) {
172 testCases := []struct {
174 end func(items chan whatsmeow.QRChannelItem)
178 name: "the code expires",
179 end: func(items chan whatsmeow.QRChannelItem) {
180 items <- whatsmeow.QRChannelTimeout
182 answer: whatsappPairExpired,
185 name: "the library closes the pairing",
186 end: func(items chan whatsmeow.QRChannelItem) {
189 answer: whatsappPairExpired,
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"),
199 answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.",
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")
210 items := <-fake.pairings
211 items <- whatsmeow.QRChannelItem{
212 Event: whatsmeow.QRChannelEventCode,
215 client.WaitFor(t, whatsappTestCode)
217 client.WaitFor(t, tc.answer)
218 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
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)
228 client.Type("/whatsapp pair 15550001111")
230 client.Type("/whatsapp pair 15550002222")
231 items := <-fake.pairings
232 items <- whatsmeow.QRChannelItem{
233 Event: whatsmeow.QRChannelEventCode,
236 client.WaitFor(t, whatsappTestCode)
237 require.Equal(t, []string{"15550002222"}, fake.Phones())
238 require.NotContains(t, client.Output(), "did not start the pairing")
241 func TestWhatsAppPairWhenLinked(t *testing.T) {
243 whatsappTestSession(t, dir, true)
244 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
245 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
246 client := terminalStartTestClient(t, socket)
248 client.Type("/whatsapp pair 15550001111")
249 client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.")
252 func TestWhatsAppUnlink(t *testing.T) {
253 testCases := []struct {
259 name: "with a logout",
260 answer: "WhatsApp is unlinked.",
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.",
269 for _, tc := range testCases {
270 t.Run(tc.name, func(t *testing.T) {
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)
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))
286 client.Type("/whatsapp unlink")
287 client.WaitFor(t, "WhatsApp is not linked.\n")
292 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
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]")
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))
312 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
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]")
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())
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)
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"))
341 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
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]")
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.")
354 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
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)
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())
368 func TestWhatsAppPhone(t *testing.T) {
369 testCases := []struct {
375 name: "a number with a plus and dashes",
376 phone: "+1-555-000-1111",
380 name: "a number with no country code",
381 phone: "0115550001111",
385 name: "a short number",
390 name: "a long number",
391 phone: "1234567890123456",
395 name: "a number with letters",
396 phone: "1555ABC1111",
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)
409 func TestWhatsAppCommandArgs(t *testing.T) {
410 testCases := []struct {
417 name: "a command with its arguments",
418 line: " /whatsapp pair +1 555 ",
423 name: "the command alone",
429 name: "a word that starts with the command",
430 line: "/whatsappstatus",
435 name: "a message that names the command",
436 line: "what does /whatsapp status do?",
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)
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 {
456 require.Eventually(t, func() bool {
457 return memory.Len() > 0
458 }, 10*time.Second, time.Millisecond)
461 for id := range memory.Len() {
462 message, err := memory.Message(id)
463 require.NoError(t, err)
465 texts = append(texts, message.Text)