X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/0018014ab36f3de61a4b8a5515009dab803d6c38..a6a82d96b4906e9e1f09f45f69f48124f11ae1bb:/whatsapp_test.go diff --git a/whatsapp_test.go b/whatsapp_test.go index e0018e5..3d79def 100644 --- a/whatsapp_test.go +++ b/whatsapp_test.go @@ -1,7 +1,11 @@ package main import ( + "crypto/sha256" + "encoding/hex" "errors" + "fmt" + "net/http" "os" "path/filepath" "strings" @@ -134,6 +138,14 @@ func TestWhatsAppPairsWithACode(t *testing.T) { items <- whatsmeow.QRChannelSuccess asking.WaitFor(t, "WhatsApp is linked to +15550001111.") + // The library connects again after the link with the context of the + // connection, so the end of the pairing must not end it. + connections := fake.Connections() + require.Len(t, connections, 1) + require.Never(t, func() bool { + return connections[0].Err() != nil + }, 200*time.Millisecond, time.Millisecond) + require.Equal(t, []string{whatsappTestNumber}, fake.Phones()) require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status()) require.Equal(t, "[connected to OneChat]\n", other.Output()) @@ -314,7 +326,7 @@ func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) { whatsappTestSession(t, dir, true) clock := newTestClock() whatsapp, fake, _ := whatsappStartTest(t, dir, clock) - whatsapp.noticeDelay = 50 * time.Millisecond + whatsapp.noticeDelay = 300 * time.Millisecond socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) client := terminalStartTestClient(t, socket) client.WaitFor(t, "[connected to OneChat]") @@ -323,7 +335,7 @@ func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) { require.True(t, fake.Emit(&events.Connected{})) require.True(t, fake.Emit(&events.Disconnected{})) require.True(t, fake.Emit(&events.Connected{})) - time.Sleep(100 * time.Millisecond) + time.Sleep(400 * time.Millisecond) require.Equal(t, "[connected to OneChat]\n", client.Output()) clock.now = clock.now.Add(time.Hour) @@ -331,7 +343,7 @@ func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) { 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(100 * time.Millisecond) + time.Sleep(400 * time.Millisecond) require.True(t, fake.Emit(&events.Connected{})) client.WaitFor(t, "WhatsApp is connected again.\n") @@ -448,22 +460,319 @@ func TestWhatsAppCommandArgs(t *testing.T) { } } -// whatsappTestLogTexts returns the texts of the messages in the log of memory, -// after the log holds at least one message. -func whatsappTestLogTexts(t *testing.T, memory *Memory) []string { +func TestWhatsAppFindMatchesNamesWithNoRegardToCaseAndAccents(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + fake.groups = []*types.GroupInfo{ + { + JID: whatsappTestFamily, + GroupName: types.GroupName{ + Name: "Família Souza", + }, + }, + } + + whatsappTestContacts(t, whatsapp) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + testCases := []struct { + name string + query string + answer string + }{ + { + name: "no accent finds an accent", + query: "joao", + answer: "15550004444@s.whatsapp.net | João Silva | contact", + }, + { + name: "a part of a name finds contacts and groups", + query: "SOUZA", + answer: "15550002222@s.whatsapp.net | Ana Souza | contact\n120363000000000001@g.us | Família Souza | group", + }, + { + name: "a business name", + query: "bakery", + answer: "15550005555@s.whatsapp.net | Corner Bakery | contact", + }, + { + name: "no match", + query: "Zed", + answer: "No contact or group has a name with \"Zed\".", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + answer, err := whatsapp.Find(t.Context(), tc.query) + require.NoError(t, err) + require.Equal(t, tc.answer, answer) + }) + } +} + +func TestWhatsAppFindGivesAtMostTwentyMatches(t *testing.T) { + whatsapp, _ := whatsappStartTestLinked(t) + for index := range 25 { + jid := types.NewJID(fmt.Sprintf("1555001%04d", index), types.DefaultUserServer) + require.NoError(t, whatsapp.device.Contacts.PutContactName(t.Context(), jid, "", fmt.Sprintf("Member %02d", index))) + } + + answer, err := whatsapp.Find(t.Context(), "member") + require.NoError(t, err) + + lines := strings.Split(answer, "\n") + require.Len(t, lines, 22) + require.Equal(t, "15550010000@s.whatsapp.net | Member 00 | contact", lines[0]) + require.Equal(t, "5 more: give a longer part of the name.", lines[20]) + require.Equal(t, "The groups are not in this answer, because WhatsApp is disconnected.", lines[21]) +} + +func TestWhatsAppFindBeforeTheNamesArrive(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + answer, err := whatsapp.Find(t.Context(), "ana") + require.NoError(t, err) + require.Equal(t, whatsappNamesNotReady, answer) +} + +func TestWhatsAppFindWithoutALink(t *testing.T) { + whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock()) + + answer, err := whatsapp.Find(t.Context(), "ana") + require.NoError(t, err) + require.Equal(t, whatsappNotLinked, answer) +} + +func TestAgentFindsAWhatsAppContact(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + whatsappTestContacts(t, whatsapp) + server := newModelFake(t) + server.reply = func(w http.ResponseWriter, call ModelFakeCall) { + if call.number == 0 { + modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "whatsapp_find", `{"name":"ana"}`)}, 100, 0, 5)) + return + } + + modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Found Ana.")}, 100, 0, 5)) + } + + socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp) + client := terminalStartTestClient(t, socket) + whatsappTestConnect(t, fake) + + client.Type("Find Ana on WhatsApp.") + client.WaitFor(t, "[result] 15550002222@s.whatsapp.net | Ana Souza | contact\nFound Ana.\n[done]") +} + +func TestSubagentHasNoWhatsAppTools(t *testing.T) { + box := &Toolbox{} + require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`)) + require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`)) +} + +// whatsappTestContacts puts the contacts of the tests into the session of +// whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user. +func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) { t.Helper() - require.Eventually(t, func() bool { - return memory.Len() > 0 - }, 10*time.Second, time.Millisecond) + contacts := whatsapp.device.Contacts + require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza")) + require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva")) + _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery") + require.NoError(t, err) + require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza")) +} + +func TestWhatsAppSendSendsOnceForEachID(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + whatsappTestContacts(t, whatsapp) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.") + require.NoError(t, err) + require.Equal(t, "Sent to Ana Souza at 12:05.", answer) + + answer, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.") + require.NoError(t, err) + require.Equal(t, "Sent to Ana Souza at 12:05. This is the answer of the first call with this id: nothing was sent again.", answer) + + _, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "Another text.") + require.EqualError(t, err, "the id keys belongs to another message: give a new id for each message") - var texts []string - for id := range memory.Len() { - message, err := memory.Message(id) + require.Equal(t, []WhatsAppFakeSend{ + { + to: whatsappTestAna.String(), + text: "The keys are under the mat.", + id: "MSG1", + }, + }, fake.Sent()) + + again, err := openWhatsAppState(filepath.Join(whatsapp.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow) + require.NoError(t, err) + + record, found := again.Send("keys") + require.True(t, found) + require.Equal(t, whatsappSent, record.State) + require.Equal(t, "MSG1", record.MessageID) +} + +func TestWhatsAppSendToAGroup(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + fake.groups = []*types.GroupInfo{ + { + JID: whatsappTestFamily, + GroupName: types.GroupName{ + Name: "Family", + }, + }, + } + + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + answer, err := whatsapp.Send(t.Context(), "cake", whatsappTestFamily.String(), "I bring the cake.") + require.NoError(t, err) + require.Equal(t, "Sent to Family at 12:05.", answer) +} + +func TestWhatsAppSendThatFails(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + fake.sendErr = errors.New("server error for " + whatsappTestNumber) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + for range 2 { + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") require.NoError(t, err) + require.True(t, strings.HasPrefix(answer, "The send failed: server error for OWN."), answer) + } + + require.Len(t, fake.Sent(), 1) +} + +func TestWhatsAppSendCutByAStop(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + digest := sha256.Sum256([]byte("hi")) + require.NoError(t, whatsapp.state.PutSend(WhatsAppSend{ + ID: "keys", + Chat: whatsappTestAna.String(), + Digest: hex.EncodeToString(digest[:]), + State: whatsappSending, + })) + + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.NoError(t, err) + require.Contains(t, answer, "its result is unknown") + require.Empty(t, fake.Sent()) +} - texts = append(texts, message.Text) +func TestWhatsAppSendRefuses(t *testing.T) { + testCases := []struct { + name string + id string + chat string + text string + err string + }{ + { + name: "no id", + id: " ", + chat: whatsappTestAna.String(), + text: "hi", + err: "the id must have 1 to 100 bytes", + }, + { + name: "no text", + id: "a", + chat: whatsappTestAna.String(), + text: "", + err: "the text must have 1 to 65536 bytes", + }, + { + name: "a name for a chat", + id: "a", + chat: "Ana Souza", + text: "hi", + err: `"Ana Souza" is not the ID of a WhatsApp chat: find the ID with whatsapp_find`, + }, + { + name: "a status broadcast", + id: "a", + chat: types.StatusBroadcastJID.String(), + text: "hi", + err: `"status@broadcast" is not a private chat or a group`, + }, + { + name: "the chat of the user", + id: "a", + chat: whatsappTestOwn.String(), + text: "hi", + err: "this is the chat of the user with itself: send to another chat", + }, + } + + whatsapp, fake := whatsappStartTestLinked(t) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + _, err := whatsapp.Send(t.Context(), tc.id, tc.chat, tc.text) + require.EqualError(t, err, tc.err) + }) + } + + require.Empty(t, fake.Sent()) +} + +func TestWhatsAppSendWhileDisconnected(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + require.True(t, fake.Emit(&events.Disconnected{})) + + _, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.EqualError(t, err, "WhatsApp is disconnected, so nothing was sent: try again later") + + require.True(t, fake.Emit(&events.Connected{})) + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.NoError(t, err) + require.Equal(t, "Sent to +15550002222 at 12:05.", answer) +} + +func TestWhatsAppSendWithoutALink(t *testing.T) { + whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock()) + + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.NoError(t, err) + require.Equal(t, whatsappNotLinked, answer) +} + +func TestAgentSendsAWhatsAppMessage(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + whatsappTestContacts(t, whatsapp) + server := newModelFake(t) + server.reply = func(w http.ResponseWriter, call ModelFakeCall) { + if call.number == 0 { + modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "whatsapp_send", `{"id":"keys","chat":"15550002222@s.whatsapp.net","text":"The keys are under the mat."}`)}, 100, 0, 5)) + return + } + + modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Sent.")}, 100, 0, 5)) } - return texts + socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp) + client := terminalStartTestClient(t, socket) + whatsappTestConnect(t, fake) + + client.Type("Tell Ana that the keys are under the mat.") + client.WaitFor(t, "[result] Sent to Ana Souza at 12:05.\nSent.\n[done]") + require.Len(t, fake.Sent(), 1) }