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

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

W5Pass2ContactUtilsTest.kt168 lines · 8.1 KiBRaw
1package com.vayunmathur.communicate.whatsapp
2
3import android.app.Application
4import androidx.test.core.app.ApplicationProvider
5import androidx.test.ext.junit.runners.AndroidJUnit4
6import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData
7import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient
8import com.vayunmathur.communicate.data.whatsapp.WhatsAppContactSync
9import com.vayunmathur.communicate.data.whatsapp.WhatsAppMessage
10import com.vayunmathur.communicate.data.whatsapp.buildIncomingMediaAttachment
11import com.vayunmathur.communicate.data.whatsapp.cacheNotifyName
12import com.vayunmathur.communicate.data.whatsapp.downloadMedia
13import com.vayunmathur.communicate.data.whatsapp.inflateZlib
14import com.vayunmathur.communicate.data.whatsapp.isLoggedIn
15import com.vayunmathur.communicate.data.whatsapp.logoutRemote
16import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
17import com.vayunmathur.communicate.data.whatsapp.rememberInboundPoll
18import com.vayunmathur.communicate.data.whatsapp.resolveDeviceContactName
19import com.vayunmathur.communicate.data.whatsapp.resolveName
20import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket
21import com.google.protobuf.ByteString
22import kotlin.test.BeforeTest
23import kotlin.test.Test
24import kotlin.test.assertContentEquals
25import kotlin.test.assertEquals
26import kotlin.test.assertFalse
27import kotlin.test.assertNull
28import kotlin.test.assertTrue
29import kotlinx.coroutines.test.runTest
30import org.junit.runner.RunWith
31
32/**
33 * Pass-2 slice-1 (whatsapp): contact-sync phone normalization and the remaining
34 * client utility surface (zlib, media-attachment gating, login state, names).
35 */
36@RunWith(AndroidJUnit4::class)
37class W5Pass2ContactUtilsTest {
38
39 private val auth = WhatsAppAuthData(
40 phoneNumber = "+15550001", pushName = "Tester", wid = "[email protected]",
41 noisePrivateKey = "", noisePublicKey = "", identityPrivateKey = "", identityPublicKey = "",
42 registrationId = 14, signedPreKeyId = 1, signedPreKeyPublic = "", signedPreKeyPrivate = "",
43 signedPreKeySignature = "", lid = "12345@lid",
44 )
45
46 private lateinit var app: Application
47
48 @BeforeTest
49 fun setUp() {
50 app = ApplicationProvider.getApplicationContext<Application>()
51 WhatsAppClient.appContext = app
52 WhatsAppClient.authData = auth
53 WhatsAppClient.db = null
54 WhatsAppClient.webSocket = WhatsAppSocket(auth)
55 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected
56 WhatsAppClient.nameCache.clear()
57 }
58
59 // ---- Contact sync normalization ----
60
61 @Test
62 fun `normalize E164 handles national and international forms`() {
63 assertEquals("+16502530000", WhatsAppContactSync.normalizeE164("(650) 253-0000", "US"))
64 assertEquals("+16502530000", WhatsAppContactSync.normalizeE164("+1 650-253-0000", "US"))
65 assertEquals("+442071234567", WhatsAppContactSync.normalizeE164("020 7123 4567", "GB"))
66 assertEquals("+442071234567", WhatsAppContactSync.normalizeE164("+44 20 7123 4567", "US"))
67 assertEquals("+919876543210", WhatsAppContactSync.normalizeE164("098765 43210", "IN"))
68 }
69
70 @Test
71 fun `normalize E164 rejects garbage`() {
72 assertNull(WhatsAppContactSync.normalizeE164("", "US"))
73 assertNull(WhatsAppContactSync.normalizeE164("not a number", "US"))
74 assertNull(WhatsAppContactSync.normalizeE164("123", "US"))
75 assertNull(WhatsAppContactSync.normalizeE164("555-123", "ZZ"))
76 }
77
78 @Test
79 fun `contact sync device reads are permission gated`() {
80 assertEquals("US", WhatsAppContactSync.defaultRegion(app).let { it.ifEmpty { "US" } })
81 assertTrue(WhatsAppContactSync.readDeviceContacts(app).isEmpty()) // no READ_CONTACTS in tests
82 val result = WhatsAppContactSync.DeviceContact("+1555", "A")
83 assertEquals("+1555", result.e164)
84 val sync = WhatsAppContactSync.SyncResult(deviceCount = 3, e164Count = 2, onWhatsAppCount = 1)
85 assertEquals(3, sync.deviceCount)
86 assertNull(sync.transportError)
87 assertEquals("x", WhatsAppContactSync.SyncResult(0, 0, 0, "x").transportError)
88 }
89
90 // ---- Client utils ----
91
92 @Test
93 fun `inflate zlib round trips and tolerates garbage`() {
94 val raw = "history blob contents, repeated repeated repeated".toByteArray()
95 val compressed = java.io.ByteArrayOutputStream().also { out ->
96 java.util.zip.DeflaterOutputStream(out).use { it.write(raw) }
97 }.toByteArray()
98 assertContentEquals(raw, WhatsAppClient.inflateZlib(compressed))
99 assertEquals(0, WhatsAppClient.inflateZlib(byteArrayOf()).size)
100 kotlin.test.assertFailsWith<java.util.zip.DataFormatException> { WhatsAppClient.inflateZlib(byteArrayOf(1, 2, 3)) }
101 }
102
103 @Test
104 fun `login state follows auth and connection`() {
105 assertTrue(WhatsAppClient.isLoggedIn())
106 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Idle
107 assertFalse(WhatsAppClient.isLoggedIn())
108 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected
109 WhatsAppClient.authData = null
110 assertFalse(WhatsAppClient.isLoggedIn())
111 WhatsAppClient.authData = auth
112 assertTrue(WhatsAppClient.isLoggedIn())
113 }
114
115 @Test
116 fun `media attachment gating rejects non media and keyless media`() = runTest {
117 val text = WhatsAppE2EProto.Message.newBuilder().setConversation("hi").build()
118 assertNull(WhatsAppClient.buildIncomingMediaAttachment(text, "m1"))
119 // An image with no media key and no URL cannot be fetched.
120 val image = WhatsAppE2EProto.Message.newBuilder()
121 .setImageMessage(WhatsAppE2EProto.ImageMessage.newBuilder().setMimetype("image/jpeg"))
122 .build()
123 assertNull(WhatsAppClient.buildIncomingMediaAttachment(image, "m2"))
124 // A document with a key but no URL/direct path also stops before any download.
125 val doc = WhatsAppE2EProto.Message.newBuilder()
126 .setDocumentMessage(
127 WhatsAppE2EProto.DocumentMessage.newBuilder()
128 .setMediaKey(ByteString.copyFrom(ByteArray(32)))
129 .setFileName("report.pdf"),
130 )
131 .build()
132 assertNull(WhatsAppClient.buildIncomingMediaAttachment(doc, "m3"))
133 // A direct download to an unreachable loopback port fails soft to null.
134 assertNull(WhatsAppClient.downloadMedia("http://127.0.0.1:1/media", ByteArray(32), "image"))
135 }
136
137 @Test
138 fun `name resolution prefers cache then falls back to the number`() = runTest {
139 WhatsAppClient.nameCache["[email protected]"] = "Cached Name"
140 assertEquals("Cached Name", WhatsAppClient.resolveName("[email protected]"))
141 val resolved = WhatsAppClient.resolveName("[email protected]")
142 assertTrue(resolved.contains("999"), resolved)
143 assertNull(WhatsAppClient.resolveDeviceContactName(null))
144 assertNull(WhatsAppClient.resolveDeviceContactName(""))
145 // No device contact in the harness: lookup resolves to null, never throws.
146 assertNull(WhatsAppClient.resolveDeviceContactName("+1999"))
147 }
148
149 @Test
150 fun `notify name caching and inbound poll memory are safe without a database`() = runTest {
151 val node = com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.Node(
152 tag = "message",
153 attrs = mapOf("from" to "[email protected]", "notify" to "Notify Name"),
154 )
155 WhatsAppClient.cacheNotifyName(node, "[email protected]")
156 assertEquals("Notify Name", WhatsAppClient.nameCache["[email protected]"])
157 val message = WhatsAppMessage(
158 id = "p1", from = "[email protected]", to = "[email protected]",
159 body = "vote?", timestamp = 1L, type = "text", messageType = "poll",
160 )
161 WhatsAppClient.rememberInboundPoll(message)
162 // Logging out sends the stanza best-effort; stop() itself is gated on
163 // init() having run, which tests never do, so the state is untouched.
164 WhatsAppClient.logoutRemote()
165 Thread.sleep(300)
166 assertTrue(WhatsAppClient.state.value is WhatsAppClient.State.Connected)
167 }
168}