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 imageSends []*waE2E.ImageMessage
92 downloadWait time.Duration
93 downloads []whatsmeow.DownloadableMessage
96 sent []WhatsAppFakeSend
97 connections []context.Context
100 // ConnectContext keeps ctx and tells the test that the daemon connected.
101 func (f *WhatsAppFake) ConnectContext(ctx context.Context) error {
104 f.connections = append(f.connections, ctx)
105 f.connectTimes = append(f.connectTimes, time.Now())
108 f.connects <- struct{}{}
111 defer f.mutex.Unlock()
113 if len(f.connectErrors) > 0 {
114 err := f.connectErrors[0]
115 f.connectErrors = f.connectErrors[1:]
123 // Connections returns the contexts of the connections, in order.
124 func (f *WhatsAppFake) Connections() []context.Context {
126 defer f.mutex.Unlock()
128 return slices.Clone(f.connections)
131 // ConnectionTimes returns the time of each connection call, in order.
132 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
134 defer f.mutex.Unlock()
136 return slices.Clone(f.connectTimes)
139 // Disconnect does nothing.
140 func (f *WhatsAppFake) Disconnect() {
143 // GetQRChannel gives a new channel of pairing items to the test.
144 func (f *WhatsAppFake) GetQRChannel(_ context.Context) (<-chan whatsmeow.QRChannelItem, error) {
145 items := make(chan whatsmeow.QRChannelItem, 8)
151 // PairPhone keeps phone and returns whatsappTestCode.
152 func (f *WhatsAppFake) PairPhone(_ context.Context, phone string, _ bool, _ whatsmeow.PairClientType, _ string) (string, error) {
154 defer f.mutex.Unlock()
156 f.phones = append(f.phones, phone)
158 return whatsappTestCode, nil
161 // Logout counts the logouts and returns logoutErr.
162 func (f *WhatsAppFake) Logout(_ context.Context) error {
164 defer f.mutex.Unlock()
171 // GetJoinedGroups returns groups.
172 func (f *WhatsAppFake) GetJoinedGroups(_ context.Context) ([]*types.GroupInfo, error) {
174 defer f.mutex.Unlock()
179 // Download waits for downloadWait, records the request, and returns the made-up
180 // image or downloadErr. A canceled context ends the wait.
181 func (f *WhatsAppFake) Download(ctx context.Context, message whatsmeow.DownloadableMessage) ([]byte, error) {
182 if f.downloadWait > 0 {
183 timer := time.NewTimer(f.downloadWait)
188 return nil, ctx.Err()
194 defer f.mutex.Unlock()
196 f.downloads = append(f.downloads, message)
198 return slices.Clone(f.downloadData), f.downloadErr
201 // Downloads returns the media requested from the fake.
202 func (f *WhatsAppFake) Downloads() []whatsmeow.DownloadableMessage {
204 defer f.mutex.Unlock()
206 return slices.Clone(f.downloads)
209 // Upload records the pixels and returns made-up media metadata.
210 func (f *WhatsAppFake) Upload(_ context.Context, data []byte, mediaType whatsmeow.MediaType) (whatsmeow.UploadResponse, error) {
212 defer f.mutex.Unlock()
214 if mediaType != whatsmeow.MediaImage {
215 return whatsmeow.UploadResponse{}, fmt.Errorf("unexpected media type %q", mediaType)
218 f.uploads = append(f.uploads, slices.Clone(data))
219 if f.uploadErr != nil {
220 return whatsmeow.UploadResponse{}, f.uploadErr
223 return whatsmeow.UploadResponse{
224 URL: "https://example.com/image",
225 DirectPath: "/image",
226 MediaKey: []byte("made-up key"),
227 FileSHA256: []byte("made-up hash"),
228 FileEncSHA256: []byte("made-up encrypted hash"),
229 FileLength: uint64(len(data)),
233 // Uploads returns the pixels passed to Upload.
234 func (f *WhatsAppFake) Uploads() [][]byte {
236 defer f.mutex.Unlock()
238 return slices.Clone(f.uploads)
241 // ImageSends returns the outgoing image messages.
242 func (f *WhatsAppFake) ImageSends() []*waE2E.ImageMessage {
244 defer f.mutex.Unlock()
246 return slices.Clone(f.imageSends)
249 // GenerateMessageID returns a new message ID.
250 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
252 defer f.mutex.Unlock()
254 return fmt.Sprintf("MSG%d", len(f.sent)+1)
257 // SendMessage keeps the send and returns sendErr.
258 func (f *WhatsAppFake) SendMessage(_ context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
260 defer f.mutex.Unlock()
262 if message.GetImageMessage() != nil {
263 f.imageSends = append(f.imageSends, message.GetImageMessage())
266 f.sent = append(f.sent, WhatsAppFakeSend{
268 text: message.GetConversation(),
272 if f.sendErr != nil {
273 return whatsmeow.SendResponse{}, f.sendErr
276 return whatsmeow.SendResponse{
277 Timestamp: whatsappTestSendTime,
281 // Sent returns the sends.
282 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
284 defer f.mutex.Unlock()
286 return slices.Clone(f.sent)
289 // Phones returns the phone numbers of the pairings.
290 func (f *WhatsAppFake) Phones() []string {
292 defer f.mutex.Unlock()
294 return append([]string{}, f.phones...)
297 // Logouts returns the number of logouts.
298 func (f *WhatsAppFake) Logouts() int {
300 defer f.mutex.Unlock()
305 // Emit gives event to the handler of the daemon and returns its answer.
306 func (f *WhatsAppFake) Emit(event any) bool {
315 // newClient keeps handle and returns the fake as the client of device.
316 func (f *WhatsAppFake) newClient(_ *store.Device, handle func(event any) bool) WhatsAppClient {
318 defer f.mutex.Unlock()
325 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
327 type WhatsAppFakeSend struct {
333 // WhatsAppRetryTest runs WhatsApp without a model or network client call. All
334 // timers and channels belong to its synctest bubble, so backoff uses fake time.
335 type WhatsAppRetryTest struct {
340 events *TurnEventRecorder
341 cancel context.CancelFunc
345 func (r *WhatsAppRetryTest) start(t *testing.T) {
348 ctx, cancel := context.WithCancel(t.Context())
350 r.done = make(chan error, 1)
352 r.done <- r.whatsapp.Run(ctx, r.loop, r.events.Add)
361 // whatsappStartTest opens the WhatsApp of the data directory dir with a fake
362 // client and the test clock, and closes it at the end of the test. The daemon
363 // log goes to the returned buffer.
364 func whatsappStartTest(t *testing.T, dir string, clock *TestClock) (*WhatsApp, *WhatsAppFake, *SyncBuffer) {
367 fake := &WhatsAppFake{
368 connects: make(chan struct{}, 16),
369 pairings: make(chan chan whatsmeow.QRChannelItem, 16),
372 logs := &SyncBuffer{}
373 whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, daemonTestLogger(logs), fake.newClient)
374 require.NoError(t, err)
377 require.NoError(t, whatsapp.Close())
380 return whatsapp, fake, logs
383 // whatsappTestSession writes a session database with mode 0600 to the data
384 // directory dir. When linked is true, it holds a device linked to
385 // whatsappTestNumber and whatsappTestLID, and else no device.
386 func whatsappTestSession(t *testing.T, dir string, linked bool) {
389 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
390 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
391 require.NoError(t, os.WriteFile(path, nil, 0o600))
393 address, err := whatsappSessionAddress(path)
394 require.NoError(t, err)
396 container, err := sqlstore.New(t.Context(), "sqlite", address, waLog.Noop)
397 require.NoError(t, err)
400 device := container.NewDevice()
401 jid := types.NewADJID(whatsappTestNumber, 0, 1)
403 device.LID = types.NewADJID(whatsappTestLID, 0, 1)
404 device.LID.Server = types.HiddenUserServer
405 device.Account = &waAdv.ADVSignedDeviceIdentity{
407 AccountSignature: make([]byte, 64),
408 AccountSignatureKey: make([]byte, 32),
409 DeviceSignature: make([]byte, 64),
411 require.NoError(t, device.Save(t.Context()))
414 require.NoError(t, container.Close())
417 // whatsappDiscardLog is a logger for a WhatsApp whose log a test does not read.
418 func whatsappDiscardLog() *slog.Logger {
419 return slog.New(slog.DiscardHandler)
422 // whatsappTestMessage returns the event of the text message id of sender in
423 // chat at the time at. A sender with whatsappTestNumber is the user.
424 func whatsappTestMessage(chat, sender types.JID, id, text string, at time.Time) *events.Message {
425 return &events.Message{
426 Info: types.MessageInfo{
427 MessageSource: types.MessageSource{
430 IsFromMe: sender.User == whatsappTestNumber,
431 IsGroup: chat.Server == types.GroupServer,
436 Message: &waE2E.Message{
437 Conversation: new(text),
442 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
443 // after the log holds at least one message.
444 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
447 require.Eventually(t, func() bool {
448 return memory.Len() > 0
449 }, 10*time.Second, time.Millisecond)
453 for id := range memory.Len() {
454 message, err := memory.Message(id)
455 require.NoError(t, err)
457 texts = append(texts, message.Text)
463 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
465 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
469 whatsappTestSession(t, dir, true)
471 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
473 return whatsapp, fake
476 // whatsappTestConnect waits for the connection of the daemon and gives it the
477 // events of a connection with an empty catch-up.
478 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
482 require.True(t, fake.Emit(&events.Connected{}))
483 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
486 // whatsappTestContacts puts the contacts of the tests into the session of
487 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
488 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
491 contacts := whatsapp.device.Contacts
492 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
493 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
495 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
496 require.NoError(t, err)
497 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))
500 func whatsappRetryTest(t *testing.T) *WhatsAppRetryTest {
504 whatsappTestSession(t, dir, true)
506 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
507 whatsapp.clock = time.Now
508 loop, events := newTestIdleTurnLoop(t, whatsapp)
510 return &WhatsAppRetryTest{