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 downloadWait time.Duration
89 downloads []whatsmeow.DownloadableMessage
92 sent []WhatsAppFakeSend
93 connections []context.Context
96 // ConnectContext keeps ctx and tells the test that the daemon connected.
97 func (f *WhatsAppFake) ConnectContext(ctx context.Context) error {
100 f.connections = append(f.connections, ctx)
101 f.connectTimes = append(f.connectTimes, time.Now())
104 f.connects <- struct{}{}
107 defer f.mutex.Unlock()
109 if len(f.connectErrors) > 0 {
110 err := f.connectErrors[0]
111 f.connectErrors = f.connectErrors[1:]
119 // Connections returns the contexts of the connections, in order.
120 func (f *WhatsAppFake) Connections() []context.Context {
122 defer f.mutex.Unlock()
124 return slices.Clone(f.connections)
127 // ConnectionTimes returns the time of each connection call, in order.
128 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
130 defer f.mutex.Unlock()
132 return slices.Clone(f.connectTimes)
135 // Disconnect does nothing.
136 func (f *WhatsAppFake) Disconnect() {
139 // GetQRChannel gives a new channel of pairing items to the test.
140 func (f *WhatsAppFake) GetQRChannel(_ context.Context) (<-chan whatsmeow.QRChannelItem, error) {
141 items := make(chan whatsmeow.QRChannelItem, 8)
147 // PairPhone keeps phone and returns whatsappTestCode.
148 func (f *WhatsAppFake) PairPhone(_ context.Context, phone string, _ bool, _ whatsmeow.PairClientType, _ string) (string, error) {
150 defer f.mutex.Unlock()
152 f.phones = append(f.phones, phone)
154 return whatsappTestCode, nil
157 // Logout counts the logouts and returns logoutErr.
158 func (f *WhatsAppFake) Logout(_ context.Context) error {
160 defer f.mutex.Unlock()
167 // GetJoinedGroups returns groups.
168 func (f *WhatsAppFake) GetJoinedGroups(_ context.Context) ([]*types.GroupInfo, error) {
170 defer f.mutex.Unlock()
175 // Download waits for downloadWait, records the request, and returns the made-up
176 // image or downloadErr. A canceled context ends the wait.
177 func (f *WhatsAppFake) Download(ctx context.Context, message whatsmeow.DownloadableMessage) ([]byte, error) {
178 if f.downloadWait > 0 {
179 timer := time.NewTimer(f.downloadWait)
184 return nil, ctx.Err()
190 defer f.mutex.Unlock()
192 f.downloads = append(f.downloads, message)
194 return slices.Clone(f.downloadData), f.downloadErr
197 // Downloads returns the media requested from the fake.
198 func (f *WhatsAppFake) Downloads() []whatsmeow.DownloadableMessage {
200 defer f.mutex.Unlock()
202 return slices.Clone(f.downloads)
205 // GenerateMessageID returns a new message ID.
206 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
208 defer f.mutex.Unlock()
210 return fmt.Sprintf("MSG%d", len(f.sent)+1)
213 // SendMessage keeps the send and returns sendErr.
214 func (f *WhatsAppFake) SendMessage(_ context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
216 defer f.mutex.Unlock()
218 f.sent = append(f.sent, WhatsAppFakeSend{
220 text: message.GetConversation(),
224 if f.sendErr != nil {
225 return whatsmeow.SendResponse{}, f.sendErr
228 return whatsmeow.SendResponse{
229 Timestamp: whatsappTestSendTime,
233 // Sent returns the sends.
234 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
236 defer f.mutex.Unlock()
238 return slices.Clone(f.sent)
241 // Phones returns the phone numbers of the pairings.
242 func (f *WhatsAppFake) Phones() []string {
244 defer f.mutex.Unlock()
246 return append([]string{}, f.phones...)
249 // Logouts returns the number of logouts.
250 func (f *WhatsAppFake) Logouts() int {
252 defer f.mutex.Unlock()
257 // Emit gives event to the handler of the daemon and returns its answer.
258 func (f *WhatsAppFake) Emit(event any) bool {
267 // newClient keeps handle and returns the fake as the client of device.
268 func (f *WhatsAppFake) newClient(_ *store.Device, handle func(event any) bool) WhatsAppClient {
270 defer f.mutex.Unlock()
277 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
279 type WhatsAppFakeSend struct {
285 // whatsappStartTest opens the WhatsApp of the data directory dir with a fake
286 // client and the test clock, and closes it at the end of the test. The daemon
287 // log goes to the returned buffer.
288 func whatsappStartTest(t *testing.T, dir string, clock *TestClock) (*WhatsApp, *WhatsAppFake, *SyncBuffer) {
291 fake := &WhatsAppFake{
292 connects: make(chan struct{}, 16),
293 pairings: make(chan chan whatsmeow.QRChannelItem, 16),
296 logs := &SyncBuffer{}
297 whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, daemonTestLogger(logs), fake.newClient)
298 require.NoError(t, err)
301 require.NoError(t, whatsapp.Close())
304 return whatsapp, fake, logs
307 // whatsappTestSession writes a session database with mode 0600 to the data
308 // directory dir. When linked is true, it holds a device linked to
309 // whatsappTestNumber and whatsappTestLID, and else no device.
310 func whatsappTestSession(t *testing.T, dir string, linked bool) {
313 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
314 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
315 require.NoError(t, os.WriteFile(path, nil, 0o600))
317 address, err := whatsappSessionAddress(path)
318 require.NoError(t, err)
320 container, err := sqlstore.New(t.Context(), "sqlite", address, waLog.Noop)
321 require.NoError(t, err)
324 device := container.NewDevice()
325 jid := types.NewADJID(whatsappTestNumber, 0, 1)
327 device.LID = types.NewADJID(whatsappTestLID, 0, 1)
328 device.LID.Server = types.HiddenUserServer
329 device.Account = &waAdv.ADVSignedDeviceIdentity{
331 AccountSignature: make([]byte, 64),
332 AccountSignatureKey: make([]byte, 32),
333 DeviceSignature: make([]byte, 64),
335 require.NoError(t, device.Save(t.Context()))
338 require.NoError(t, container.Close())
341 // whatsappDiscardLog is a logger for a WhatsApp whose log a test does not read.
342 func whatsappDiscardLog() *slog.Logger {
343 return slog.New(slog.DiscardHandler)
346 // whatsappTestMessage returns the event of the text message id of sender in
347 // chat at the time at. A sender with whatsappTestNumber is the user.
348 func whatsappTestMessage(chat, sender types.JID, id, text string, at time.Time) *events.Message {
349 return &events.Message{
350 Info: types.MessageInfo{
351 MessageSource: types.MessageSource{
354 IsFromMe: sender.User == whatsappTestNumber,
355 IsGroup: chat.Server == types.GroupServer,
360 Message: &waE2E.Message{
361 Conversation: new(text),
366 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
367 // after the log holds at least one message.
368 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
371 require.Eventually(t, func() bool {
372 return memory.Len() > 0
373 }, 10*time.Second, time.Millisecond)
377 for id := range memory.Len() {
378 message, err := memory.Message(id)
379 require.NoError(t, err)
381 texts = append(texts, message.Text)
387 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
388 // directory, with a quiet time of 50 ms for its batches.
389 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
393 whatsappTestSession(t, dir, true)
395 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
396 whatsapp.state.quiet = 50 * time.Millisecond
398 return whatsapp, fake
401 // whatsappTestConnect waits for the connection of the daemon and gives it the
402 // events of a connection with an empty catch-up.
403 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
407 require.True(t, fake.Emit(&events.Connected{}))
408 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
411 // whatsappTestContacts puts the contacts of the tests into the session of
412 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
413 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
416 contacts := whatsapp.device.Contacts
417 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
418 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
420 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
421 require.NoError(t, err)
422 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))