Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / whatsapp / W5Slice1ClientUtilsTest.kt

W5Slice1ClientUtilsTest.kt237 lines · 10.1 KiBRaw
1package com.vayunmathur.communicate.whatsapp
2
3import androidx.test.core.app.ApplicationProvider
4import androidx.test.ext.junit.runners.AndroidJUnit4
5import com.vayunmathur.communicate.data.whatsapp.ContactSuggestion
6import com.vayunmathur.communicate.data.whatsapp.MessageSource
7import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData
8import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient
9import com.vayunmathur.communicate.data.whatsapp.WhatsAppMessage
10import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol
11import com.vayunmathur.communicate.data.whatsapp.cacheNotifyName
12import com.vayunmathur.communicate.data.whatsapp.extractJid
13import com.vayunmathur.communicate.data.whatsapp.extractMessageId
14import com.vayunmathur.communicate.data.whatsapp.generateClientId
15import com.vayunmathur.communicate.data.whatsapp.generateMessageId
16import com.vayunmathur.communicate.data.whatsapp.generateRef
17import com.vayunmathur.communicate.data.whatsapp.generateToken
18import com.vayunmathur.communicate.data.whatsapp.getContactSuggestions
19import com.vayunmathur.communicate.data.whatsapp.inflateZlib
20import com.vayunmathur.communicate.data.whatsapp.isLoggedIn
21import com.vayunmathur.communicate.data.whatsapp.isOwnJid
22import com.vayunmathur.communicate.data.whatsapp.resolveChatSender
23import com.vayunmathur.communicate.data.whatsapp.resolveJID
24import com.vayunmathur.communicate.data.whatsapp.resolveMentionsInBody
25import com.vayunmathur.communicate.data.whatsapp.resolveName
26import com.vayunmathur.communicate.data.whatsapp.trackUndecryptable
27import java.io.ByteArrayOutputStream
28import java.util.zip.Deflater
29import kotlinx.coroutines.test.runTest
30import org.junit.runner.RunWith
31import kotlin.test.BeforeTest
32import kotlin.test.Test
33import kotlin.test.assertEquals
34import kotlin.test.assertFalse
35import kotlin.test.assertNull
36import kotlin.test.assertTrue
37
38/**
39 * Slice 1 (w5): WhatsAppClient pure helpers (WhatsAppClientUtils.kt) that need no
40 * socket/auth: JID extraction, own-JID checks, LID resolution, zlib inflate,
41 * mention resolution, chat-sender routing, contact suggestions, id generators.
42 *
43 * Robolectric: the client singleton touches Android (Base64, appContext on some
44 * paths); these tests init() the singleton with the test application context.
45 * NOTE: if the lead fixes Robolectric exec capture, this file's coverage will
46 * start counting; until then it still guards behavior.
47 */
48@RunWith(AndroidJUnit4::class)
49class W5Slice1ClientUtilsTest {
50
51 // NOTE: WhatsAppClient.init() is NOT called: it builds the SQLCipher database via
52 // the AndroidKeyStore, which Robolectric does not provide. The helpers under test
53 // (extractJid, resolveJID, inflateZlib, generators, caches) do not touch appContext/db.
54
55 @Test
56 fun extractJid_stripsAllWaPrefixes() {
57 assertEquals("[email protected]", WhatsAppClient.extractJid("wa:wa:[email protected]"))
58 assertEquals("[email protected]", WhatsAppClient.extractJid("wa:[email protected]"))
59 assertEquals("[email protected]", WhatsAppClient.extractJid("[email protected]"))
60 assertNull(WhatsAppClient.extractJid("wa:"))
61 }
62
63 @Test
64 fun extractMessageId_stripsWaPrefixes() {
65 assertEquals("ABC", WhatsAppClient.extractMessageId("wa:wa:ABC"))
66 assertEquals("ABC", WhatsAppClient.extractMessageId("ABC"))
67 }
68
69 @Test
70 fun isOwnJid_cases() {
71 assertFalse(WhatsAppClient.isOwnJid(null))
72 assertFalse(WhatsAppClient.isOwnJid(""))
73 // no auth loaded in test: only structural checks
74 assertFalse(WhatsAppClient.isOwnJid("[email protected]"))
75 }
76
77 @Test
78 fun isOwnJid_withAuth_matchesWidAndLidBareUser() {
79 WhatsAppClient.authData = WhatsAppAuthData(
80 phoneNumber = "+15550001", pushName = "", wid = "[email protected]",
81 noisePrivateKey = "", noisePublicKey = "", identityPrivateKey = "", identityPublicKey = "",
82 registrationId = 1, signedPreKeyId = 1, signedPreKeyPublic = "", signedPreKeyPrivate = "",
83 signedPreKeySignature = "", lid = "12345@lid",
84 )
85 try {
86 assertTrue(WhatsAppClient.isOwnJid("[email protected]"))
87 assertTrue(WhatsAppClient.isOwnJid("15550001:[email protected]"))
88 assertTrue(WhatsAppClient.isOwnJid("12345@lid"))
89 assertFalse(WhatsAppClient.isOwnJid("[email protected]"))
90 } finally {
91 WhatsAppClient.authData = null
92 }
93 }
94
95 @Test
96 fun resolveJID_cases() {
97 // non-LID passes through
98 assertEquals("[email protected]", WhatsAppClient.resolveJID("[email protected]"))
99 // cached mapping wins
100 WhatsAppClient.lidToPhoneMap["abc@lid"] = "[email protected]"
101 try {
102 assertEquals("[email protected]", WhatsAppClient.resolveJID("abc@lid"))
103 // bot JIDs pass through
104 assertEquals("x@bot", WhatsAppClient.resolveJID("x@bot"))
105 // unknown LID passes through
106 assertEquals("zzz@lid", WhatsAppClient.resolveJID("zzz@lid"))
107 } finally {
108 WhatsAppClient.lidToPhoneMap.clear()
109 }
110 }
111
112 @Test
113 fun resolveJID_ownLid_mapsToWid() {
114 WhatsAppClient.authData = WhatsAppAuthData(
115 phoneNumber = "+1", pushName = "", wid = "[email protected]",
116 noisePrivateKey = "", noisePublicKey = "", identityPrivateKey = "", identityPublicKey = "",
117 registrationId = 1, signedPreKeyId = 1, signedPreKeyPublic = "", signedPreKeyPrivate = "",
118 signedPreKeySignature = "", lid = "777@lid",
119 )
120 try {
121 assertEquals("[email protected]", WhatsAppClient.resolveJID("777@lid"))
122 } finally {
123 WhatsAppClient.authData = null
124 }
125 }
126
127 @Test
128 fun trackUndecryptable_countsPerSender() {
129 val node = WhatsAppProtocol.Node(tag = "message", attrs = mapOf("from" to "[email protected]"))
130 WhatsAppClient.trackUndecryptable(node)
131 WhatsAppClient.trackUndecryptable(node)
132 assertEquals(2, WhatsAppClient.undecryptableTracker["[email protected]"])
133 // missing from: no-op
134 WhatsAppClient.trackUndecryptable(WhatsAppProtocol.Node(tag = "message"))
135 WhatsAppClient.undecryptableTracker.clear()
136 }
137
138 @Test
139 fun inflateZlib_roundTrips() {
140 val raw = "history blob bytes 1234567890 repeated ".repeat(20).toByteArray()
141 val deflater = Deflater()
142 deflater.setInput(raw)
143 deflater.finish()
144 val bos = ByteArrayOutputStream()
145 val buf = ByteArray(1024)
146 while (!deflater.finished()) bos.write(buf, 0, deflater.deflate(buf))
147 deflater.end()
148 assertTrue(WhatsAppClient.inflateZlib(bos.toByteArray()).contentEquals(raw))
149 }
150
151 @Test
152 fun generators_shapes() {
153 assertTrue(WhatsAppClient.generateMessageId().startsWith("3EB0"))
154 assertTrue(WhatsAppClient.generateRef().isNotEmpty())
155 assertTrue(WhatsAppClient.generateClientId().isNotEmpty())
156 assertTrue(WhatsAppClient.generateToken().isNotEmpty())
157 // 24 random bytes -> 32 base64 chars (no wrap)
158 assertEquals(32, WhatsAppClient.generateToken().length)
159 }
160
161 @Test
162 fun resolveName_botAndPhone() = runTest {
163 assertEquals("Meta AI", WhatsAppClient.resolveName("123@bot"))
164 assertEquals("+15550001", WhatsAppClient.resolveName("[email protected]"))
165 assertEquals("+15550001", WhatsAppClient.resolveName("15550001:[email protected]"))
166 // cached notify name wins
167 WhatsAppClient.nameCache["[email protected]"] = "Zed"
168 try {
169 assertEquals("Zed", WhatsAppClient.resolveName("[email protected]"))
170 } finally {
171 WhatsAppClient.nameCache.remove("[email protected]")
172 }
173 }
174
175 @Test
176 fun resolveMentionsInBody_replacesTokens() = runTest {
177 assertEquals("no mentions", WhatsAppClient.resolveMentionsInBody("no mentions", emptyList()))
178 assertEquals("hi @+1555", WhatsAppClient.resolveMentionsInBody("hi @1555", listOf("[email protected]")))
179 }
180
181 @Test
182 fun resolveChatSender_groupOwnParticipant_isFromMe() {
183 val msg = WhatsAppMessage(
184 id = "g1", from = "[email protected]", to = "", body = "x", timestamp = 1, type = "text",
185 participant = "[email protected]",
186 )
187 WhatsAppClient.authData = WhatsAppAuthData(
188 phoneNumber = "+1", pushName = "", wid = "[email protected]",
189 noisePrivateKey = "", noisePublicKey = "", identityPrivateKey = "", identityPublicKey = "",
190 registrationId = 1, signedPreKeyId = 1, signedPreKeyPublic = "", signedPreKeyPrivate = "",
191 signedPreKeySignature = "",
192 )
193 try {
194 val (sender, fromMe) = WhatsAppClient.resolveChatSender(msg)
195 assertEquals("[email protected]", sender)
196 assertTrue(fromMe)
197 } finally {
198 WhatsAppClient.authData = null
199 }
200 }
201
202 @Test
203 fun cacheNotifyName_storesNonEmpty() {
204 WhatsAppClient.cacheNotifyName(
205 WhatsAppProtocol.Node(tag = "message", attrs = mapOf("notify" to "Al")),
206 "[email protected]",
207 )
208 try {
209 assertEquals("Al", WhatsAppClient.nameCache["[email protected]"])
210 } finally {
211 WhatsAppClient.nameCache.remove("[email protected]")
212 }
213 WhatsAppClient.cacheNotifyName(WhatsAppProtocol.Node(tag = "message"), "[email protected]")
214 assertNull(WhatsAppClient.nameCache["[email protected]"])
215 }
216
217 @Test
218 fun contactSuggestions_filtersCache() {
219 WhatsAppClient.nameCache["a"] = "Alice Anderson"
220 WhatsAppClient.nameCache["b"] = "Bob"
221 try {
222 val hits = WhatsAppClient.getContactSuggestions("ali")
223 assertEquals(1, hits.size)
224 assertEquals("Alice Anderson", hits[0].displayName)
225 assertEquals(MessageSource.WHATSAPP, hits[0].source)
226 assertEquals(ContactSuggestion("Alice Anderson", null, null, MessageSource.WHATSAPP), hits[0])
227 } finally {
228 WhatsAppClient.nameCache.clear()
229 }
230 }
231
232 @Test
233 fun isLoggedIn_falseWithoutAuth() {
234 WhatsAppClient.authData = null
235 assertFalse(WhatsAppClient.isLoggedIn())
236 }
237}