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 sent []WhatsAppFakeSend
90 connections []context.Context
93 // ConnectContext keeps ctx and tells the test that the daemon connected.
94 func (f *WhatsAppFake) ConnectContext(ctx context.Context) error {
96 f.connections = append(f.connections, ctx)
97 f.connectTimes = append(f.connectTimes, time.Now())
100 f.connects <- struct{}{}
103 defer f.mutex.Unlock()
105 if len(f.connectErrors) > 0 {
106 err := f.connectErrors[0]
107 f.connectErrors = f.connectErrors[1:]
114 // Connections returns the contexts of the connections, in order.
115 func (f *WhatsAppFake) Connections() []context.Context {
117 defer f.mutex.Unlock()
119 return slices.Clone(f.connections)
122 // ConnectionTimes returns the time of each connection call, in order.
123 func (f *WhatsAppFake) ConnectionTimes() []time.Time {
125 defer f.mutex.Unlock()
127 return slices.Clone(f.connectTimes)
130 // Disconnect does nothing.
131 func (f *WhatsAppFake) Disconnect() {
134 // GetQRChannel gives a new channel of pairing items to the test.
135 func (f *WhatsAppFake) GetQRChannel(_ context.Context) (<-chan whatsmeow.QRChannelItem, error) {
136 items := make(chan whatsmeow.QRChannelItem, 8)
142 // PairPhone keeps phone and returns whatsappTestCode.
143 func (f *WhatsAppFake) PairPhone(_ context.Context, phone string, _ bool, _ whatsmeow.PairClientType, _ string) (string, error) {
145 defer f.mutex.Unlock()
147 f.phones = append(f.phones, phone)
149 return whatsappTestCode, nil
152 // Logout counts the logouts and returns logoutErr.
153 func (f *WhatsAppFake) Logout(_ context.Context) error {
155 defer f.mutex.Unlock()
162 // GetJoinedGroups returns groups.
163 func (f *WhatsAppFake) GetJoinedGroups(_ context.Context) ([]*types.GroupInfo, error) {
165 defer f.mutex.Unlock()
170 // GenerateMessageID returns a new message ID.
171 func (f *WhatsAppFake) GenerateMessageID() types.MessageID {
173 defer f.mutex.Unlock()
175 return fmt.Sprintf("MSG%d", len(f.sent)+1)
178 // SendMessage keeps the send and returns sendErr.
179 func (f *WhatsAppFake) SendMessage(_ context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
181 defer f.mutex.Unlock()
183 f.sent = append(f.sent, WhatsAppFakeSend{
185 text: message.GetConversation(),
189 if f.sendErr != nil {
190 return whatsmeow.SendResponse{}, f.sendErr
193 return whatsmeow.SendResponse{
194 Timestamp: whatsappTestSendTime,
198 // Sent returns the sends.
199 func (f *WhatsAppFake) Sent() []WhatsAppFakeSend {
201 defer f.mutex.Unlock()
203 return slices.Clone(f.sent)
206 // Phones returns the phone numbers of the pairings.
207 func (f *WhatsAppFake) Phones() []string {
209 defer f.mutex.Unlock()
211 return append([]string{}, f.phones...)
214 // Logouts returns the number of logouts.
215 func (f *WhatsAppFake) Logouts() int {
217 defer f.mutex.Unlock()
222 // Emit gives event to the handler of the daemon and returns its answer.
223 func (f *WhatsAppFake) Emit(event any) bool {
231 // newClient keeps handle and returns the fake as the client of device.
232 func (f *WhatsAppFake) newClient(_ *store.Device, handle func(event any) bool) WhatsAppClient {
234 defer f.mutex.Unlock()
241 // WhatsAppFakeSend is one send of the fake: the chat, the text, and the message
243 type WhatsAppFakeSend struct {
249 // whatsappStartTest opens the WhatsApp of the data directory dir with a fake
250 // client and the test clock, and closes it at the end of the test. The daemon
251 // log goes to the returned buffer.
252 func whatsappStartTest(t *testing.T, dir string, clock *TestClock) (*WhatsApp, *WhatsAppFake, *SyncBuffer) {
255 fake := &WhatsAppFake{
256 connects: make(chan struct{}, 16),
257 pairings: make(chan chan whatsmeow.QRChannelItem, 16),
260 logs := &SyncBuffer{}
261 whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, log.New(logs, "", 0), fake.newClient)
262 require.NoError(t, err)
265 require.NoError(t, whatsapp.Close())
268 return whatsapp, fake, logs
271 // whatsappTestSession writes a session database with mode 0600 to the data
272 // directory dir. When linked is true, it holds a device linked to
273 // whatsappTestNumber and whatsappTestLID, and else no device.
274 func whatsappTestSession(t *testing.T, dir string, linked bool) {
277 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
278 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
279 require.NoError(t, os.WriteFile(path, nil, 0o600))
281 address, err := whatsappSessionAddress(path)
282 require.NoError(t, err)
284 container, err := sqlstore.New(t.Context(), "sqlite", address, waLog.Noop)
285 require.NoError(t, err)
288 device := container.NewDevice()
289 jid := types.NewADJID(whatsappTestNumber, 0, 1)
291 device.LID = types.NewADJID(whatsappTestLID, 0, 1)
292 device.LID.Server = types.HiddenUserServer
293 device.Account = &waAdv.ADVSignedDeviceIdentity{
295 AccountSignature: make([]byte, 64),
296 AccountSignatureKey: make([]byte, 32),
297 DeviceSignature: make([]byte, 64),
299 require.NoError(t, device.Save(t.Context()))
302 require.NoError(t, container.Close())
305 // whatsappDiscardLog is a logger for a WhatsApp whose log a test does not read.
306 func whatsappDiscardLog() *log.Logger {
307 return log.New(io.Discard, "", 0)
310 // whatsappTestMessage returns the event of the text message id of sender in
311 // chat at the time at. A sender with whatsappTestNumber is the user.
312 func whatsappTestMessage(chat, sender types.JID, id, text string, at time.Time) *events.Message {
313 return &events.Message{
314 Info: types.MessageInfo{
315 MessageSource: types.MessageSource{
318 IsFromMe: sender.User == whatsappTestNumber,
319 IsGroup: chat.Server == types.GroupServer,
324 Message: &waE2E.Message{
325 Conversation: new(text),
330 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
331 // after the log holds at least one message.
332 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
335 require.Eventually(t, func() bool {
336 return memory.Len() > 0
337 }, 10*time.Second, time.Millisecond)
340 for id := range memory.Len() {
341 message, err := memory.Message(id)
342 require.NoError(t, err)
344 texts = append(texts, message.Text)
350 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
351 // directory, with a quiet time of 50 ms for its batches.
352 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
356 whatsappTestSession(t, dir, true)
357 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
358 whatsapp.state.quiet = 50 * time.Millisecond
360 return whatsapp, fake
363 // whatsappTestConnect waits for the connection of the daemon and gives it the
364 // events of a connection with an empty catch-up.
365 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
369 require.True(t, fake.Emit(&events.Connected{}))
370 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
373 // whatsappTestContacts puts the contacts of the tests into the session of
374 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
375 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
378 contacts := whatsapp.device.Contacts
379 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
380 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
381 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
382 require.NoError(t, err)
383 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))