X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/522d7fd117285e4e4ce3ea5ec9b5a1722521b681..959c24478e2c3a596a81cca359fd784c897f46a2:/whatsapp_test.go?ds=inline diff --git a/whatsapp_test.go b/whatsapp_test.go index 7a00bbe..9da1537 100644 --- a/whatsapp_test.go +++ b/whatsapp_test.go @@ -1,8 +1,8 @@ package main import ( - "context" "errors" + "log/slog" "os" "path/filepath" "strings" @@ -48,7 +48,7 @@ func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) { synctest.Wait() require.Equal(t, "WhatsApp is linked and disconnected since "+time.Now().Format(whatsappTimeLayout)+".", test.whatsapp.Status()) - require.Equal(t, "first connect failed, retrying: network unavailable\n", test.logs.String()) + require.Equal(t, "<4>first connect failed, retrying: network unavailable\n", test.logs.String()) }) } @@ -91,7 +91,7 @@ func TestWhatsAppRetriesTheFirstConnectionWithCappedBackoff(t *testing.T) { time.Sleep(10 * time.Minute) synctest.Wait() require.Len(t, test.fake.Connections(), 11) - require.Equal(t, "first connect failed, retrying: network unavailable\nconnected again after "+durationText(outage)+"\n", test.logs.String()) + require.Equal(t, "<4>first connect failed, retrying: network unavailable\n<6>connected again after="+durationText(outage)+"\n", test.logs.String()) }) } @@ -124,6 +124,7 @@ func TestWhatsAppLinkedPairRequestKeepsFirstConnectionRetries(t *testing.T) { test.whatsapp.Command("pair 15550001111", func(text string) { answers <- text }) + require.Equal(t, "WhatsApp is linked already. Run /whatsapp unlink first.", <-answers) synctest.Wait() test.fake.mutex.Lock() @@ -139,7 +140,7 @@ func TestWhatsAppLinkedPairRequestKeepsFirstConnectionRetries(t *testing.T) { time.Sleep(whatsappRetryLimit) synctest.Wait() require.Len(t, test.fake.Connections(), 2) - require.Equal(t, "first connect failed, retrying: network unavailable\nconnected again after 2s\n", test.logs.String()) + require.Equal(t, "<4>first connect failed, retrying: network unavailable\n<6>connected again after=2s\n", test.logs.String()) }) } @@ -149,20 +150,20 @@ func TestWhatsAppFirstConnectionRetriesStopForLinkChanges(t *testing.T) { stop func(test *WhatsAppRetryTest) }{ { - name: "unlink", + name: "stops retrying after unlink", stop: func(test *WhatsAppRetryTest) { test.whatsapp.Command("unlink", func(_ string) { }) }, }, { - name: "logout", + name: "stops retrying after logout", stop: func(test *WhatsAppRetryTest) { test.fake.Emit(&events.LoggedOut{}) }, }, { - name: "permanent disconnect", + name: "stops retrying after a permanent disconnect", stop: func(test *WhatsAppRetryTest) { test.fake.Emit(&events.StreamReplaced{}) }, @@ -194,6 +195,7 @@ func TestWhatsAppPairsAfterFirstConnectionRetriesStop(t *testing.T) { synctest.Wait() test.whatsapp.Command("unlink", func(_ string) { }) + synctest.Wait() require.False(t, test.whatsapp.isLinked()) @@ -250,12 +252,12 @@ func TestWhatsAppLongFirstConnectionOutageGivesOneNotice(t *testing.T) { since := time.Now().Format(whatsappTimeLayout) - time.Sleep(whatsappNoticeDelay) + time.Sleep(whatsappOutageNoticeDelay) synctest.Wait() require.Equal(t, 1, test.events.Count("notice")) require.Equal(t, "WhatsApp is disconnected since "+since+". OneChat tries again.", test.events.Last("notice")) - time.Sleep(whatsappNoticeDelay) + time.Sleep(whatsappOutageNoticeDelay) synctest.Wait() require.Equal(t, 1, test.events.Count("notice")) test.fake.mutex.Lock() @@ -312,10 +314,11 @@ func TestWhatsAppLogsEachChangeOfTheConnectionOnce(t *testing.T) { require.True(t, fake.Emit(&events.Connected{})) require.Equal(t, []string{ - "connected", - "disconnected, retrying", - "connected again after 1m25s", + "<6>connected", + "<4>disconnected, retrying", + "<6>connected again after=1m25s", }, strings.Split(strings.TrimSuffix(logs.String(), "\n"), "\n")) + require.NotContains(t, logs.String(), whatsappTestNumber) require.NotContains(t, logs.String(), whatsappTestLID) } @@ -326,12 +329,12 @@ func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) { session func(t *testing.T, dir string) }{ { - name: "no session file", + name: "stays unlinked without a session file", session: func(_ *testing.T, _ string) { }, }, { - name: "a session of a pairing that did not end", + name: "stays unlinked after incomplete pairing", session: func(t *testing.T, dir string) { whatsappTestSession(t, dir, false) }, @@ -388,7 +391,7 @@ func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) { func TestWhatsAppPairsWithACode(t *testing.T) { dir := t.TempDir() - whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock()) server := newModelFake(t) socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp) asking := terminalStartTestClient(t, socket) @@ -426,6 +429,7 @@ func TestWhatsAppPairsWithACode(t *testing.T) { require.Equal(t, "[connected to OneChat]\n", other.Output()) require.Zero(t, server.Calls()) require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory)) + require.Equal(t, "<6>linked\n", logs.String()) info, err := os.Stat(filepath.Join(dir, whatsappDirName)) require.NoError(t, err) @@ -462,21 +466,21 @@ func TestWhatsAppPairingEnds(t *testing.T) { answer string }{ { - name: "the code expires", + name: "ends pairing when the code expires", end: func(items chan whatsmeow.QRChannelItem) { items <- whatsmeow.QRChannelTimeout }, answer: whatsappPairExpired, }, { - name: "the library closes the pairing", + name: "ends pairing when the library closes it", end: func(items chan whatsmeow.QRChannelItem) { close(items) }, answer: whatsappPairExpired, }, { - name: "the pairing fails", + name: "ends pairing when the library reports failure", end: func(items chan whatsmeow.QRChannelItem) { items <- whatsmeow.QRChannelItem{ Event: whatsmeow.QRChannelEventError, @@ -545,11 +549,11 @@ func TestWhatsAppUnlink(t *testing.T) { answer string }{ { - name: "with a logout", + name: "logs out before removing the session", answer: "WhatsApp is unlinked.", }, { - name: "with no logout", + name: "removes an offline session without logout", logoutErr: errors.New("not connected"), 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.", }, @@ -560,7 +564,7 @@ func TestWhatsAppUnlink(t *testing.T) { dir := t.TempDir() whatsappTestSession(t, dir, true) - whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock()) fake.logoutErr = tc.logoutErr socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) client := terminalStartTestClient(t, socket) @@ -570,6 +574,7 @@ func TestWhatsAppUnlink(t *testing.T) { client.Type("/whatsapp unlink") client.WaitFor(t, tc.answer) require.Equal(t, 1, fake.Logouts()) + require.Equal(t, "<6>unlinked\n", logs.String()) require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName)) require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status()) require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory)) @@ -584,7 +589,7 @@ func TestWhatsAppLogoutFromThePhone(t *testing.T) { dir := t.TempDir() whatsappTestSession(t, dir, true) - whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock()) telegram := newTelegramFake(t) bot, _ := telegramStartTestBot(t, telegram) socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp) @@ -597,47 +602,47 @@ func TestWhatsAppLogoutFromThePhone(t *testing.T) { notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again." client.WaitFor(t, notice) telegramWaitForSent(t, telegram, notice) + require.Equal(t, "<3>logged out by the phone, run /whatsapp pair PHONE\n", logs.String()) require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName)) require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status()) require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory)) } func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) { - dir := t.TempDir() - whatsappTestSession(t, dir, true) - - clock := newTestClock() - whatsapp, fake, _ := whatsappStartTest(t, dir, clock) - whatsapp.noticeDelay = 300 * time.Millisecond - socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) - client := terminalStartTestClient(t, socket) - client.WaitFor(t, "[connected to OneChat]") - <-fake.connects - - require.True(t, fake.Emit(&events.Connected{})) - require.True(t, fake.Emit(&events.Disconnected{})) - require.True(t, fake.Emit(&events.Connected{})) - time.Sleep(400 * time.Millisecond) - require.Equal(t, "[connected to OneChat]\n", client.Output()) + synctest.Test(t, func(t *testing.T) { + test := whatsappRetryTest(t) + test.start(t) + synctest.Wait() - clock.now = clock.now.Add(time.Hour) + require.True(t, test.fake.Emit(&events.Connected{})) + require.True(t, test.fake.Emit(&events.Disconnected{})) + require.True(t, test.fake.Emit(&events.Connected{})) + time.Sleep(whatsappOutageNoticeDelay + time.Second) + synctest.Wait() + require.Zero(t, test.events.Count("notice")) - require.True(t, fake.Emit(&events.Disconnected{})) - require.True(t, fake.Emit(&events.Disconnected{})) - client.WaitFor(t, "WhatsApp is disconnected since 2026-01-01 13:00. OneChat tries again.\n") - require.True(t, fake.Emit(&events.Disconnected{})) - time.Sleep(400 * time.Millisecond) + require.True(t, test.fake.Emit(&events.Disconnected{})) + require.True(t, test.fake.Emit(&events.Disconnected{})) + time.Sleep(whatsappOutageNoticeDelay) + synctest.Wait() + require.Equal(t, 1, test.events.Count("notice")) + require.Contains(t, test.events.Last("notice"), "OneChat tries again.") + require.True(t, test.fake.Emit(&events.Disconnected{})) + time.Sleep(whatsappOutageNoticeDelay) + synctest.Wait() + require.Equal(t, 1, test.events.Count("notice")) - require.True(t, fake.Emit(&events.Connected{})) - client.WaitFor(t, "WhatsApp is connected again.\n") - require.Equal(t, 1, strings.Count(client.Output(), "WhatsApp is disconnected since")) + require.True(t, test.fake.Emit(&events.Connected{})) + require.Equal(t, 2, test.events.Count("notice")) + require.Equal(t, "WhatsApp is connected again.", test.events.Last("notice")) + }) } func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) { dir := t.TempDir() whatsappTestSession(t, dir, true) - whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock()) socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) client := terminalStartTestClient(t, socket) client.WaitFor(t, "[connected to OneChat]") @@ -645,6 +650,7 @@ func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) { require.True(t, fake.Emit(&events.StreamReplaced{})) client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.") + require.Equal(t, "<3>disconnected for good, restart to retry: stream replaced\n", logs.String()) } func TestWhatsAppLogsNoOwnNumber(t *testing.T) { @@ -660,7 +666,8 @@ func TestWhatsAppLogsNoOwnNumber(t *testing.T) { require.Eventually(t, func() bool { return logs.String() != "" }, 10*time.Second, time.Millisecond) - require.Equal(t, "first connect failed, retrying: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String()) + + require.Equal(t, "<4>first connect failed, retrying: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String()) } func TestWhatsAppPhone(t *testing.T) { @@ -670,27 +677,27 @@ func TestWhatsAppPhone(t *testing.T) { valid bool }{ { - name: "a number with a plus and dashes", + name: "accepts a number with a plus and dashes", phone: "+1-555-000-1111", valid: true, }, { - name: "a number with no country code", + name: "refuses a number without a country code", phone: "0115550001111", valid: false, }, { - name: "a short number", + name: "refuses a number shorter than the minimum", phone: "123456", valid: false, }, { - name: "a long number", + name: "refuses a number longer than the maximum", phone: "1234567890123456", valid: false, }, { - name: "a number with letters", + name: "refuses a number with letters", phone: "1555ABC1111", valid: false, }, @@ -712,25 +719,25 @@ func TestWhatsAppCommandArgs(t *testing.T) { found bool }{ { - name: "a command with its arguments", + name: "reads and trims the command arguments", line: " /whatsapp pair +1 555 ", args: "pair +1 555", found: true, }, { - name: "the command alone", + name: "accepts the command without arguments", line: "/whatsapp", args: "", found: true, }, { - name: "a word that starts with the command", + name: "leaves a joined command word as text", line: "/whatsappstatus", args: "", found: false, }, { - name: "a message that names the command", + name: "leaves a mention of the command as text", line: "what does /whatsapp status do?", args: "", found: false, @@ -752,61 +759,7 @@ func TestSubagentHasNoWhatsAppTools(t *testing.T) { require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`)) } -// WhatsAppRetryTest runs WhatsApp without a model or network client call. All -// timers and channels belong to its synctest bubble, so backoff uses fake time. -type WhatsAppRetryTest struct { - whatsapp *WhatsApp - fake *WhatsAppFake - logs *SyncBuffer - loop *TurnLoop - events *TurnEventRecorder - cancel context.CancelFunc - done chan error -} - -func (r *WhatsAppRetryTest) start(t *testing.T) { - t.Helper() - - ctx, cancel := context.WithCancel(t.Context()) - r.cancel = cancel - r.done = make(chan error, 1) - go func() { - r.done <- r.whatsapp.Run(ctx, r.loop, r.events.Add) - }() - - t.Cleanup(func() { - cancel() - synctest.Wait() - }) -} - -func whatsappRetryTest(t *testing.T) *WhatsAppRetryTest { - t.Helper() - - dir := t.TempDir() - whatsappTestSession(t, dir, true) - - whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock()) - whatsapp.clock = time.Now - agent, err := openAgent(t.TempDir()) - require.NoError(t, err) - - memory, err := openMemory(t.Context(), agent.dir, time.Now, newFakeSummarizer(), discardLog()) - require.NoError(t, err) - t.Cleanup(func() { - require.NoError(t, memory.Close()) - }) - - events := &TurnEventRecorder{} - client := newModelClient("https://example.com", ModelAPIKey(modelTestKey), agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl")) - loop, err := newTurnLoop(agent, memory, newTestSubagents(t), whatsapp, newTestSchedules(t, time.Now), client, time.Now, discardLog(), events.Add) - require.NoError(t, err) - - return &WhatsAppRetryTest{ - whatsapp: whatsapp, - fake: fake, - logs: logs, - loop: loop, - events: events, - } +// whatsappDiscardLog is a logger for a WhatsApp whose log a test does not read. +func whatsappDiscardLog() *slog.Logger { + return slog.New(slog.DiscardHandler) }