15 "github.com/stretchr/testify/require"
17 waAdv "go.mau.fi/whatsmeow/proto/waAdv"
18 "go.mau.fi/whatsmeow/proto/waE2E"
19 "go.mau.fi/whatsmeow/store"
20 "go.mau.fi/whatsmeow/store/sqlstore"
21 "go.mau.fi/whatsmeow/types"
22 "go.mau.fi/whatsmeow/types/events"
23 waLog "go.mau.fi/whatsmeow/util/log"
27 // whatsappTestNumber is the phone number of the own account in the
28 // tests. It is a number for fiction.
29 whatsappTestNumber = "15550001111"
31 // whatsappTestLID is the LID of the own account in the tests.
32 whatsappTestLID = "987654321012345"
34 // whatsappTestCode is the pairing code of the fake.
35 whatsappTestCode = "ABCD-EFGH"
39 // whatsappTestOwn is the own account in the tests.
40 whatsappTestOwn = types.NewJID(whatsappTestNumber, types.DefaultUserServer)
42 // whatsappTestAna is a contact in the tests.
43 whatsappTestAna = types.NewJID("15550002222", types.DefaultUserServer)
45 // whatsappTestBruno is a member of the test group.
46 whatsappTestBruno = types.NewJID("15550003333", types.DefaultUserServer)
48 // whatsappTestFamily is the test group.
49 whatsappTestFamily = types.NewJID("120363000000000001", types.GroupServer)
51 // whatsappTestChat is the private chat with whatsappTestAna.
52 whatsappTestChat = WhatsAppChat{
53 ID: whatsappTestAna.String(),
57 // whatsappTestSendTime is the time of the sends of the fake.
58 whatsappTestSendTime = time.Date(2026, 1, 1, 12, 5, 0, 0, time.UTC)
60 // whatsappTestGroup is the chat of whatsappTestFamily.
61 whatsappTestGroup = WhatsAppChat{
62 ID: whatsappTestFamily.String(),
68 // WhatsAppFake is a fake WhatsApp client. It keeps the event handler that the
69 // daemon gives it, and Emit gives events to the handler, as the library does.
70 // Each connection keeps its context and sends to connects, and each pairing
71 // sends its channel to pairings, so that the test gives the items of the
72 // pairing. A connection takes its error from connectErrors, then connectErr. A
73 // logout fails with logoutErr, and a send with sendErr. groups are the groups
74 // of the account. A send that does not fail gets the time whatsappTestSendTime.
75 type WhatsAppFake struct {
76 connects chan struct{}
77 pairings chan chan whatsmeow.QRChannelItem
80 handle func(event any) bool
83 connectTimes []time.Time
85 groups []*types.GroupInfo
89 downloadWait time.Duration
90 downloads []whatsmeow.DownloadableMessage
93 sent []WhatsAppFakeSend
94 connections []context.Context
97 // ConnectContext keeps ctx and tells the test that the daemon connected.
98 func (f *WhatsAppFake) ConnectContext(ctx context.Context) error {
101 f.connections = append(f.connections, ctx)
102 f.connectTimes = append(f.connectTimes, time.Now())
105 f.connects <- struct{}{}
108 defer f.mutex.Unlock()
110 if len(f.connectErrors) > 0 {
111 err := f.connectErrors[0]
112 f.connectErrors = f.connectErrors[1:]
120 // Connections returns the contexts of the connections, in order.
121 func (f *WhatsAppFake) Connections() []context.Context {
123 defer f.mutex.Unlock()
125 return slices.Clone(f.connections)
128 // ConnectionTimes returns the time of each connection call, in order.
129 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
131 defer f.mutex.Unlock()
133 return slices.Clone(f.connectTimes)
136 // Disconnect does nothing.
137 func (f *WhatsAppFake) Disconnect() {
140 // GetQRChannel gives a new channel of pairing items to the test.
141 func (f *WhatsAppFake) GetQRChannel(_ context.Context) (<-chan whatsmeow.QRChannelItem, error) {
142 items := make(chan whatsmeow.QRChannelItem, 8)
148 // PairPhone keeps phone and returns whatsappTestCode.
149 func (f *WhatsAppFake) PairPhone(_ context.Context, phone string, _ bool, _ whatsmeow.PairClientType, _ string) (string, error) {
151 defer f.mutex.Unlock()
153 f.phones = append(f.phones, phone)
155 return whatsappTestCode, nil
158 // Logout counts the logouts and returns logoutErr.
159 func (f *WhatsAppFake) Logout(_ context.Context) error {
161 defer f.mutex.Unlock()
168 // GetJoinedGroups returns groups.
169 func (f *WhatsAppFake) GetJoinedGroups(_ context.Context) ([]*types.GroupInfo, error) {
171 defer f.mutex.Unlock()
176 // Download waits for downloadWait, records the request, and returns the made-up
177 // image or downloadErr. A canceled context ends the wait.
178 func (f *WhatsAppFake) Download(ctx context.Context, message whatsmeow.DownloadableMessage) ([]byte, error) {
179 if f.downloadWait > 0 {
180 timer := time.NewTimer(f.downloadWait)
185 return nil, ctx.Err()
191 defer f.mutex.Unlock()
193 f.downloads = append(f.downloads, message)
195 return slices.Clone(f.downloadData), f.downloadErr
198 // Downloads returns the media requested from the fake.
199 func (f *WhatsAppFake) Downloads() []whatsmeow.DownloadableMessage {
201 defer f.mutex.Unlock()
203 return slices.Clone(f.downloads)
206 // GenerateMessageID returns a new message ID.
207 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
209 defer f.mutex.Unlock()
211 return fmt.Sprintf("MSG%d", len(f.sent)+1)
214 // SendMessage keeps the send and returns sendErr.
215 func (f *WhatsAppFake) SendMessage(_ context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
217 defer f.mutex.Unlock()
219 f.sent = append(f.sent, WhatsAppFakeSend{
221 text: message.GetConversation(),
225 if f.sendErr != nil {
226 return whatsmeow.SendResponse{}, f.sendErr
229 return whatsmeow.SendResponse{
230 Timestamp: whatsappTestSendTime,
234 // Sent returns the sends.
235 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
237 defer f.mutex.Unlock()
239 return slices.Clone(f.sent)
242 // Phones returns the phone numbers of the pairings.
243 func (f *WhatsAppFake) Phones() []string {
245 defer f.mutex.Unlock()
247 return append([]string{}, f.phones...)
250 // Logouts returns the number of logouts.
251 func (f *WhatsAppFake) Logouts() int {
253 defer f.mutex.Unlock()
258 // Emit gives event to the handler of the daemon and returns its answer.
259 func (f *WhatsAppFake) Emit(event any) bool {
268 // newClient keeps handle and returns the fake as the client of device.
269 func (f *WhatsAppFake) newClient(_ *store.Device, handle func(event any) bool) WhatsAppClient {
271 defer f.mutex.Unlock()
278 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
280 type WhatsAppFakeSend struct {
286 // WhatsAppRetryTest runs WhatsApp without a model or network client call. All
287 // timers and channels belong to its synctest bubble, so backoff uses fake time.
288 type WhatsAppRetryTest struct {
293 events *TurnEventRecorder
294 cancel context.CancelFunc
298 func (r *WhatsAppRetryTest) start(t *testing.T) {
301 ctx, cancel := context.WithCancel(t.Context())
303 r.done = make(chan error, 1)
305 r.done <- r.whatsapp.Run(ctx, r.loop, r.events.Add)
314 // whatsappStartTest opens the WhatsApp of the data directory dir with a fake
315 // client and the test clock, and closes it at the end of the test. The daemon
316 // log goes to the returned buffer.
317 func whatsappStartTest(t *testing.T, dir string, clock *TestClock) (*WhatsApp, *WhatsAppFake, *SyncBuffer) {
320 fake := &WhatsAppFake{
321 connects: make(chan struct{}, 16),
322 pairings: make(chan chan whatsmeow.QRChannelItem, 16),
325 logs := &SyncBuffer{}
326 whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, daemonTestLogger(logs), fake.newClient)
327 require.NoError(t, err)
330 require.NoError(t, whatsapp.Close())
333 return whatsapp, fake, logs
336 // whatsappTestSession writes a session database with mode 0600 to the data
337 // directory dir. When linked is true, it holds a device linked to
338 // whatsappTestNumber and whatsappTestLID, and else no device.
339 func whatsappTestSession(t *testing.T, dir string, linked bool) {
342 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
343 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
344 require.NoError(t, os.WriteFile(path, nil, 0o600))
346 address, err := whatsappSessionAddress(path)
347 require.NoError(t, err)
349 container, err := sqlstore.New(t.Context(), "sqlite", address, waLog.Noop)
350 require.NoError(t, err)
353 device := container.NewDevice()
354 jid := types.NewADJID(whatsappTestNumber, 0, 1)
356 device.LID = types.NewADJID(whatsappTestLID, 0, 1)
357 device.LID.Server = types.HiddenUserServer
358 device.Account = &waAdv.ADVSignedDeviceIdentity{
360 AccountSignature: make([]byte, 64),
361 AccountSignatureKey: make([]byte, 32),
362 DeviceSignature: make([]byte, 64),
364 require.NoError(t, device.Save(t.Context()))
367 require.NoError(t, container.Close())
370 // whatsappDiscardLog is a logger for a WhatsApp whose log a test does not read.
371 func whatsappDiscardLog() *slog.Logger {
372 return slog.New(slog.DiscardHandler)
375 // whatsappTestMessage returns the event of the text message id of sender in
376 // chat at the time at. A sender with whatsappTestNumber is the user.
377 func whatsappTestMessage(chat, sender types.JID, id, text string, at time.Time) *events.Message {
378 return &events.Message{
379 Info: types.MessageInfo{
380 MessageSource: types.MessageSource{
383 IsFromMe: sender.User == whatsappTestNumber,
384 IsGroup: chat.Server == types.GroupServer,
389 Message: &waE2E.Message{
390 Conversation: new(text),
395 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
396 // after the log holds at least one message.
397 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
400 require.Eventually(t, func() bool {
401 return memory.Len() > 0
402 }, 10*time.Second, time.Millisecond)
406 for id := range memory.Len() {
407 message, err := memory.Message(id)
408 require.NoError(t, err)
410 texts = append(texts, message.Text)
416 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
418 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
422 whatsappTestSession(t, dir, true)
424 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
426 return whatsapp, fake
429 // whatsappTestConnect waits for the connection of the daemon and gives it the
430 // events of a connection with an empty catch-up.
431 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
435 require.True(t, fake.Emit(&events.Connected{}))
436 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
439 // whatsappTestContacts puts the contacts of the tests into the session of
440 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
441 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
444 contacts := whatsapp.device.Contacts
445 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
446 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
448 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
449 require.NoError(t, err)
450 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))
453 func whatsappRetryTest(t *testing.T) *WhatsAppRetryTest {
457 whatsappTestSession(t, dir, true)
459 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
460 whatsapp.clock = time.Now
461 loop, events := newTestIdleTurnLoop(t, whatsapp)
463 return &WhatsAppRetryTest{