14 "github.com/stretchr/testify/require"
16 waAdv "go.mau.fi/whatsmeow/proto/waAdv"
17 "go.mau.fi/whatsmeow/proto/waE2E"
18 "go.mau.fi/whatsmeow/store"
19 "go.mau.fi/whatsmeow/store/sqlstore"
20 "go.mau.fi/whatsmeow/types"
21 "go.mau.fi/whatsmeow/types/events"
22 waLog "go.mau.fi/whatsmeow/util/log"
26 // whatsappTestNumber is the phone number of the own account in the
27 // tests. It is a number for fiction.
28 whatsappTestNumber = "15550001111"
30 // whatsappTestLID is the LID of the own account in the tests.
31 whatsappTestLID = "987654321012345"
33 // whatsappTestCode is the pairing code of the fake.
34 whatsappTestCode = "ABCD-EFGH"
38 // whatsappTestOwn is the own account in the tests.
39 whatsappTestOwn = types.NewJID(whatsappTestNumber, types.DefaultUserServer)
41 // whatsappTestAna is a contact in the tests.
42 whatsappTestAna = types.NewJID("15550002222", types.DefaultUserServer)
44 // whatsappTestBruno is a member of the test group.
45 whatsappTestBruno = types.NewJID("15550003333", types.DefaultUserServer)
47 // whatsappTestFamily is the test group.
48 whatsappTestFamily = types.NewJID("120363000000000001", types.GroupServer)
50 // whatsappTestChat is the private chat with whatsappTestAna.
51 whatsappTestChat = WhatsAppChat{
52 ID: whatsappTestAna.String(),
56 // whatsappTestSendTime is the time of the sends of the fake.
57 whatsappTestSendTime = time.Date(2026, 1, 1, 12, 5, 0, 0, time.UTC)
59 // whatsappTestGroup is the chat of whatsappTestFamily.
60 whatsappTestGroup = WhatsAppChat{
61 ID: whatsappTestFamily.String(),
67 // WhatsAppFake is a fake WhatsApp client. It keeps the event handler that the
68 // daemon gives it, and Emit gives events to the handler, as the library does.
69 // Each connection keeps its context and sends to connects, and each pairing
70 // sends its channel to pairings, so that the test gives the items of the
71 // pairing. A connection takes its error from connectErrors, then connectErr. A
72 // logout fails with logoutErr, and a send with sendErr. groups are the groups
73 // of the account. A send that does not fail gets the time whatsappTestSendTime.
74 type WhatsAppFake struct {
75 connects chan struct{}
76 pairings chan chan whatsmeow.QRChannelItem
79 handle func(event any) bool
82 connectTimes []time.Time
84 groups []*types.GroupInfo
88 imageSends []*waE2E.ImageMessage
91 downloadWait time.Duration
92 downloads []whatsmeow.DownloadableMessage
95 sent []WhatsAppFakeSend
96 connections []context.Context
99 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
101 type WhatsAppFakeSend struct {
107 // WhatsAppRetryTest runs WhatsApp without a model or network client call. All
108 // timers and channels belong to its synctest bubble, so backoff uses fake time.
109 type WhatsAppRetryTest struct {
114 events *TurnEventRecorder
115 cancel context.CancelFunc
119 // ConnectContext keeps ctx and tells the test that the daemon connected.
120 func (f *WhatsAppFake) ConnectContext(ctx context.Context) error {
123 f.connections = append(f.connections, ctx)
124 f.connectTimes = append(f.connectTimes, time.Now())
127 f.connects <- struct{}{}
130 defer f.mutex.Unlock()
132 if len(f.connectErrors) > 0 {
133 err := f.connectErrors[0]
134 f.connectErrors = f.connectErrors[1:]
142 // Connections returns the contexts of the connections, in order.
143 func (f *WhatsAppFake) Connections() []context.Context {
145 defer f.mutex.Unlock()
147 return slices.Clone(f.connections)
150 // ConnectionTimes returns the time of each connection call, in order.
151 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
153 defer f.mutex.Unlock()
155 return slices.Clone(f.connectTimes)
158 // Disconnect does nothing.
159 func (f *WhatsAppFake) Disconnect() {
162 // GetQRChannel gives a new channel of pairing items to the test.
163 func (f *WhatsAppFake) GetQRChannel(_ context.Context) (<-chan whatsmeow.QRChannelItem, error) {
164 items := make(chan whatsmeow.QRChannelItem, 8)
170 // PairPhone keeps phone and returns whatsappTestCode.
171 func (f *WhatsAppFake) PairPhone(_ context.Context, phone string, _ bool, _ whatsmeow.PairClientType, _ string) (string, error) {
173 defer f.mutex.Unlock()
175 f.phones = append(f.phones, phone)
177 return whatsappTestCode, nil
180 // Logout counts the logouts and returns logoutErr.
181 func (f *WhatsAppFake) Logout(_ context.Context) error {
183 defer f.mutex.Unlock()
190 // GetJoinedGroups returns groups.
191 func (f *WhatsAppFake) GetJoinedGroups(_ context.Context) ([]*types.GroupInfo, error) {
193 defer f.mutex.Unlock()
198 // Download waits for downloadWait, records the request, and returns the made-up
199 // image or downloadErr. A canceled context ends the wait.
200 func (f *WhatsAppFake) Download(ctx context.Context, message whatsmeow.DownloadableMessage) ([]byte, error) {
201 if f.downloadWait > 0 {
202 timer := time.NewTimer(f.downloadWait)
207 return nil, ctx.Err()
213 defer f.mutex.Unlock()
215 f.downloads = append(f.downloads, message)
217 return slices.Clone(f.downloadData), f.downloadErr
220 // Downloads returns the media requested from the fake.
221 func (f *WhatsAppFake) Downloads() []whatsmeow.DownloadableMessage {
223 defer f.mutex.Unlock()
225 return slices.Clone(f.downloads)
228 // Upload records the pixels and returns made-up media metadata.
229 func (f *WhatsAppFake) Upload(_ context.Context, data []byte, mediaType whatsmeow.MediaType) (whatsmeow.UploadResponse, error) {
231 defer f.mutex.Unlock()
233 if mediaType != whatsmeow.MediaImage {
234 return whatsmeow.UploadResponse{}, fmt.Errorf("unexpected media type %q", mediaType)
237 f.uploads = append(f.uploads, slices.Clone(data))
238 if f.uploadErr != nil {
239 return whatsmeow.UploadResponse{}, f.uploadErr
242 return whatsmeow.UploadResponse{
243 URL: "https://example.com/image",
244 DirectPath: "/image",
245 MediaKey: []byte("made-up key"),
246 FileSHA256: []byte("made-up hash"),
247 FileEncSHA256: []byte("made-up encrypted hash"),
248 FileLength: uint64(len(data)),
252 // Uploads returns the pixels passed to Upload.
253 func (f *WhatsAppFake) Uploads() [][]byte {
255 defer f.mutex.Unlock()
257 return slices.Clone(f.uploads)
260 // ImageSends returns the outgoing image messages.
261 func (f *WhatsAppFake) ImageSends() []*waE2E.ImageMessage {
263 defer f.mutex.Unlock()
265 return slices.Clone(f.imageSends)
268 // GenerateMessageID returns a new message ID.
269 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
271 defer f.mutex.Unlock()
273 return fmt.Sprintf("MSG%d", len(f.sent)+1)
276 // SendMessage keeps the send and returns sendErr.
277 func (f *WhatsAppFake) SendMessage(_ context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
279 defer f.mutex.Unlock()
281 if message.GetImageMessage() != nil {
282 f.imageSends = append(f.imageSends, message.GetImageMessage())
285 f.sent = append(f.sent, WhatsAppFakeSend{
287 text: message.GetConversation(),
291 if f.sendErr != nil {
292 return whatsmeow.SendResponse{}, f.sendErr
295 return whatsmeow.SendResponse{
296 Timestamp: whatsappTestSendTime,
300 // Sent returns the sends.
301 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
303 defer f.mutex.Unlock()
305 return slices.Clone(f.sent)
308 // Phones returns the phone numbers of the pairings.
309 func (f *WhatsAppFake) Phones() []string {
311 defer f.mutex.Unlock()
313 return append([]string{}, f.phones...)
316 // Logouts returns the number of logouts.
317 func (f *WhatsAppFake) Logouts() int {
319 defer f.mutex.Unlock()
324 // Emit gives event to the handler of the daemon and returns its answer.
325 func (f *WhatsAppFake) Emit(event any) bool {
334 // newClient keeps handle and returns the fake as the client of device.
335 func (f *WhatsAppFake) newClient(_ *store.Device, handle func(event any) bool) WhatsAppClient {
337 defer f.mutex.Unlock()
344 func (r *WhatsAppRetryTest) start(t *testing.T) {
347 ctx, cancel := context.WithCancel(t.Context())
349 r.done = make(chan error, 1)
351 r.done <- r.whatsapp.Run(ctx, r.loop, r.events.Add)
360 // whatsappStartTest opens the WhatsApp of the data directory dir with a fake
361 // client and the test clock, and closes it at the end of the test. The daemon
362 // log goes to the returned buffer.
363 func whatsappStartTest(t *testing.T, dir string, clock *TestClock) (*WhatsApp, *WhatsAppFake, *SyncBuffer) {
366 fake := &WhatsAppFake{
367 connects: make(chan struct{}, 16),
368 pairings: make(chan chan whatsmeow.QRChannelItem, 16),
371 logs := &SyncBuffer{}
372 whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, daemonTestLogger(logs), fake.newClient)
373 require.NoError(t, err)
376 require.NoError(t, whatsapp.Close())
379 return whatsapp, fake, logs
382 // whatsappTestSession writes a session database with mode 0600 to the data
383 // directory dir. When linked is true, it holds a device linked to
384 // whatsappTestNumber and whatsappTestLID, and else no device.
385 func whatsappTestSession(t *testing.T, dir string, linked bool) {
388 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
389 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
390 require.NoError(t, os.WriteFile(path, nil, 0o600))
392 address, err := whatsappSessionAddress(path)
393 require.NoError(t, err)
395 container, err := sqlstore.New(t.Context(), "sqlite", address, waLog.Noop)
396 require.NoError(t, err)
399 device := container.NewDevice()
400 jid := types.NewADJID(whatsappTestNumber, 0, 1)
402 device.LID = types.NewADJID(whatsappTestLID, 0, 1)
403 device.LID.Server = types.HiddenUserServer
404 device.Account = &waAdv.ADVSignedDeviceIdentity{
406 AccountSignature: make([]byte, 64),
407 AccountSignatureKey: make([]byte, 32),
408 DeviceSignature: make([]byte, 64),
410 require.NoError(t, device.Save(t.Context()))
413 require.NoError(t, container.Close())
416 // whatsappTestMessage returns the event of the text message id of sender in
417 // chat at the time at. A sender with whatsappTestNumber is the user.
418 func whatsappTestMessage(chat, sender types.JID, id, text string, at time.Time) *events.Message {
419 return &events.Message{
420 Info: types.MessageInfo{
421 MessageSource: types.MessageSource{
424 IsFromMe: sender.User == whatsappTestNumber,
425 IsGroup: chat.Server == types.GroupServer,
430 Message: &waE2E.Message{
431 Conversation: new(text),
436 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
437 // after the log holds at least one message.
438 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
441 require.Eventually(t, func() bool {
442 return memory.Len() > 0
443 }, 10*time.Second, time.Millisecond)
447 for id := range memory.Len() {
448 message, err := memory.Message(id)
449 require.NoError(t, err)
451 texts = append(texts, message.Text)
457 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
459 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
463 whatsappTestSession(t, dir, true)
465 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
467 return whatsapp, fake
470 // whatsappTestConnect waits for the connection of the daemon and gives it the
471 // events of a connection with an empty catch-up.
472 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
476 require.True(t, fake.Emit(&events.Connected{}))
477 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
480 // whatsappTestContacts puts the contacts of the tests into the session of
481 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
482 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
485 contacts := whatsapp.device.Contacts
486 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
487 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
489 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
490 require.NoError(t, err)
491 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))
494 func whatsappRetryTest(t *testing.T) *WhatsAppRetryTest {
498 whatsappTestSession(t, dir, true)
500 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
501 whatsapp.clock = time.Now
502 loop, events := newTestIdleTurnLoop(t, whatsapp)
504 return &WhatsAppRetryTest{