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 // ConnectContext keeps ctx and tells the test that the daemon connected.
100 func (f *WhatsAppFake) ConnectContext(ctx context.Context) error {
103 f.connections = append(f.connections, ctx)
104 f.connectTimes = append(f.connectTimes, time.Now())
107 f.connects <- struct{}{}
110 defer f.mutex.Unlock()
112 if len(f.connectErrors) > 0 {
113 err := f.connectErrors[0]
114 f.connectErrors = f.connectErrors[1:]
122 // Connections returns the contexts of the connections, in order.
123 func (f *WhatsAppFake) Connections() []context.Context {
125 defer f.mutex.Unlock()
127 return slices.Clone(f.connections)
130 // ConnectionTimes returns the time of each connection call, in order.
131 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
133 defer f.mutex.Unlock()
135 return slices.Clone(f.connectTimes)
138 // Disconnect does nothing.
139 func (f *WhatsAppFake) Disconnect() {
142 // GetQRChannel gives a new channel of pairing items to the test.
143 func (f *WhatsAppFake) GetQRChannel(_ context.Context) (<-chan whatsmeow.QRChannelItem, error) {
144 items := make(chan whatsmeow.QRChannelItem, 8)
150 // PairPhone keeps phone and returns whatsappTestCode.
151 func (f *WhatsAppFake) PairPhone(_ context.Context, phone string, _ bool, _ whatsmeow.PairClientType, _ string) (string, error) {
153 defer f.mutex.Unlock()
155 f.phones = append(f.phones, phone)
157 return whatsappTestCode, nil
160 // Logout counts the logouts and returns logoutErr.
161 func (f *WhatsAppFake) Logout(_ context.Context) error {
163 defer f.mutex.Unlock()
170 // GetJoinedGroups returns groups.
171 func (f *WhatsAppFake) GetJoinedGroups(_ context.Context) ([]*types.GroupInfo, error) {
173 defer f.mutex.Unlock()
178 // Download waits for downloadWait, records the request, and returns the made-up
179 // image or downloadErr. A canceled context ends the wait.
180 func (f *WhatsAppFake) Download(ctx context.Context, message whatsmeow.DownloadableMessage) ([]byte, error) {
181 if f.downloadWait > 0 {
182 timer := time.NewTimer(f.downloadWait)
187 return nil, ctx.Err()
193 defer f.mutex.Unlock()
195 f.downloads = append(f.downloads, message)
197 return slices.Clone(f.downloadData), f.downloadErr
200 // Downloads returns the media requested from the fake.
201 func (f *WhatsAppFake) Downloads() []whatsmeow.DownloadableMessage {
203 defer f.mutex.Unlock()
205 return slices.Clone(f.downloads)
208 // Upload records the pixels and returns made-up media metadata.
209 func (f *WhatsAppFake) Upload(_ context.Context, data []byte, mediaType whatsmeow.MediaType) (whatsmeow.UploadResponse, error) {
211 defer f.mutex.Unlock()
213 if mediaType != whatsmeow.MediaImage {
214 return whatsmeow.UploadResponse{}, fmt.Errorf("unexpected media type %q", mediaType)
217 f.uploads = append(f.uploads, slices.Clone(data))
218 if f.uploadErr != nil {
219 return whatsmeow.UploadResponse{}, f.uploadErr
222 return whatsmeow.UploadResponse{
223 URL: "https://example.com/image",
224 DirectPath: "/image",
225 MediaKey: []byte("made-up key"),
226 FileSHA256: []byte("made-up hash"),
227 FileEncSHA256: []byte("made-up encrypted hash"),
228 FileLength: uint64(len(data)),
232 // Uploads returns the pixels passed to Upload.
233 func (f *WhatsAppFake) Uploads() [][]byte {
235 defer f.mutex.Unlock()
237 return slices.Clone(f.uploads)
240 // ImageSends returns the outgoing image messages.
241 func (f *WhatsAppFake) ImageSends() []*waE2E.ImageMessage {
243 defer f.mutex.Unlock()
245 return slices.Clone(f.imageSends)
248 // GenerateMessageID returns a new message ID.
249 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
251 defer f.mutex.Unlock()
253 return fmt.Sprintf("MSG%d", len(f.sent)+1)
256 // SendMessage keeps the send and returns sendErr.
257 func (f *WhatsAppFake) SendMessage(_ context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
259 defer f.mutex.Unlock()
261 if message.GetImageMessage() != nil {
262 f.imageSends = append(f.imageSends, message.GetImageMessage())
265 f.sent = append(f.sent, WhatsAppFakeSend{
267 text: message.GetConversation(),
271 if f.sendErr != nil {
272 return whatsmeow.SendResponse{}, f.sendErr
275 return whatsmeow.SendResponse{
276 Timestamp: whatsappTestSendTime,
280 // Sent returns the sends.
281 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
283 defer f.mutex.Unlock()
285 return slices.Clone(f.sent)
288 // Phones returns the phone numbers of the pairings.
289 func (f *WhatsAppFake) Phones() []string {
291 defer f.mutex.Unlock()
293 return append([]string{}, f.phones...)
296 // Logouts returns the number of logouts.
297 func (f *WhatsAppFake) Logouts() int {
299 defer f.mutex.Unlock()
304 // Emit gives event to the handler of the daemon and returns its answer.
305 func (f *WhatsAppFake) Emit(event any) bool {
314 // newClient keeps handle and returns the fake as the client of device.
315 func (f *WhatsAppFake) newClient(_ *store.Device, handle func(event any) bool) WhatsAppClient {
317 defer f.mutex.Unlock()
324 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
326 type WhatsAppFakeSend struct {
332 // WhatsAppRetryTest runs WhatsApp without a model or network client call. All
333 // timers and channels belong to its synctest bubble, so backoff uses fake time.
334 type WhatsAppRetryTest struct {
339 events *TurnEventRecorder
340 cancel context.CancelFunc
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{