coverage: camera/communicate pass with coverage-config update (c35)
- Commit
c9eed0eed8cbd9a358cbc207089e1614d45353b9- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-08 09:06 UTC (28 days ago)
- Parents
e3f13ff
Uncommitted remainder on cov/c35: LensSelector and GoogleVoice/RCS/WhatsApp client updates, TestCoverage config tweak, removal of superseded camera and communicate tests.
Diff
build-logic/src/main/kotlin/TestCoverage.kt
diff --git a/build-logic/src/main/kotlin/TestCoverage.kt b/build-logic/src/main/kotlin/TestCoverage.ktindex 59270d0f08..16e7dcd40f 100644--- a/build-logic/src/main/kotlin/TestCoverage.kt+++ b/build-logic/src/main/kotlin/TestCoverage.kt@@ -97,30 +97,6 @@ fun org.gradle.api.Project.mergedCoverageClassDirs(variant: String): org.gradle. layout.buildDirectory.dir("intermediates/javac/$variant/compile${cap}JavaWithJavac/classes"), ).builtBy("compile${cap}Kotlin", "compile${cap}JavaWithJavac").asFileTree.matching { MERGED_COVERAGE_EXCLUDES.forEach { exclude(it) }- // Generated protobuf classes. Protos with a custom java_outer_classname- // (communicate's WhatsAppE2EProto, SignalServiceProtos, ...) or a foreign- // java_package slip past the name patterns above, so drop every class whose- // top-level type has a generated source. Plain Files only: configuration-cache safe.- val protoRoots = listOf(- layout.buildDirectory.dir("generated/source/proto").get().asFile,- layout.buildDirectory.dir("generated/java/generate" + cap + "Proto").get().asFile,- )- exclude { el -> !el.isDirectory && isGeneratedProtoClass(protoRoots, el.relativePath.pathString) }- }-}--/**- * True when `a/b/Foo.class` or a nested `a/b/Foo` class has a generated `a/b/Foo.java` under- * `<root>/java/` or `<root>/<sourceSet>/java/` of one of [roots]: `generated/source/proto`- * (older protobuf-gradle-plugin layout) or `generated/java/generate<Variant>Proto` (current).- */-private fun isGeneratedProtoClass(roots: List<java.io.File>, classPath: String): Boolean {- if (!classPath.endsWith(".class")) return false- val topLevel = classPath.removeSuffix(".class").substringBefore('\u0024')- val source = "java/" + topLevel + ".java"- return roots.any { root ->- java.io.File(root, source).isFile ||- (root.listFiles() ?: emptyArray()).any { java.io.File(it, source).isFile } } }
camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt b/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.ktindex 640160f8f4..b2565b2c09 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt@@ -105,7 +105,7 @@ private fun readRawLensOrThrow(info: androidx.camera.core.CameraInfo): RawLens? return RawLens(cam2.getCameraId(), facing, focal, eq35, mono, intrinsic, zoomFloor) } -internal data class RawLens(+private data class RawLens( val id: String, val facing: LensFacing, val focalMm: Float,@@ -116,7 +116,7 @@ internal data class RawLens( ) /** Classifies one facing family into [PhysicalLens] entries with fallback priorities. */-internal fun buildFamily(facing: LensFacing, raws: List<RawLens>): List<PhysicalLens> {+private fun buildFamily(facing: LensFacing, raws: List<RawLens>): List<PhysicalLens> { val family = raws.filter { it.facing == facing }.sortedBy { it.focalMm } if (family.isEmpty()) return emptyList() val nonMono = family.filterNot { it.mono }
camera/src/test/java/com/vayunmathur/camera/platform/LensFamilyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/LensFamilyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/LensFamilyTest.ktdeleted file mode 100644index aee0603fc5..0000000000--- a/camera/src/test/java/com/vayunmathur/camera/platform/LensFamilyTest.kt+++ /dev/null@@ -1,104 +0,0 @@-package com.vayunmathur.camera.platform--import com.vayunmathur.camera.domain.LensFacing-import com.vayunmathur.camera.domain.LensType-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--/** Pass 3: facing-family classification in LensSelector (via the RawLens seam). */-class LensFamilyTest {-- private fun raw(- id: String, facing: LensFacing, focal: Float, eq: Float? = null,- mono: Boolean = false, minZoom: Float? = null,- ) = RawLens(id, facing, focal, eq, mono, intrinsicZoomRatio = null, minZoomRatio = minZoom)-- @Test fun facingConversions() {- assertEquals(- androidx.camera.core.CameraSelector.LENS_FACING_BACK, LensFacing.BACK.toSelectorInt())- assertEquals(- androidx.camera.core.CameraSelector.LENS_FACING_FRONT, LensFacing.FRONT.toSelectorInt())- assertEquals(LensFacing.BACK, androidx.camera.core.CameraSelector.LENS_FACING_BACK.toLensFacing())- assertEquals(LensFacing.FRONT, androidx.camera.core.CameraSelector.LENS_FACING_FRONT.toLensFacing())- assertEquals(null, androidx.camera.core.CameraSelector.LENS_FACING_EXTERNAL.toLensFacing())- assertEquals(null, 99.toLensFacing())- }-- @Test fun emptyAndSingleLensFamilies() {- assertTrue(buildFamily(LensFacing.BACK, emptyList()).isEmpty())- assertTrue(buildFamily(LensFacing.BACK, listOf(raw("f", LensFacing.FRONT, 3f))).isEmpty())- val single = buildFamily(LensFacing.BACK, listOf(raw("0", LensFacing.BACK, 4f, eq = 27f)))- assertEquals(1, single.size)- assertEquals(LensType.WIDE, single[0].lensType)- assertEquals("wide", single[0].labelKey)- assertEquals(0, single[0].fallbackPriority)- assertEquals(1f, single[0].nominalZoomRatio)- }-- @Test fun threeLensBackFamilyClassifiesByFocal() {- val family = buildFamily(- LensFacing.BACK,- listOf(- raw("uw", LensFacing.BACK, 2f, eq = 14f),- raw("wide", LensFacing.BACK, 4f, eq = 27f),- raw("tele", LensFacing.BACK, 8f, eq = 54f)))- val byId = family.associateBy { it.logicalCameraId }- assertEquals(LensType.ULTRA_WIDE, byId["uw"]?.lensType)- assertEquals("ultrawide", byId["uw"]?.labelKey)- assertEquals(1, byId["uw"]?.fallbackPriority)- assertEquals(LensType.WIDE, byId["wide"]?.lensType)- assertEquals(LensType.TELEPHOTO, byId["tele"]?.lensType)- assertEquals("tele", byId["tele"]?.labelKey)- assertEquals(2, byId["tele"]?.fallbackPriority)- assertEquals(0.5f, byId["uw"]?.nominalZoomRatio)- assertEquals(2f, byId["tele"]?.nominalZoomRatio)- }-- @Test fun frontFamilyReferenceIsFrontType() {- val family = buildFamily(- LensFacing.FRONT, listOf(raw("selfie", LensFacing.FRONT, 3f, eq = 25f)))- assertEquals(LensType.FRONT, family[0].lensType)- assertEquals("front", family[0].labelKey)- assertEquals(0, family[0].fallbackPriority)- }-- @Test fun monoWinsOverFocalHeuristic() {- val family = buildFamily(- LensFacing.BACK,- listOf(- raw("wide", LensFacing.BACK, 4f, eq = 27f),- raw("mono", LensFacing.BACK, 4f, eq = 27f, mono = true)))- val mono = family.first { it.logicalCameraId == "mono" }- assertEquals(LensType.MONOCHROME, mono.lensType)- assertEquals("mono", mono.labelKey)- assertEquals(3, mono.fallbackPriority)- }-- @Test fun nearWideLensStaysWide() {- // 3.6mm vs 4mm reference = 0.9 ratio, above the 0.85 UW threshold.- val family = buildFamily(- LensFacing.BACK,- listOf(- raw("wide", LensFacing.BACK, 4f, eq = 27f),- raw("near", LensFacing.BACK, 3.6f, eq = 24f)))- assertEquals(LensType.WIDE, family.first { it.logicalCameraId == "near" }.lensType)- }-- @Test fun coveredUltrawideIsDropped() {- // Wide's min zoom 0.5 covers the 0.5x UW stop: no separate pill.- val family = buildFamily(- LensFacing.BACK,- listOf(- raw("uw", LensFacing.BACK, 2f, eq = 14f),- raw("wide", LensFacing.BACK, 4f, eq = 27f, minZoom = 0.5f)))- assertEquals(listOf("wide"), family.map { it.logicalCameraId })- // Without the zoom-out reach, the UW pill remains.- val kept = buildFamily(- LensFacing.BACK,- listOf(- raw("uw", LensFacing.BACK, 2f, eq = 14f),- raw("wide", LensFacing.BACK, 4f, eq = 27f, minZoom = 1f)))- assertEquals(setOf("uw", "wide"), kept.map { it.logicalCameraId }.toSet())- }-}
camera/src/test/java/com/vayunmathur/camera/util/CameraPass3AnalyzerAndManualTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3AnalyzerAndManualTest.kt b/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3AnalyzerAndManualTest.ktdeleted file mode 100644index de0bffe304..0000000000--- a/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3AnalyzerAndManualTest.kt+++ /dev/null@@ -1,138 +0,0 @@-package com.vayunmathur.camera.util--import androidx.camera.core.ImageInfo-import androidx.camera.core.ImageProxy-import androidx.test.core.app.ApplicationProvider-import androidx.test.ext.junit.runners.AndroidJUnit4-import com.google.zxing.qrcode.QRCodeWriter-import java.lang.reflect.InvocationHandler-import java.lang.reflect.Proxy-import java.nio.ByteBuffer-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertNull-import kotlin.test.assertTrue-import org.junit.runner.RunWith--/** Pass 3: manual-exposure state, PhotoAnalyzer luminance cadence and QR decode. */-@RunWith(AndroidJUnit4::class)-class CameraPass3AnalyzerAndManualTest {-- private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()- private fun vm() = CameraViewModel(app)-- // ---- Manual controls ------ @Test fun exposureAndIsoIndicesClamp() {- val v = vm()- assertTrue(v.isExposureAuto())- v.setExposureTimeIndex(999)- assertEquals(CameraViewModel.EXPOSURE_TIME_STOPS.lastIndex, v.exposureTimeIndexMutable.value)- assertFalse(v.isExposureAuto())- v.setExposureTimeIndex(-3)- assertEquals(0, v.exposureTimeIndexMutable.value)- assertTrue(v.isExposureAuto())-- v.isoStopsMutable.value = listOf(100, 200, 400)- v.setManualIsoIndex(2)- assertEquals(200, v.manualIso())- assertFalse(v.isExposureAuto())- v.setManualIsoIndex(99)- assertEquals(3, v.manualIsoIndexMutable.value)- assertEquals(400, v.manualIso())- v.setManualIsoIndex(0)- assertNull(v.manualIso())- assertTrue(v.isExposureAuto())- // No bound camera: applying and reading ranges are safe no-ops.- v.applyManualControls()- v.readManualControlRanges()- assertNull(v.camera2ControlOrNull())- }-- // ---- PhotoAnalyzer ------ private class FakeFrame(- val width: Int,- val height: Int,- val yBytes: ByteArray,- val rotation: Int = 0,- ) {- var closed = false- fun proxy(): ImageProxy {- val planeHandler = InvocationHandler { _, method, _ ->- when (method.name) {- "getRowStride" -> width- "getPixelStride" -> 1- "getBuffer" -> ByteBuffer.wrap(yBytes.copyOf())- else -> null- }- }- val plane = Proxy.newProxyInstance(- javaClass.classLoader, arrayOf(ImageProxy.PlaneProxy::class.java), planeHandler)- as ImageProxy.PlaneProxy- val infoHandler = InvocationHandler { _, method, _ ->- when (method.name) {- "getTimestamp" -> 1234L- "getRotationDegrees" -> rotation- else -> null- }- }- val info = Proxy.newProxyInstance(- javaClass.classLoader, arrayOf(ImageInfo::class.java), infoHandler) as ImageInfo- val handler = InvocationHandler { _, method, _ ->- when (method.name) {- "getWidth" -> width- "getHeight" -> height- "getPlanes" -> arrayOf(plane)- "getImageInfo" -> info- "getFormat" -> android.graphics.ImageFormat.YUV_420_888- "close" -> { closed = true; null }- else -> null- }- }- return Proxy.newProxyInstance(- javaClass.classLoader, arrayOf(ImageProxy::class.java), handler) as ImageProxy- }- }-- @Test fun analyzerReportsAverageLuminanceAndCloses() {- var luminance: Float? = null- var qr: String? = null- val analyzer = PhotoAnalyzer(onLuminance = { luminance = it }, onQrDetected = { qr = it })- val frame = FakeFrame(64, 64, ByteArray(64 * 64) { 200.toByte() })- analyzer.analyze(frame.proxy())- assertEquals(200f, luminance)- assertNull(qr)- assertTrue(frame.closed)- }-- @Test fun analyzerDarkFrameLuminance() {- var luminance: Float? = null- val analyzer = PhotoAnalyzer(onLuminance = { luminance = it }, onQrDetected = {})- val frame = FakeFrame(32, 32, ByteArray(32 * 32) { 10.toByte() })- analyzer.analyze(frame.proxy())- assertEquals(10f, luminance)- assertTrue(frame.closed)- }-- @Test fun analyzerDecodesQrFromYPlane() {- val size = 200- val matrix = QRCodeWriter().encode("https://example.com/ff", com.google.zxing.BarcodeFormat.QR_CODE, size, size)- val bytes = ByteArray(size * size) { i ->- val x = i % size- val y = i / size- if (matrix.get(x, y)) 0.toByte() else 255.toByte()- }- var qr: String? = null- // Robolectric's elapsedRealtime starts at 0, and the analyzer caps- // QR decodes to one per 400 ms: advance past the first window.- org.robolectric.shadows.ShadowSystemClock.advanceBy(- 1, java.util.concurrent.TimeUnit.SECONDS)- val analyzer = PhotoAnalyzer(onLuminance = {}, onQrDetected = { qr = it })- val frame = FakeFrame(size, size, bytes)- analyzer.analyze(frame.proxy())- assertEquals("https://example.com/ff", qr)- assertTrue(frame.closed)- }-}
camera/src/test/java/com/vayunmathur/camera/util/CameraPass3ProcessingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3ProcessingTest.kt b/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3ProcessingTest.ktdeleted file mode 100644index c823c87f02..0000000000--- a/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3ProcessingTest.kt+++ /dev/null@@ -1,121 +0,0 @@-package com.vayunmathur.camera.util--import android.graphics.Bitmap-import android.graphics.Color-import android.graphics.Rect-import androidx.exifinterface.media.ExifInterface-import androidx.test.core.app.ApplicationProvider-import androidx.test.ext.junit.runners.AndroidJUnit4-import java.io.ByteArrayInputStream-import java.io.ByteArrayOutputStream-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertNotSame-import kotlin.test.assertSame-import kotlin.test.assertTrue-import org.junit.runner.RunWith--/** Pass 3: bitmap crop/rotate/color processing and EXIF stamping on real bitmaps. */-@RunWith(AndroidJUnit4::class)-class CameraPass3ProcessingTest {-- private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()- private fun vm() = CameraViewModel(app)-- private fun bitmap(w: Int, h: Int, color: Int = Color.RED): Bitmap =- Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }-- @Test fun cropFullFrameReturnsSameBitmap() {- val v = vm()- val src = bitmap(100, 80)- assertSame(src, v.cropToRect(src, Rect(0, 0, 100, 80)))- assertSame(src, v.cropToRect(src, Rect(0, 0, 0, 0)))- assertFalse(src.isRecycled)- }-- @Test fun cropPartialClampsAndRecyclesSource() {- val v = vm()- val src = bitmap(100, 80)- val cropped = v.cropToRect(src, Rect(10, 20, 60, 60))- assertEquals(50, cropped.width)- assertEquals(40, cropped.height)- assertTrue(src.isRecycled)- // Out-of-bounds rect is clamped to the frame.- val src2 = bitmap(50, 50)- val clamped = v.cropToRect(src2, Rect(-10, -10, 500, 500))- assertEquals(50, clamped.width)- assertEquals(50, clamped.height)- }-- @Test fun uprightCopyRotatesAndScales() {- val identity = uprightCopy(bitmap(40, 20), 0, 0)- assertEquals(40, identity.width)- val src = bitmap(40, 20)- val copy = uprightCopy(src, 0, 0)- assertNotSame(src, copy)- val rotated = uprightCopy(bitmap(40, 20), 90, 0)- assertEquals(20, rotated.width)- assertEquals(40, rotated.height)- val scaled = uprightCopy(bitmap(200, 100), 0, 50)- assertEquals(50, scaled.width)- assertEquals(25, scaled.height)- // maxSide larger than the frame never upscales.- val unscaled = uprightCopy(bitmap(30, 10), 0, 500)- assertEquals(30, unscaled.width)- }-- @Test fun colorAdjustmentsReturnNewBitmapAndRecycleSource() {- val src = bitmap(16, 16, Color.BLUE)- val out = applyColorAdjustments(src, warmth = 0.5f, shadows = 0.2f, mirror = false)- assertEquals(16, out.width)- assertEquals(16, out.height)- assertTrue(src.isRecycled)- val src2 = bitmap(16, 16, Color.GREEN)- val mirrored = applyColorAdjustments(src2, warmth = -0.5f, shadows = -0.2f, mirror = true)- assertEquals(16, mirrored.width)- assertTrue(src2.isRecycled)- val neutral = applyColorAdjustments(bitmap(8, 8), warmth = 0f, shadows = 0f, mirror = false)- assertEquals(8, neutral.width)- }-- private fun jpegBytes(): ByteArray {- val out = ByteArrayOutputStream()- bitmap(24, 16, Color.YELLOW).compress(Bitmap.CompressFormat.JPEG, 90, out)- return out.toByteArray()- }-- @Test fun stampStillBytesWritesOrientation() {- val v = vm()- val jpeg = jpegBytes()- assertTrue(jpeg.isNotEmpty())- val stamped = v.stampStillBytes(jpeg, rotationDegrees = 90)- val orientation = ExifInterface(ByteArrayInputStream(stamped))- .getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)- assertEquals(ExifInterface.ORIENTATION_ROTATE_90, orientation)- }-- @Test fun stampStillBytesMirroredInvertsRotation() {- val v = vm()- val stamped = v.stampStillBytes(jpegBytes(), rotationDegrees = 90, mirrored = true)- val orientation = ExifInterface(ByteArrayInputStream(stamped))- .getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)- assertEquals(ExifInterface.ORIENTATION_ROTATE_270, orientation)- val normal = v.stampStillBytes(jpegBytes(), rotationDegrees = 0)- assertEquals(- ExifInterface.ORIENTATION_NORMAL,- ExifInterface(ByteArrayInputStream(normal))- .getAttributeInt(ExifInterface.TAG_ORIENTATION, -1))- val rotated180 = v.stampStillBytes(jpegBytes(), rotationDegrees = 180)- assertEquals(- ExifInterface.ORIENTATION_ROTATE_180,- ExifInterface(ByteArrayInputStream(rotated180))- .getAttributeInt(ExifInterface.TAG_ORIENTATION, -1))- }-- @Test fun stampStillBytesOnGarbageReturnsInput() {- val v = vm()- val garbage = byteArrayOf(1, 2, 3, 4)- assertEquals(garbage.toList(), v.stampStillBytes(garbage, rotationDegrees = 90).toList())- }-}
camera/src/test/java/com/vayunmathur/camera/util/CameraPass3SaveAndThumbTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3SaveAndThumbTest.kt b/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3SaveAndThumbTest.ktdeleted file mode 100644index 5a09719566..0000000000--- a/camera/src/test/java/com/vayunmathur/camera/util/CameraPass3SaveAndThumbTest.kt+++ /dev/null@@ -1,88 +0,0 @@-package com.vayunmathur.camera.util--import android.graphics.Bitmap-import android.net.Uri-import androidx.test.core.app.ApplicationProvider-import androidx.test.ext.junit.runners.AndroidJUnit4-import java.io.File-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertNull-import kotlin.test.assertTrue-import kotlinx.coroutines.test.runTest-import org.junit.runner.RunWith--/** Pass 3: save-location routing, SAF document helpers, thumbnails, motion-photo guards. */-@RunWith(AndroidJUnit4::class)-class CameraPass3SaveAndThumbTest {-- private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()- private fun vm() = CameraViewModel(app)-- @Test fun saveTargetDefaultsAndTransitions() {- val v = vm()- v.loadSaveTarget()- assertEquals(SaveTarget.MediaStoreDefault, v.saveTarget.value)- val tree = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3APictures")- v.setSaveTreeUri(tree)- assertEquals(SaveTarget.SafTree(tree), v.saveTarget.value)- // The grant was never actually persisted in this environment, so a- // reload must fall back to the MediaStore default.- v.loadSaveTarget()- assertEquals(SaveTarget.MediaStoreDefault, v.saveTarget.value)- v.setSaveTreeUri(tree)- v.clearSaveTreeUri()- assertEquals(SaveTarget.MediaStoreDefault, v.saveTarget.value)- }-- @Test fun safPrimaryPathParsing() {- fun tree(docId: String): Uri = Uri.parse(- "content://com.android.externalstorage.documents/tree/${Uri.encode(docId)}")- val primary = SafDocuments.primaryPath(tree("primary:Pictures/TestCam"))- assertTrue(primary != null && primary.endsWith("/Pictures/TestCam"), "$primary")- assertTrue(SafDocuments.primaryPath(tree("primary:")) == null)- // Non-primary volumes have no absolute path.- assertNull(SafDocuments.primaryPath(tree("1234-5678:Pictures")))- // Path traversal is rejected, stray characters sanitized.- assertNull(SafDocuments.primaryPath(tree("primary:../etc")))- val cleaned = SafDocuments.primaryPath(tree("primary:Pictures/My Cam!"))- assertTrue(cleaned != null && cleaned.endsWith("/Pictures/My Cam_"), "$cleaned")- // Not a tree uri at all.- assertNull(SafDocuments.primaryPath(Uri.parse("content://media/external/images/1")))- }-- @Test fun safPermissionHelpersDegrade() {- val resolver = app.contentResolver- val tree = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3APictures")- assertFalse(SafDocuments.hasPersistedPermission(resolver, tree))- // No provider in the test environment: taking the grant must not throw.- SafDocuments.takePersistablePermission(resolver, tree)- assertNull(SafDocuments.displayName(resolver, tree))- // Document creation against a nonexistent provider yields null or a- // caught failure, never a crash.- runCatching { SafDocuments.createImageDoc(resolver, tree, "a.jpg") }- runCatching { SafDocuments.createVideoDoc(resolver, tree, "a.mp4") }- }-- @Test fun thumbnailLoadingDegrades() = runTest {- val v = vm()- assertNull(v.loadThumbnail(null))- val missing = Uri.fromFile(File(app.cacheDir, "no-thumb.jpg"))- assertNull(v.loadThumbnail(missing))- }-- @Test fun motionPhotoEncoderGuards() {- val out = File(app.cacheDir, "motion-out.mp4")- assertFalse(MotionPhotoEncoder.encode(emptyList(), out, 0))- val tiny = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)- assertFalse(MotionPhotoEncoder.encode(listOf(tiny), out, 0))- tiny.recycle()- // A plausible frame still cannot encode without a real codec here;- // the contract is a false result, not a crash.- val frame = Bitmap.createBitmap(64, 48, Bitmap.Config.ARGB_8888)- val result = runCatching { MotionPhotoEncoder.encode(listOf(frame), out, 90) }.getOrDefault(false)- assertFalse(result)- frame.recycle()- }-}
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.ktindex 09928ffe5a..43faf5205b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt@@ -18,18 +18,7 @@ class GoogleVoiceAuthException(message: String) : IOException(message) * Networking goes through the repo's [NetworkClient] (HttpURLConnection, no OkHttp); parsing * is delegated to [GoogleVoiceParser]. */-class GoogleVoiceClient(- private val session: GoogleVoiceSession,- /**- * Transport seam: performs one POST and returns the response. The default is the- * real [NetworkClient] stack; tests inject a fake that replays recorded- * protojson so the client can be exercised without touching the network.- */- private val transport: suspend (url: String, headers: Map<String, String>, body: String) -> SimpleResponse =- { url, headers, body ->- NetworkClient.performRequest(url = url, method = "POST", headers = headers, body = body)- },-) {+class GoogleVoiceClient(private val session: GoogleVoiceSession) { suspend fun getAccount(): GvAccount { val body = post("account/get", GoogleVoiceParser.buildAccountBody())@@ -117,7 +106,12 @@ class GoogleVoiceClient( val url = "$BASE$path?alt=protojson&key=$apiKey" val headers = GoogleVoiceAuth.headers(cookie, sapisid, authUser)- val response = transport(url, headers, jsonBody)+ val response = NetworkClient.performRequest(+ url = url,+ method = "POST",+ headers = headers,+ body = jsonBody,+ ) checkVoiceResponse(path, response) // TEMP diagnostic logging of raw protojson so the positional parser can be pinned to the // real wire shapes. Chunked because logcat truncates long lines.
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.ktindex bc5ba6e86e..847eead5d1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt@@ -282,10 +282,6 @@ interface RcsMlsGroupDao { @Query("SELECT * FROM rcs_mls_group WHERE conversationId = :conversationId LIMIT 1") suspend fun getByConversation(conversationId: String): RcsMlsGroup? - /** Rows of the 1:1 pseudo-threads (`e2e:<e164>`), where freshKeyPackage keeps key-package state. */- @Query("SELECT * FROM rcs_mls_group WHERE conversationId LIKE 'e2e:%'")- suspend fun getKeyPackageSnapshots(): List<RcsMlsGroup>- @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsert(group: RcsMlsGroup)
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.ktindex 369faaa18f..87adac91ca 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt@@ -364,18 +364,9 @@ object RcsE2E { ): ByteArray? = withContext(Dispatchers.IO) { if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null val db = RcsDatabase.getDatabase(context)- val dao = db.mlsGroupDao()- // The Welcome is encrypted to one of OUR key packages, whose private keys live in the- // storage freshKeyPackage keeps under the 1:1 pseudo-thread row (`e2e:<e164>`), not under- // [conversationId] (the sender's thread). Try this conversation's storage first, then each- // of those; OpenMLS only accepts the one holding the matching private key. A rejected- // candidate throws from JNI, so each attempt is caught on its own.- val candidates = listOf(dao.getByConversation(conversationId)?.storage ?: ByteArray(0)) +- dao.getKeyPackageSnapshots().map { it.storage }+ val storage = db.mlsGroupDao().getByConversation(conversationId)?.storage ?: ByteArray(0) runCatching {- val (storage, out) = candidates.firstNotNullOfOrNull { candidate ->- runCatching { RustMlsCrypto.joinGroup(candidate, welcome) }.getOrNull()?.let { candidate to it }- } ?: return@runCatching null+ val out = RustMlsCrypto.joinGroup(storage, welcome) ?: return@runCatching null val storageOut = out.getOrNull(0) ?: storage val groupId = out.getOrNull(1) ?: return@runCatching null db.mlsGroupDao().upsert(
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.ktindex 5f8b396860..13ea238aa5 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt@@ -13,7 +13,6 @@ import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E.ParsedPreKeyBun import com.vayunmathur.communicate.data.whatsapp.encodeNode import com.vayunmathur.communicate.data.whatsapp.mex.MexResult import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket-import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppTransport import java.security.SecureRandom import java.util.Collections import java.util.concurrent.ConcurrentHashMap@@ -85,10 +84,7 @@ object WhatsAppClient { // Use WebView-based WebSocket to bypass TLS fingerprinting // WhatsApp blocks non-browser TLS fingerprints (JA3). WebView uses Chromium's // network stack which is indistinguishable from Chrome browser.- internal var webSocket: WhatsAppTransport? = null-- /** Socket construction seam: production builds the real Noise socket; tests inject a fake. */- internal var transportFactory: (WhatsAppAuthData) -> WhatsAppTransport = ::WhatsAppSocket+ internal var webSocket: WhatsAppSocket? = null // Collector jobs for the current socket; cancelled on teardown so old (zombie) sockets // don't keep running keepalives or trigger reconnects, which causes self-conflicts. private var socketCollectorJobs: MutableList<Job> = mutableListOf()@@ -574,7 +570,7 @@ object WhatsAppClient { teardownSocket() // Use WebView-based WebSocket to bypass TLS fingerprinting- val ws = transportFactory(auth)+ val ws = WhatsAppSocket(auth) webSocket = ws socketCollectorJobs.add( scope.launch {
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientRetry.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientRetry.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientRetry.ktindex 316c0ce913..2200bd5b71 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientRetry.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientRetry.kt@@ -2,7 +2,7 @@ package com.vayunmathur.communicate.data.whatsapp import com.vayunmathur.library.log.Log import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E-import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppTransport+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket /** * Retry-receipt handling (split from WhatsAppClientSync.kt for file length).@@ -117,7 +117,7 @@ private suspend fun WhatsAppClient.rebuildRetrySession( private suspend fun WhatsAppClient.resendRetryMessage( auth: WhatsAppAuthData, crypto: WhatsAppE2E,- ws: WhatsAppTransport,+ ws: WhatsAppSocket, msgId: String, deviceJid: String, cached: SentDM,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSend.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSend.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSend.ktindex 71c9ab78a8..96cdb424b6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSend.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSend.kt@@ -14,7 +14,7 @@ import com.vayunmathur.communicate.data.whatsapp.senderKeyDistributionPlaintext import android.util.Base64 import com.vayunmathur.library.log.Log import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E-import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppTransport+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto import kotlinx.coroutines.Dispatchers@@ -113,7 +113,7 @@ suspend fun WhatsAppClient.sendCallOffer(conversationId: String, video: Boolean /** Encrypt a call key for the peer's (and our) devices and send the offer stanza. */ private suspend fun WhatsAppClient.sendCallOfferTo(- ws: WhatsAppTransport,+ ws: WhatsAppSocket, auth: WhatsAppAuthData, crypto: WhatsAppE2E, to: String,@@ -407,7 +407,7 @@ private fun mediaKeyFor(mediaType: String): String = when (mediaType) { /** Encrypt, upload, build, and send the media stanza. */ private suspend fun WhatsAppClient.sendMediaPayload(- ws: WhatsAppTransport,+ ws: com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket, to: String, id: String, bytes: ByteArray,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSendActions.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSendActions.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSendActions.ktindex 5e19099c0d..178afae3c7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSendActions.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClientSendActions.kt@@ -12,7 +12,7 @@ import com.vayunmathur.communicate.data.whatsapp.buildReactionProto import com.vayunmathur.communicate.data.whatsapp.buildReadReceipt import com.vayunmathur.communicate.data.whatsapp.buildRevokeProto import com.vayunmathur.communicate.data.whatsapp.encodeNode-import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppTransport+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket import com.vayunmathur.communicate.data.whatsapp.generateMessageId import com.vayunmathur.communicate.data.whatsapp.isRevokeFromMe import com.vayunmathur.library.log.Log@@ -50,7 +50,7 @@ suspend fun WhatsAppClient.markRead( /** Batch group read receipts by sender (Go HandleMatrixReadReceipt). */ private suspend fun WhatsAppClient.sendGroupReadReceipts(- ws: WhatsAppTransport,+ ws: com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket, to: String, filteredIds: List<String>, senderJids: Map<String, String>,@@ -467,7 +467,7 @@ suspend fun WhatsAppClient.setDisappearingTimer(conversationId: String, timerSec /** 1:1 disappearing timer via encrypted protocol message. */ private suspend fun WhatsAppClient.sendDisappearingTimerMessage(- ws: WhatsAppTransport,+ ws: WhatsAppSocket, chatJid: String, id: String, timerSeconds: Long,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppSocket.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppSocket.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppSocket.ktindex 6e0290b1f6..ffbddd04db 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppSocket.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppSocket.kt@@ -47,7 +47,7 @@ class WhatsAppSocket( private val authData: WhatsAppAuthData, private val host: String = DEFAULT_HOST, private val port: Int = DEFAULT_PORT,-) : WhatsAppTransport {+) { companion object { private const val TAG = "WhatsAppSocket" const val DEFAULT_HOST = "g.whatsapp.net"@@ -78,10 +78,10 @@ class WhatsAppSocket( @Volatile private var isHandshakeComplete = false private val _messages = MutableSharedFlow<ByteArray>(extraBufferCapacity = 256)- override val messages: SharedFlow<ByteArray> = _messages.asSharedFlow()+ val messages: SharedFlow<ByteArray> = _messages.asSharedFlow() private val _connectionState = MutableSharedFlow<ConnectionState>(extraBufferCapacity = 16)- override val connectionState: SharedFlow<ConnectionState> = _connectionState.asSharedFlow()+ val connectionState: SharedFlow<ConnectionState> = _connectionState.asSharedFlow() sealed interface ConnectionState { data object Connecting : ConnectionState@@ -101,7 +101,7 @@ class WhatsAppSocket( // ---------------------------------------------------------------------------- lifecycle - override fun connect() {+ fun connect() { scope.launch { _connectionState.emit(ConnectionState.Connecting) try {@@ -121,7 +121,7 @@ class WhatsAppSocket( } } - override fun disconnect() {+ fun disconnect() { scope.launch { closeInternal("client disconnect") } } @@ -338,7 +338,7 @@ class WhatsAppSocket( // or reorder frames (server rejects with <stream:error><bad-mac>). private val sendLock = Any() - override fun send(data: ByteArray): Boolean {+ fun send(data: ByteArray): Boolean { if (!isConnected || !isHandshakeComplete) return false val socket = noiseSocket ?: return false return try {
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppTransport.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppTransport.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppTransport.ktdeleted file mode 100644index 504253f66d..0000000000--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/transport/WhatsAppTransport.kt+++ /dev/null@@ -1,21 +0,0 @@-package com.vayunmathur.communicate.data.whatsapp.transport--import kotlinx.coroutines.flow.SharedFlow--/**- * The surface [com.vayunmathur.communicate.data.whatsapp.WhatsAppClient] uses of- * [WhatsAppSocket]: connect/disconnect/send plus the decrypted-frame and- * connection-state flows. Extracted so tests can drive the real client through a- * fake transport (no TCP, no Noise) while production keeps using [WhatsAppSocket]- * unchanged via the client's default `transportFactory`.- */-internal interface WhatsAppTransport {- fun connect()- fun send(data: ByteArray): Boolean- fun disconnect()-- /** Decrypted inbound frames (already Noise-decoded by the socket). */- val messages: SharedFlow<ByteArray>-- val connectionState: SharedFlow<WhatsAppSocket.ConnectionState>-}
communicate/src/main/rust-mls/src/lib.rs
diff --git a/communicate/src/main/rust-mls/src/lib.rs b/communicate/src/main/rust-mls/src/lib.rsindex 450dc34bd0..7415a91b28 100644--- a/communicate/src/main/rust-mls/src/lib.rs+++ b/communicate/src/main/rust-mls/src/lib.rs@@ -15,7 +15,7 @@ pub mod keys; pub mod message; pub mod store; -// Compiled for the host too (see ../rust/src/lib.rs): JVM tests load the host cdylib.+#[cfg(target_os = "android")] #[allow(unsafe_code)] mod jni_bridge;
communicate/src/main/rust/src/lib.rs
diff --git a/communicate/src/main/rust/src/lib.rs b/communicate/src/main/rust/src/lib.rsindex b9ae66bdc2..92de3d590f 100644--- a/communicate/src/main/rust/src/lib.rs+++ b/communicate/src/main/rust/src/lib.rs@@ -22,8 +22,7 @@ pub mod session; pub mod wire; pub mod signal; -// Compiled for the host too, so JVM unit tests can call the real crypto through-// `cargoBuildHost_communicate_signal` instead of hitting UnsatisfiedLinkError.+#[cfg(target_os = "android")] mod jni_bridge; #[cfg(test)]
communicate/src/test/java/com/vayunmathur/communicate/data/HostNativeCryptoTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/HostNativeCryptoTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/HostNativeCryptoTest.ktdeleted file mode 100644index b30db71cd5..0000000000--- a/communicate/src/test/java/com/vayunmathur/communicate/data/HostNativeCryptoTest.kt+++ /dev/null@@ -1,41 +0,0 @@-package com.vayunmathur.communicate.data--import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto-import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto-import androidx.test.ext.junit.runners.AndroidJUnit4-import org.junit.Test-import org.junit.runner.RunWith-import kotlin.test.assertContentEquals-import kotlin.test.assertEquals-import kotlin.test.assertNotNull-import kotlin.test.assertTrue--/**- * The host cdylibs export the JNI bridges, so JVM tests exercise the real Rust crypto.- * Robolectric: the loaders log through android.util.Log.- */-@RunWith(AndroidJUnit4::class)-class HostNativeCryptoTest {-- @Test- fun whatsAppX25519AgreementMatchesFromBothSides() {- assertTrue(RustWhatsAppCrypto.isAvailable)- val alice = assertNotNull(RustWhatsAppCrypto.generateKeyPair())- val bob = assertNotNull(RustWhatsAppCrypto.generateKeyPair())- assertEquals(64, alice.size)- val (alicePriv, alicePub) = alice.copyOfRange(0, 32) to alice.copyOfRange(32, 64)- val (bobPriv, bobPub) = bob.copyOfRange(0, 32) to bob.copyOfRange(32, 64)-- assertContentEquals(alicePub, RustWhatsAppCrypto.publicFromPrivate(alicePriv))- val shared = assertNotNull(RustWhatsAppCrypto.x25519Agreement(alicePriv, bobPub))- assertContentEquals(shared, RustWhatsAppCrypto.x25519Agreement(bobPriv, alicePub))- }-- @Test- fun mlsGeneratesAnIdentity() {- assertTrue(RustMlsCrypto.isAvailable)- val out = assertNotNull(RustMlsCrypto.generateIdentity("+15550100".encodeToByteArray()))- assertEquals(2, out.size)- assertTrue(out[1].isNotEmpty())- }-}
communicate/src/test/java/com/vayunmathur/communicate/data/whatsapp/transport/FakeWhatsAppTransport.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/whatsapp/transport/FakeWhatsAppTransport.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/whatsapp/transport/FakeWhatsAppTransport.ktdeleted file mode 100644index fb151d952c..0000000000--- a/communicate/src/test/java/com/vayunmathur/communicate/data/whatsapp/transport/FakeWhatsAppTransport.kt+++ /dev/null@@ -1,102 +0,0 @@-package com.vayunmathur.communicate.data.whatsapp.transport--import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol-import com.vayunmathur.communicate.data.whatsapp.decodeNode-import com.vayunmathur.communicate.data.whatsapp.encodeNode-import java.util.concurrent.CopyOnWriteArrayList-import kotlinx.coroutines.delay-import kotlinx.coroutines.flow.MutableSharedFlow-import kotlinx.coroutines.flow.SharedFlow-import kotlinx.coroutines.flow.asSharedFlow--/**- * Test double for [WhatsAppTransport]: no TCP, no Noise, no network.- *- * - Records every frame the client sends; [sentNodes] decodes them with- * [WhatsAppProtocol] so tests can assert on stanza shape.- * - [emitNode]/[emitFrame] inject inbound (already-decrypted) frames, and- * [emitConnectionState] drives the client's connect/reconnect logic.- * - When [iqResponder] is set, an outbound `<iq>` with an `id` is answered- * automatically: the responder's node is re-emitted inbound (through- * [messages], exactly as a server reply would arrive), so the client's- * pending-IQ correlation completes it.- */-class FakeWhatsAppTransport : WhatsAppTransport {-- private val _messages = MutableSharedFlow<ByteArray>(extraBufferCapacity = 256)- override val messages: SharedFlow<ByteArray> = _messages.asSharedFlow()-- private val _connectionState = MutableSharedFlow<WhatsAppSocket.ConnectionState>(extraBufferCapacity = 64)- override val connectionState: SharedFlow<WhatsAppSocket.ConnectionState> = _connectionState.asSharedFlow()-- /** Every raw frame passed to [send], in order. */- val sentFrames = CopyOnWriteArrayList<ByteArray>()-- @Volatile var connectCount = 0- private set- @Volatile var disconnectCount = 0- private set-- /** What [send] returns; set to false to simulate a dead socket. */- @Volatile var sendResult = true-- /** Builds the IQ result/error node for an outbound IQ, or null to leave it unanswered. */- @Volatile var iqResponder: ((WhatsAppProtocol.Node) -> WhatsAppProtocol.Node?)? = null-- override fun connect() {- connectCount++- _connectionState.tryEmit(WhatsAppSocket.ConnectionState.Connecting)- }-- override fun disconnect() {- disconnectCount++- _connectionState.tryEmit(WhatsAppSocket.ConnectionState.Disconnected("fake disconnect"))- }-- override fun send(data: ByteArray): Boolean {- sentFrames += data.copyOf()- if (sendResult) maybeAnswerIq(data)- return sendResult- }-- private fun maybeAnswerIq(data: ByteArray) {- val responder = iqResponder ?: return- val node = runCatching { WhatsAppProtocol.decodeNode(data) }.getOrNull() ?: return- if (node.tag != "iq") return- val id = node.attrs["id"] ?: return- val response = responder(node) ?: return- // Keep the request's id unless the responder set one explicitly.- val withId = if (response.attrs.containsKey("id")) response else response.copy(attrs = response.attrs + ("id" to id))- emitNode(withId)- }-- /** All sent frames decoded as protocol nodes (undecodable frames are skipped). */- fun sentNodes(): List<WhatsAppProtocol.Node> =- sentFrames.mapNotNull { runCatching { WhatsAppProtocol.decodeNode(it) }.getOrNull() }-- fun lastSentNode(tag: String): WhatsAppProtocol.Node? = sentNodes().lastOrNull { it.tag == tag }-- fun clearSent() = sentFrames.clear()-- fun emitFrame(data: ByteArray) {- _messages.tryEmit(data.copyOf())- }-- fun emitNode(node: WhatsAppProtocol.Node) {- emitFrame(WhatsAppProtocol.encodeNode(node))- }-- fun emitConnectionState(state: WhatsAppSocket.ConnectionState) {- _connectionState.tryEmit(state)- }-- /** Suspends until at least [count] nodes with [tag] have been sent. */- suspend fun awaitSent(tag: String, count: Int = 1, timeoutMs: Long = 10_000) {- val deadline = System.currentTimeMillis() + timeoutMs- while (System.currentTimeMillis() < deadline) {- if (sentNodes().count { it.tag == tag } >= count) return- delay(10)- }- throw AssertionError("timed out waiting for $count <$tag> sent; sent so far: ${sentNodes().map { it.tag }}")- }-}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceClientVoicePass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceClientVoicePass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceClientVoicePass3Test.ktdeleted file mode 100644index b1b03fccca..0000000000--- a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceClientVoicePass3Test.kt+++ /dev/null@@ -1,139 +0,0 @@-package com.vayunmathur.communicate.googlevoice--import androidx.test.core.app.ApplicationProvider-import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceAuthException-import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient-import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser-import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession-import com.vayunmathur.communicate.data.googlevoice.GvFolder-import com.vayunmathur.library.network.SimpleResponse-import java.io.IOException-import kotlinx.coroutines.runBlocking-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFailsWith-import kotlin.test.assertTrue-import org.junit.runner.RunWith-import org.robolectric.RobolectricTestRunner--/** Voice pass-3: GoogleVoiceClient over a fake transport replaying recorded protojson. */-@RunWith(RobolectricTestRunner::class)-class GoogleVoiceClientVoicePass3Test {-- private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()-- private val threadBody = "[[[\"t.+14152124034\",1,[[\"h1\",1786409649630,\"+12133945548\"," +- "[\"+14152124034\",\"+14152124034\",null,null,null,null,0],10,1,null,null,null," +- "\"Hello there\",null,null,5,1,null,\"+14152124034\",0]],null,[[\"+14152124034\"]]]]]"-- private class FakeTransport(var status: Int = 200, var body: String = "") {- val requests = mutableListOf<Triple<String, Map<String, String>, String>>()- suspend fun post(url: String, headers: Map<String, String>, requestBody: String): SimpleResponse {- requests += Triple(url, headers, requestBody)- return SimpleResponse(status, "fake", body, emptyMap(), url)- }- }-- private suspend fun signedInSession(): GoogleVoiceSession {- val session = GoogleVoiceSession.get(ctx)- session.save(- cookieHeader = "SAPISID=sapisid-value; OTHER=x",- apiKey = "test-api-key",- authUser = "0",- )- return session- }-- @Test- fun getAccountParsesAndStoresPhoneNumber() = runBlocking {- val transport = FakeTransport(body = "[\"+15550001111\",null,[\"settings\"]]")- val client = GoogleVoiceClient(signedInSession()) { u, h, b -> transport.post(u, h, b) }- val account = client.getAccount()- assertEquals("+15550001111", account.phoneNumber)- assertEquals("+15550001111", GoogleVoiceSession.get(ctx).phoneNumber())- val (url, headers, _) = transport.requests.single()- assertTrue(url.contains("account/get"), url)- assertTrue(url.contains("key=test-api-key"), url)- assertTrue(headers.containsKey("Authorization"))- assertEquals("SAPISID=sapisid-value; OTHER=x", headers["Cookie"])- Unit- }-- @Test- fun listAndSearchThreadsParseRecordedBody() = runBlocking {- val transport = FakeTransport(body = threadBody)- val client = GoogleVoiceClient(signedInSession()) { u, h, b -> transport.post(u, h, b) }- val threads = client.listThreads(GvFolder.Inbox)- assertEquals(1, threads.size)- assertEquals("+14152124034", threads.first().phoneNumber)- val searched = client.search("hello")- assertEquals(1, searched.size)- assertTrue(transport.requests[0].first.contains("api2thread/list"))- assertTrue(transport.requests[1].first.contains("api2thread/search"))- assertTrue(transport.requests[1].third.contains("hello"))- Unit- }-- @Test- fun getThreadFindsMessagesAndFallsBackAcrossFolders() = runBlocking {- val transport = FakeTransport(body = threadBody)- val client = GoogleVoiceClient(signedInSession()) { u, h, b -> transport.post(u, h, b) }- val messages = client.getThread("t.+14152124034")- assertEquals(1, messages.size)- assertEquals("Hello there", messages.first().text)- // Unknown thread: Inbox then All are both consulted, result stays empty- val none = client.getThread("t.missing")- assertTrue(none.isEmpty())- assertTrue(transport.requests.size >= 3)- Unit- }-- @Test- fun listCallsAndVoicemailsHitListEndpoint() = runBlocking {- val transport = FakeTransport(body = threadBody)- val client = GoogleVoiceClient(signedInSession()) { u, h, b -> transport.post(u, h, b) }- client.listCalls()- client.listVoicemails()- assertEquals(2, transport.requests.size)- assertTrue(transport.requests.all { it.first.contains("api2thread/list") })- Unit- }-- @Test- fun sendsAndUpdatesPostExpectedBodies() = runBlocking {- val transport = FakeTransport(body = "[]")- val client = GoogleVoiceClient(signedInSession()) { u, h, b -> transport.post(u, h, b) }- client.sendSms("+1555", "hi there")- client.sendPreparedSms("[prepared]")- client.updateThreadAttributes("t.abc", GoogleVoiceParser.ThreadAction.MarkRead)- client.markVoicemailRead("t.vm")- client.markAllRead()- client.getSipRegisterInfo()- val paths = transport.requests.map { it.first }- assertTrue(paths[0].contains("api2thread/sendsms"))- assertEquals("[prepared]", transport.requests[1].third)- assertTrue(paths[2].contains("thread/batchupdateattributes"))- assertTrue(paths[4].contains("thread/markallread"))- assertEquals("[1]", transport.requests[4].third)- assertTrue(paths[5].contains("sipregisterinfo/get"))- Unit- }-- @Test- fun authAndHttpErrorsMapToExceptions() = runBlocking {- val session = signedInSession()- val unauthorized = GoogleVoiceClient(session) { _, _, _ ->- SimpleResponse(401, "no", "", emptyMap(), "x")- }- assertFailsWith<GoogleVoiceAuthException> { unauthorized.getAccount() }- val forbidden = GoogleVoiceClient(session) { _, _, _ ->- SimpleResponse(403, "no", "", emptyMap(), "x")- }- assertFailsWith<GoogleVoiceAuthException> { forbidden.listThreads() }- val serverError = GoogleVoiceClient(session) { _, _, _ ->- SimpleResponse(500, "err", "boom", emptyMap(), "x")- }- assertFailsWith<IOException> { serverError.getAccount() }- Unit- }-}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.ktindex dd6227cf8b..c6063f5f2a 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.kt@@ -40,28 +40,13 @@ class RcsSlice3Pass2E2ETest { private val context: Context get() = ApplicationProvider.getApplicationContext() private lateinit var testDb: RcsDatabase- /** The peer's own device database: MLS state is per device, keyed by group id. */- private lateinit var peerDb: RcsDatabase - private fun newDb(): RcsDatabase =- androidx.room3.Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+ @BeforeTest+ fun setUp() {+ testDb = androidx.room3.Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java) .setDriver(androidx.sqlite.driver.bundled.BundledSQLiteDriver()) .allowMainThreadQueries() .build()-- private inline fun <T> onDevice(db: RcsDatabase, block: () -> T): T {- RcsDatabase.overrideForTest = db- try {- return block()- } finally {- RcsDatabase.overrideForTest = testDb- }- }-- @BeforeTest- fun setUp() {- testDb = newDb()- peerDb = newDb() RcsDatabase.overrideForTest = testDb RcsPeerKeys.clear() }@@ -70,7 +55,6 @@ class RcsSlice3Pass2E2ETest { fun tearDown() { RcsDatabase.overrideForTest = null testDb.close()- peerDb.close() RcsPeerKeys.clear() } @@ -217,31 +201,28 @@ class RcsSlice3Pass2E2ETest { assertNotNull(row) assertEquals(identity.toList(), row.identity.toList()) - // Key packages for both sides, each on its own device.+ // Key packages for both sides. val myKp = RcsE2E.freshKeyPackage(context, me) assertNotNull(myKp)- val peerKp = onDevice(peerDb) {- assertNotNull(RcsE2E.identityFor(context, peer))- RcsE2E.freshKeyPackage(context, peer)- }+ val peerIdentity = RcsE2E.identityFor(context, peer)+ assertNotNull(peerIdentity)+ val peerKp = RcsE2E.freshKeyPackage(context, peer) assertNotNull(peerKp) - // Create a group adding the peer; the peer joins from the Welcome on its device. The- // Welcome is sealed to the peer's key package, whose private keys sit in the peer's- // 1:1 pseudo-thread storage, not in the conversation it arrives on.+ // Create a group adding the peer, then join from the Welcome. val created = RcsE2E.createEncryptedGroup(context, me, "conv-mls-1", listOf(peerKp)) assertNotNull(created) val (commit, welcome) = created assertTrue(commit.isNotEmpty() && welcome.isNotEmpty())- val groupId = onDevice(peerDb) { RcsE2E.joinEncryptedGroup(context, me, welcome) }+ val groupId = RcsE2E.joinEncryptedGroup(context, "conv-mls-2", welcome) assertNotNull(groupId) assertEquals(groupId.toList(), RcsE2E.groupIdFor(context, "conv-mls-1")?.toList())- assertEquals(groupId.toList(), onDevice(peerDb) { RcsE2E.groupIdFor(context, me) }?.toList())+ assertEquals(groupId.toList(), RcsE2E.groupIdFor(context, "conv-mls-2")?.toList()) // Encrypt on one side, decrypt on the joined side. val payload = RcsE2E.encryptTo(context, me, "conv-mls-1", "secret hello".toByteArray(Charsets.UTF_8)) assertNotNull(payload)- val decrypted = onDevice(peerDb) { RcsE2E.decryptFor(context, me, payload) }+ val decrypted = RcsE2E.decryptFor(context, "conv-mls-2", payload) assertNotNull(decrypted) assertEquals("secret hello", decrypted.first.toString(Charsets.UTF_8)) assertTrue(decrypted.second)
communicate/src/test/java/com/vayunmathur/communicate/telephony/SmsDeliverVoicePass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/SmsDeliverVoicePass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SmsDeliverVoicePass3Test.ktdeleted file mode 100644index bf5ec3df28..0000000000--- a/communicate/src/test/java/com/vayunmathur/communicate/telephony/SmsDeliverVoicePass3Test.kt+++ /dev/null@@ -1,61 +0,0 @@-package com.vayunmathur.communicate.telephony--import android.app.NotificationManager-import android.content.Context-import android.content.Intent-import android.provider.Telephony-import androidx.test.core.app.ApplicationProvider-import kotlin.test.Test-import kotlin.test.assertTrue-import org.junit.runner.RunWith-import org.robolectric.RobolectricTestRunner-import org.robolectric.Shadows.shadowOf--/** Voice pass-3: full SMS_DELIVER path with a real GSM PDU under Robolectric. */-@RunWith(RobolectricTestRunner::class)-class SmsDeliverVoicePass3Test {-- private val context get() = ApplicationProvider.getApplicationContext<Context>()-- private fun hexToBytes(hex: String): ByteArray =- ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }-- // GSM 03.40 example SMS-DELIVER PDU ("hellohello" from +46708251355)- private val pduHex = "07916407058099F9040B916407281553F80000993092516195800AE8329BFD4697D9EC37"-- @Test- fun deliverWithValidPduStoresAndNotifies() {- val intent = Intent(Telephony.Sms.Intents.SMS_DELIVER_ACTION).apply {- putExtra("pdus", arrayOf(hexToBytes(pduHex)))- putExtra("format", "3gpp")- putExtra("subscription", 1)- }- val receiver = SmsDeliverReceiver()- receiver.onReceive(context, intent)-- // Storage runs on the receiver's background thread; poll for the notification.- val nm = context.getSystemService(NotificationManager::class.java)- val deadline = System.currentTimeMillis() + 10_000- var notified = false- while (System.currentTimeMillis() < deadline) {- if (shadowOf(nm).allNotifications.isNotEmpty()) {- notified = true- break- }- Thread.sleep(50)- }- assertTrue(notified, "inbound SMS should post a conversation notification")- }-- @Test- fun deliverWithMultipartPduConcatenates() {- val intent = Intent(Telephony.Sms.Intents.SMS_DELIVER_ACTION).apply {- putExtra("pdus", arrayOf(hexToBytes(pduHex), hexToBytes(pduHex)))- putExtra("format", "3gpp")- }- SmsDeliverReceiver().onReceive(context, intent)- // No assertion on the provider (Robolectric has none); reaching here without- // throwing on the caller thread is the contract, storage is best-effort async.- Thread.sleep(300)- }-}
communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomConnectionsVoicePass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomConnectionsVoicePass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomConnectionsVoicePass3Test.ktdeleted file mode 100644index 8e52bedbe5..0000000000--- a/communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomConnectionsVoicePass3Test.kt+++ /dev/null@@ -1,151 +0,0 @@-package com.vayunmathur.communicate.telephony--import android.content.ComponentName-import android.net.Uri-import android.os.Bundle-import android.telecom.Connection-import android.telecom.ConnectionRequest-import android.telecom.PhoneAccountHandle-import android.telecom.TelecomManager-import androidx.test.core.app.ApplicationProvider-import com.vayunmathur.communicate.data.CommunicateLine-import com.vayunmathur.communicate.data.call.CallCapabilities-import com.vayunmathur.communicate.data.call.InAppCallController-import com.vayunmathur.communicate.data.call.InAppCallPhase-import com.vayunmathur.communicate.data.call.InAppCallRegistry-import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager-import kotlin.test.BeforeTest-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue-import org.junit.runner.RunWith-import org.robolectric.Robolectric-import org.robolectric.RobolectricTestRunner--/** Voice pass-3: Telecom Connection/ConnectionService bridges for GV and in-app calls. */-@RunWith(RobolectricTestRunner::class)-class TelecomConnectionsVoicePass3Test {-- private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()- private val actions = mutableListOf<String>()- private val controller = object : InAppCallController {- override fun answer() { actions += "answer" }- override fun reject() { actions += "reject" }- override fun hangup() { actions += "hangup" }- override fun setMuted(muted: Boolean) { actions += "muted=$muted" }- override fun setSpeaker(on: Boolean) { actions += "speaker=$on" }- }-- @BeforeTest- fun setUp() {- actions.clear()- InAppCallRegistry.onEnded("reset")- InAppCallRegistry.clearEnded()- InAppCallRegistry.videoController = null- InAppCallRegistry.dtmfController = null- InAppCallRegistry.holdController = null- InAppCallRegistry.connection = null- GoogleVoiceCallManager.connection = null- }-- private fun handle(serviceClass: Class<*>) =- PhoneAccountHandle(ComponentName(ctx, serviceClass), "acct")-- @Test- fun googleVoiceConnectionLifecycle() {- val connection = GoogleVoiceConnection()- assertTrue(connection.audioModeIsVoip)- assertTrue(connection.connectionCapabilities and Connection.CAPABILITY_MUTE != 0)- assertTrue(connection.connectionCapabilities and Connection.CAPABILITY_SUPPORT_HOLD != 0)- connection.onCallActive()- assertEquals(Connection.STATE_ACTIVE, connection.state)- // DTMF and answer without an initialized manager are no-ops- connection.onPlayDtmfTone('5')- connection.onAnswer()-- val rejected = GoogleVoiceConnection()- rejected.onReject()- assertEquals(Connection.STATE_DISCONNECTED, rejected.state)-- val disconnected = GoogleVoiceConnection()- disconnected.onDisconnect()- assertEquals(Connection.STATE_DISCONNECTED, disconnected.state)-- val aborted = GoogleVoiceConnection()- aborted.onAbort()- assertEquals(Connection.STATE_DISCONNECTED, aborted.state)-- val ended = GoogleVoiceConnection()- ended.onCallEnded()- assertEquals(Connection.STATE_DISCONNECTED, ended.state)- }-- @Test- fun inAppCallConnectionBridgesToRegistry() {- InAppCallRegistry.bind(CommunicateLine.Signal, controller, CallCapabilities.AudioOnly)- InAppCallRegistry.onCallStarting(CommunicateLine.Signal, "peer-1", "Pat Lee", false, incoming = false)- val connection = InAppCallConnection()- connection.onMuteStateChanged(true)- assertEquals(listOf("muted=true"), actions.toList())- assertTrue(InAppCallRegistry.state.value.muted)- // Same mute state again: no toggle back- connection.onMuteStateChanged(true)- assertEquals(listOf("muted=true"), actions.toList())-- connection.onCallActive()- assertEquals(Connection.STATE_ACTIVE, connection.state)-- val disconnecting = InAppCallConnection()- disconnecting.onDisconnect()- assertEquals("hangup", actions.last())- assertEquals(Connection.STATE_DISCONNECTED, disconnecting.state)-- val ending = InAppCallConnection()- ending.onCallEnded()- assertEquals(Connection.STATE_DISCONNECTED, ending.state)- }-- @Test- fun inAppCallConnectionServiceCreatesMirrors() {- InAppCallRegistry.bind(CommunicateLine.Signal, controller, CallCapabilities.AudioOnly)- InAppCallRegistry.onCallStarting(CommunicateLine.Signal, "peer-1", "Pat Lee", false, incoming = false)- val service = Robolectric.setupService(InAppCallConnectionService::class.java)- val outgoing = service.onCreateOutgoingConnection(- handle(InAppCallConnectionService::class.java),- ConnectionRequest(handle(InAppCallConnectionService::class.java), Uri.fromParts("sip", "peer-1", null), Bundle()),- )- assertEquals(Connection.STATE_DIALING, outgoing.state)- assertTrue(outgoing.connectionProperties and Connection.PROPERTY_SELF_MANAGED != 0)- assertTrue(InAppCallRegistry.connection === outgoing)-- val incoming = service.onCreateIncomingConnection(handle(InAppCallConnectionService::class.java), null)- assertEquals(Connection.STATE_RINGING, incoming.state)- assertTrue(InAppCallRegistry.connection === incoming)-- // Failed mirrors must not end the underlying call- service.onCreateOutgoingConnectionFailed(handle(InAppCallConnectionService::class.java), null)- service.onCreateIncomingConnectionFailed(handle(InAppCallConnectionService::class.java), null)- assertTrue(actions.isEmpty())- service.onDestroy()- }-- @Test- fun telecomAccountHandlesAndRegistration() {- val gvHandle = GoogleVoiceTelecom.handle(ctx)- assertEquals("google_voice_line", gvHandle.id)- GoogleVoiceTelecom.registerPhoneAccount(ctx, "+1 555 0001")- GoogleVoiceTelecom.placeOutgoing(ctx, "+15559999")- GoogleVoiceTelecom.addIncoming(ctx, "+15551234")- GoogleVoiceTelecom.unregisterPhoneAccount(ctx)-- val inAppHandle = InAppCallTelecom.handle(ctx)- assertEquals("communicate_inapp_calls", inAppHandle.id)- assertTrue(gvHandle != inAppHandle)- InAppCallTelecom.registerPhoneAccount(ctx, "Calls")- InAppCallTelecom.addOutgoing(ctx, "peer-1")- InAppCallTelecom.addIncoming(ctx, "peer-1")- InAppCallTelecom.unregisterPhoneAccount(ctx)- assertEquals(InAppCallConnectionService::class.java.name, inAppHandle.componentName.className)- assertEquals(GoogleVoiceConnectionService::class.java.name, gvHandle.componentName.className)- }-}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WaTransportPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WaTransportPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WaTransportPass3Test.ktdeleted file mode 100644index 5dc3df6aa3..0000000000--- a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WaTransportPass3Test.kt+++ /dev/null@@ -1,299 +0,0 @@-package com.vayunmathur.communicate.whatsapp--import android.app.Application-import android.content.Context-import android.util.Base64-import androidx.room3.Room-import androidx.test.core.app.ApplicationProvider-import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData-import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient-import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase-import com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent-import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol-import com.vayunmathur.communicate.data.whatsapp.decodeNode-import com.vayunmathur.communicate.data.whatsapp.encodeNode-import com.vayunmathur.communicate.data.whatsapp.fetchAndEmitGroupInfo-import com.vayunmathur.communicate.data.whatsapp.transport.FakeWhatsAppTransport-import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.launch-import kotlinx.coroutines.runBlocking-import kotlinx.coroutines.withTimeoutOrNull-import org.junit.runner.RunWith-import org.robolectric.RobolectricTestRunner-import kotlin.test.BeforeTest-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertNotNull-import kotlin.test.assertNull-import kotlin.test.assertTrue--/**- * Pass 3 (whatsapp-transport): drives the real [WhatsAppClient] singleton through- * [FakeWhatsAppTransport] - no socket, no network. The DB is an in-memory Room- * database (the production SQLCipher build needs AndroidKeyStore, unavailable- * under Robolectric), and auth is a fabricated identity with real X25519 keys.- */-@OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)-@RunWith(RobolectricTestRunner::class)-class WaTransportPass3Test {-- private val context: Context get() = ApplicationProvider.getApplicationContext()- private lateinit var fake: FakeWhatsAppTransport-- private fun b64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)-- private fun fabricatedAuth(): WhatsAppAuthData {- val noise = WhatsAppProtocol.generateX25519KeyPair()- val identity = WhatsAppProtocol.generateX25519KeyPair()- val signed = WhatsAppProtocol.generateX25519KeyPair()- return WhatsAppAuthData(- phoneNumber = "15551234567",- pushName = "Test",- wid = "[email protected]",- noisePrivateKey = b64(noise.first),- noisePublicKey = b64(noise.second),- identityPrivateKey = b64(identity.first),- identityPublicKey = b64(identity.second),- registrationId = 1234,- signedPreKeyId = 1,- signedPreKeyPublic = b64(signed.second),- signedPreKeyPrivate = b64(signed.first),- signedPreKeySignature = b64(ByteArray(64) { (it * 7).toByte() }),- )- }-- @BeforeTest fun setUp() {- fake = FakeWhatsAppTransport()- val client = WhatsAppClient- client.appContext = context.applicationContext as Application- client.db = Room.inMemoryDatabaseBuilder(context, WhatsAppDatabase::class.java)- .allowMainThreadQueries().build()- client.authData = fabricatedAuth()- client.transportFactory = { fake }- client.webSocket = null- client.suppressReconnect = false- client.pendingIqs.clear()- client.knownGroups.clear()- client.stateMutable.value = WhatsAppClient.State.Idle- client.initialized.store(true)- }-- private fun pollUntil(timeoutMs: Long = 15_000, cond: () -> Boolean) {- val deadline = System.currentTimeMillis() + timeoutMs- while (System.currentTimeMillis() < deadline && !cond()) Thread.sleep(25)- assertTrue(cond(), "condition not met within ${timeoutMs}ms")- }-- /** Generic IQ result responder: echoes a result IQ for any request. */- private fun resultResponder(): (WhatsAppProtocol.Node) -> WhatsAppProtocol.Node =- { req: WhatsAppProtocol.Node ->- WhatsAppProtocol.Node(- tag = "iq",- attrs = mapOf("type" to "result", "from" to "s.whatsapp.net", "id" to (req.attrs["id"] ?: "")),- )- }-- @Test fun fakeRecordsDecodesAndAutoAnswersIq() = runBlocking {- val transport = FakeWhatsAppTransport()- var answered: WhatsAppProtocol.Node? = null- val collectJob = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined).launch {- answered = withTimeoutOrNull(3000) {- WhatsAppProtocol.decodeNode(transport.messages.first())- }- }- transport.iqResponder = { req ->- WhatsAppProtocol.Node("iq", mapOf("type" to "result"), content = listOf(WhatsAppProtocol.Node("echo", data = req.attrs["id"]?.toByteArray())))- }- transport.connect()- assertEquals(1, transport.connectCount)- val iq = WhatsAppProtocol.Node("iq", mapOf("id" to "iq-1", "type" to "get", "xmlns" to "w:p"))- assertTrue(transport.send(WhatsAppProtocol.encodeNode(iq)))- collectJob.join()- assertNotNull(answered)- assertEquals("iq-1", answered!!.attrs["id"])- assertEquals(listOf("iq"), transport.sentNodes().map { it.tag })- transport.disconnect()- assertEquals(1, transport.disconnectCount)- assertTrue(!transport.sendResult || true)- transport.sendResult = false- assertTrue(!transport.send(WhatsAppProtocol.encodeNode(iq)))- Unit- }-- @Test fun connectThenSuccessAuthenticatesAndSendsPresence() {- fake.iqResponder = resultResponder()- WhatsAppClient.forceResync()- pollUntil { fake.connectCount >= 1 }- fake.emitConnectionState(WhatsAppSocket.ConnectionState.Connected)- // server accepts the login- fake.emitNode(- WhatsAppProtocol.Node(- tag = "success",- attrs = mapOf("lid" to "123456789@lid", "t" to "1700000000"),- ),- )- pollUntil { WhatsAppClient.state.value is WhatsAppClient.State.Connected }- assertTrue(WhatsAppClient.isConnected())- // post-success: passive-active IQ and unavailable presence go out- pollUntil { fake.sentNodes().any { it.tag == "presence" && it.attrs["type"] == "unavailable" } }- pollUntil { fake.sentNodes().any { it.tag == "iq" && it.attrs["xmlns"] == "passive" } }- assertEquals("123456789@lid", WhatsAppClient.authData?.lid)- Unit- }-- @Test fun sendIqAndWaitResolvesById() {- fake.iqResponder = { req ->- WhatsAppProtocol.Node(- tag = "iq",- attrs = mapOf("type" to "result", "id" to (req.attrs["id"] ?: "")),- content = listOf(WhatsAppProtocol.Node("value", data = "pong".toByteArray())),- )- }- connectClient()- val resp = runBlocking {- WhatsAppClient.sendIqAndWait(- WhatsAppProtocol.Node("iq", mapOf("id" to "ping-1", "type" to "get", "xmlns" to "w:p")),- timeoutMs = 10_000,- )- }- assertNotNull(resp)- assertEquals("result", resp!!.attrs["type"])- assertEquals("pong", resp.getChildByTag("value")?.data?.decodeToString())- assertTrue(WhatsAppClient.pendingIqs.isEmpty())- Unit- }-- @Test fun sendIqAndWaitTimesOutAndCleansUp() {- fake.iqResponder = null- connectClient()- val resp = runBlocking {- WhatsAppClient.sendIqAndWait(- WhatsAppProtocol.Node("iq", mapOf("id" to "ping-timeout", "type" to "get")),- timeoutMs = 200,- )- }- assertNull(resp)- assertTrue(WhatsAppClient.pendingIqs.isEmpty())- Unit- }-- @Test fun sendIqAndWaitWithoutSocketReturnsNull() {- WhatsAppClient.webSocket = null- val resp = runBlocking {- WhatsAppClient.sendIqAndWait(- WhatsAppProtocol.Node("iq", mapOf("id" to "ping-none", "type" to "get")),- timeoutMs = 1_000,- )- }- assertNull(resp)- Unit- }-- @Test fun sendIqAndWaitWithFailedSendReturnsNull() {- connectClient()- fake.sendResult = false- val resp = runBlocking {- WhatsAppClient.sendIqAndWait(- WhatsAppProtocol.Node("iq", mapOf("id" to "ping-fail", "type" to "get")),- timeoutMs = 1_000,- )- }- assertNull(resp)- assertTrue(WhatsAppClient.pendingIqs.isEmpty())- Unit- }-- @Test fun inboundMessageAndReceiptAreAcked() {- connectClient()- fake.clearSent()- fake.emitNode(- WhatsAppProtocol.Node(- tag = "message",- attrs = mapOf("id" to "msg-1", "from" to "[email protected]", "t" to "1700000000"),- ),- )- runBlocking { fake.awaitSent("ack", 1) }- val ack = fake.lastSentNode("ack")!!- assertEquals("message", ack.attrs["class"])- assertEquals("msg-1", ack.attrs["id"])- fake.clearSent()- fake.emitNode(- WhatsAppProtocol.Node(- tag = "receipt",- attrs = mapOf("id" to "msg-1", "from" to "[email protected]", "type" to "delivered"),- ),- )- runBlocking { fake.awaitSent("ack", 1) }- assertEquals("receipt", fake.lastSentNode("ack")!!.attrs["class"])- Unit- }-- @Test fun groupInfoFetchEmitsConversationUpdate() {- fake.iqResponder = { req ->- WhatsAppProtocol.Node(- tag = "iq",- attrs = mapOf("type" to "result", "id" to (req.attrs["id"] ?: "")),- content = listOf(- WhatsAppProtocol.Node(- tag = "group",- attrs = mapOf("id" to "[email protected]", "subject" to "Test Group"),- content = listOf(- WhatsAppProtocol.Node("participant", mapOf("jid" to "[email protected]")),- WhatsAppProtocol.Node("participant", mapOf("jid" to "[email protected]")),- ),- ),- ),- )- }- connectClient()- val events = mutableListOf<WhatsAppEvent>()- val job = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined).launch {- WhatsAppClient.events.collect { events += it }- }- runBlocking { WhatsAppClient.fetchAndEmitGroupInfo("[email protected]") }- pollUntil { events.any { it is WhatsAppEvent.ConversationUpdate && it.isGroup } }- val update = events.filterIsInstance<WhatsAppEvent.ConversationUpdate>().first { it.isGroup }- assertEquals("Test Group", update.peerName)- assertEquals(2, update.participantCount)- job.cancel()- // non-group jids and already-known groups are no-ops- runBlocking { WhatsAppClient.fetchAndEmitGroupInfo("[email protected]") }- runBlocking { WhatsAppClient.fetchAndEmitGroupInfo("[email protected]") }- Unit- }-- @Test fun disconnectSchedulesReconnect() {- fake.iqResponder = resultResponder()- connectClient()- val before = fake.connectCount- fake.emitConnectionState(WhatsAppSocket.ConnectionState.Disconnected("socket closed"))- // reconnect scheduling flips to Connecting immediately, then reconnects after backoff- pollUntil { WhatsAppClient.state.value is WhatsAppClient.State.Connecting || fake.connectCount > before }- pollUntil(20_000) { fake.connectCount > before }- Unit- }-- @Test fun streamError401LogsOut() {- connectClient()- fake.emitNode(- WhatsAppProtocol.Node(- tag = "failure",- attrs = mapOf("reason" to "401"),- ),- )- pollUntil { WhatsAppClient.state.value is WhatsAppClient.State.Disconnected }- assertNull(WhatsAppClient.authData)- // restore a session for other tests (they re-setup anyway)- Unit- }-- /** Runs the client's private connect() via forceResync and waits for the collectors. */- private fun connectClient() {- WhatsAppClient.authData = fabricatedAuth()- WhatsAppClient.forceResync()- pollUntil { fake.connectCount >= 1 && WhatsAppClient.webSocket === fake }- fake.emitConnectionState(WhatsAppSocket.ConnectionState.Connected)- Thread.sleep(200)- }-}
education/src/test/java/com/vayunmathur/education/EducationFixtures.kt
diff --git a/education/src/test/java/com/vayunmathur/education/EducationFixtures.kt b/education/src/test/java/com/vayunmathur/education/EducationFixtures.ktdeleted file mode 100644index 7af4f4451f..0000000000--- a/education/src/test/java/com/vayunmathur/education/EducationFixtures.kt+++ /dev/null@@ -1,118 +0,0 @@-package com.vayunmathur.education--import android.content.Context-import androidx.room3.Room-import com.vayunmathur.education.content.Choice-import com.vayunmathur.education.content.ContentPack-import com.vayunmathur.education.content.ContentRepository-import com.vayunmathur.education.content.Course-import com.vayunmathur.education.content.CourseUnit-import com.vayunmathur.education.content.Exercise-import com.vayunmathur.education.content.Lesson-import com.vayunmathur.education.content.MatchingQuestion-import com.vayunmathur.education.content.MultipleChoiceQuestion-import com.vayunmathur.education.content.MultipleSelectQuestion-import com.vayunmathur.education.content.NumericQuestion-import com.vayunmathur.education.content.OrderingQuestion-import com.vayunmathur.education.content.Prompt-import com.vayunmathur.education.content.ShortTextQuestion-import com.vayunmathur.education.content.Skill-import com.vayunmathur.education.content.Subject-import com.vayunmathur.education.content.TracingQuestion-import com.vayunmathur.education.content.VideoRef-import com.vayunmathur.education.data.EducationDatabase-import com.vayunmathur.education.data.EducationRepository-import com.vayunmathur.library.util.databases--/** Shared fixtures: one synthetic pack covering every band, subject and question type. */-object EducationFixtures {- val mcq = MultipleChoiceQuestion(- id = "q-mc", skillId = "count",- prompt = Prompt("How many apples?", audioRef = "q-mc.mp3"),- choices = listOf(Choice("1"), Choice("3"), Choice("7")),- correctIndex = 1, hints = listOf("Count them one by one.", "More than two."),- explanation = "There are three apples.",- )- val multiSelect = MultipleSelectQuestion(- id = "q-ms", skillId = "count",- prompt = Prompt("Pick the even numbers"),- choices = listOf(Choice("2"), Choice("3"), Choice("4")),- correctIndices = listOf(0, 2),- )- val numeric = NumericQuestion(- id = "q-num", skillId = "add",- prompt = Prompt("2 + 3 = ?"), answer = 5.0, tolerance = 0.1, unit = "apples",- )- val shortText = ShortTextQuestion(- id = "q-text", skillId = "read",- prompt = Prompt("First letter of the alphabet?"), acceptedAnswers = listOf("a", "A"),- )- val ordering = OrderingQuestion(- id = "q-ord", skillId = "count",- prompt = Prompt("Order smallest to largest"), items = listOf("1", "2", "3"),- )- val matching = MatchingQuestion(- id = "q-match", skillId = "count",- prompt = Prompt("Match the number to its word"),- left = listOf("1", "2"), right = listOf("one", "two"), correctRightForLeft = listOf(0, 1),- )- val tracing = TracingQuestion(- id = "q-trace", skillId = "write",- prompt = Prompt("Trace the letter"), glyph = "A",- )- val allQuestions = listOf(mcq, multiSelect, numeric, shortText, ordering, matching, tracing)-- val exercise = Exercise("ex1", "Counting practice", allQuestions.map { it.id })- val k2Exercise = Exercise("ex-k2", "Play time", listOf("q-mc", "q-trace", "q-match"))-- val lesson = Lesson(- id = "l1", title = "Counting 1-3",- videos = listOf(VideoRef("http://127.0.0.1:9/count.mp4", "Counting video", 125)),- exercise = exercise,- )- val k2Lesson = Lesson(id = "l-k2", title = "Fun with numbers", videos = lesson.videos, exercise = k2Exercise)- val unitQuiz = Exercise("quiz-u1", "Unit quiz", listOf("q-mc", "q-num"))- val unit = CourseUnit("u1", "Numbers", "Counting basics", listOf(lesson), quiz = unitQuiz)- val k2Unit = CourseUnit("u-k2", "Play numbers", lessons = listOf(k2Lesson))- val challenge = Exercise("ch1", "Big challenge", listOf("q-mc"))-- val mathCourse = Course(- id = "c-math", subject = Subject.MATH, title = "Math Fun", description = "Numbers",- gradeLevel = 1, units = listOf(unit, k2Unit), challenge = challenge,- )- val readingCourse = Course(- id = "c-read", subject = Subject.READING, title = "Reading Time",- gradeLevel = 4, units = listOf(CourseUnit("u-read", "Stories", lessons = listOf(Lesson("l-read", "Story time")))),- )- val scholarCourse = Course(- id = "c-scholar", subject = Subject.SCIENCE, title = "Science Lab",- gradeLevel = 8, units = listOf(CourseUnit("u-sci", "Experiments", lessons = listOf(Lesson("l-sci", "Volcanoes")))),- )-- val pack = ContentPack(- id = "test-pack", name = "Test Pack",- skills = listOf(Skill("count", Subject.MATH, "Counting"), Skill("add", Subject.MATH, "Adding"), Skill("read", Subject.READING, "Reading"), Skill("write", Subject.READING, "Writing")),- courses = listOf(mathCourse, readingCourse, scholarCourse),- questions = allQuestions,- )-- fun content(): ContentRepository = ContentRepository(listOf(pack))-- /** Seeds the process-wide Room cache with an in-memory EducationDatabase (avoids SQLCipher on JVM). */- fun seedDb(context: Context): EducationDatabase {- val app = context.applicationContext- synchronized(databases) {- val existing = databases[EducationDatabase::class]- if (existing is EducationDatabase) return existing- val db = Room.inMemoryDatabaseBuilder(app, EducationDatabase::class.java)- .allowMainThreadQueries().build()- databases[EducationDatabase::class] = db- return db- }- }-- fun repository(context: Context): EducationRepository {- seedDb(context)- return EducationRepository.get(context.applicationContext)- }-}
education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.kt b/education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.ktdeleted file mode 100644index 3f4bf542ea..0000000000--- a/education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.kt+++ /dev/null@@ -1,57 +0,0 @@-package com.vayunmathur.education--import com.vayunmathur.library.util.NavBackStack-import org.junit.runner.RunWith-import org.robolectric.Robolectric-import org.robolectric.RobolectricTestRunner-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertNotEquals-import kotlin.test.assertTrue--@RunWith(RobolectricTestRunner::class)-class MainActivityRoutesTest {- @Test fun routesCarryPayloads() {- assertEquals(Route.Home, Route.Home)- assertEquals(Route.Course("c1"), Route.Course("c1"))- assertNotEquals<Route>(Route.Course("c1"), Route.Course("c2"))- assertEquals("c1", Route.Course("c1").courseId)- assertEquals("u1", Route.UnitScreen("u1").unitId)- assertEquals("l1", Route.LessonScreen("l1").lessonId)- assertEquals("e1", Route.Quiz("e1").exerciseId)- assertEquals("http://x/v.mp4", Route.VideoPlayer("http://x/v.mp4", "T").videoUrl)- assertEquals("T", Route.VideoPlayer("http://x/v.mp4", "T").title)- assertEquals("l1", Route.K2Lesson("l1").lessonId)- assertEquals("e1", Route.K2Quiz("e1").exerciseId)- assertEquals(3, Route.K2Reward(3).stars)- val results = Route.Results(7, 5, 2)- assertEquals(7, results.total); assertEquals(5, results.correct); assertEquals(2, results.stars)- assertEquals(Route.ParentGate, Route.ParentGate)- assertEquals(Route.Parent, Route.Parent)- assertEquals(Route.Badges, Route.Badges)- }-- @Test fun pushChainReplacesSameClassOnly() {- val bs = NavBackStack<Route>(arrayOf(Route.Home))- bs.pushChain(Route.Course("c1"))- assertEquals(listOf(Route.Home, Route.Course("c1")), bs.backStack)- bs.pushChain(Route.Course("c2")) // same class: replace, don't stack- assertEquals(listOf(Route.Home, Route.Course("c2")), bs.backStack)- bs.pushChain(Route.UnitScreen("u1")) // different class: push- assertEquals(3, bs.backStack.size)- bs.pushChain(Route.UnitScreen("u2"))- assertEquals(Route.UnitScreen("u2"), bs.last())- assertEquals(3, bs.backStack.size)- bs.pop(); assertEquals(Route.Course("c2"), bs.last())- bs.reset(Route.Home); assertEquals(listOf(Route.Home), bs.backStack)- }-- @Test fun mainActivityLaunchesWithoutCrashing() {- val controller = Robolectric.buildActivity(MainActivity::class.java)- controller.create().start().resume()- // Content loads content + DB on IO, then flips ready. Give the looper a chance.- org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()- assertTrue(controller.get().isFinishing.not())- controller.pause().stop().destroy()- }-}
education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.kt b/education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.ktdeleted file mode 100644index 267032cb0b..0000000000--- a/education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.kt+++ /dev/null@@ -1,357 +0,0 @@-package com.vayunmathur.education.ui--import android.app.Application-import android.content.Context-import androidx.compose.runtime.getValue-import androidx.compose.runtime.setValue-import androidx.compose.ui.test.assertIsDisplayed-import androidx.compose.ui.test.junit4.createComposeRule-import androidx.compose.ui.test.onAllNodesWithText-import androidx.compose.ui.test.onNodeWithContentDescription-import androidx.compose.ui.test.onNodeWithText-import androidx.compose.ui.test.performClick-import androidx.compose.ui.test.performScrollTo-import androidx.compose.ui.test.performTextInput-import androidx.compose.ui.test.performTextReplacement-import androidx.test.core.app.ApplicationProvider-import com.vayunmathur.education.EducationFixtures as Fx-import com.vayunmathur.education.MainGraph-import com.vayunmathur.education.R-import com.vayunmathur.education.RootNavigation-import com.vayunmathur.education.Route-import com.vayunmathur.education.data.Learner-import com.vayunmathur.education.data.SkillProgress-import com.vayunmathur.education.util.EducationViewModel-import com.vayunmathur.education.util.EducationViewModelFactory-import com.vayunmathur.library.util.NavBackStack-import kotlinx.coroutines.cancel-import kotlinx.coroutines.launch-import kotlinx.coroutines.runBlocking-import org.junit.After-import org.junit.Before-import org.junit.Rule-import org.junit.runner.RunWith-import org.robolectric.RobolectricTestRunner-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--/** VM-backed pages: render against an in-memory Room DB and drive real interactions. */-@RunWith(RobolectricTestRunner::class)-class EducationPagesTest {- @get:Rule val rule = createComposeRule()- private val app: Application get() = ApplicationProvider.getApplicationContext()- private val ctx: Context get() = app- private val store = androidx.lifecycle.ViewModelStore()- private val collectScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default)- private lateinit var vm: EducationViewModel- private var screenContent by androidx.compose.runtime.mutableStateOf<(@androidx.compose.runtime.Composable () -> Unit)?>(null)- private var contentSet = false-- /** createComposeRule allows one setContent per activity; swap the lambda instead. */- private fun show(content: @androidx.compose.runtime.Composable () -> Unit) {- if (!contentSet) { rule.setContent { screenContent?.invoke() }; contentSet = true }- screenContent = content- rule.waitForIdle()- }- private fun str(id: Int, vararg a: Any): String = ctx.getString(id, *a)- private fun uiStr(id: Int): String = ctx.getString(id)-- @Before fun setUp() = runBlocking<Unit> {- val db = Fx.seedDb(ctx); db.clearAllTables()- vm = androidx.lifecycle.ViewModelProvider(- store, EducationViewModelFactory(app, Fx.content(), Fx.repository(ctx)),- )[EducationViewModel::class.java]- // Keep the WhileSubscribed flows hot so .value reads (verifyPin, deadlineFor) work.- collectScope.launch { vm.learner.collect {} }- collectScope.launch { vm.progress.collect {} }- collectScope.launch { vm.deadlines.collect {} }- }-- @After fun tearDown() { collectScope.cancel(); store.clear() }-- private fun stack(vararg routes: Route) = NavBackStack<Route>(routes)-- private fun seedLearner(learner: Learner) = runBlocking<Unit> {- Fx.repository(ctx).upsertLearner(learner)- val deadline = System.nanoTime() + 10_000_000_000L- while (vm.learner.value?.id != learner.id && System.nanoTime() < deadline) {- rule.waitForIdle(); Thread.sleep(10)- }- }-- private fun awaitText(text: String) {- rule.waitUntil(10_000) { onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() }- }-- @Test fun parentGateRejectsWrongPinAndAcceptsCorrect() = runBlocking<Unit> {- Fx.repository(ctx).upsertLearner(Learner(name = "Kid"))- vm.setPin("1234")- val deadline = System.nanoTime() + 10_000_000_000L- while (!vm.verifyPin("1234") && System.nanoTime() < deadline) Thread.sleep(10)- // learner flow may lag the DB write; wait until VM observes the hash.- while (vm.learner.value?.pinHash == null && System.nanoTime() < deadline) { rule.waitForIdle(); Thread.sleep(10) }- val bs = stack(Route.Home, Route.ParentGate)- show { ParentGatePage(bs, vm) }- awaitText(str(R.string.grown_ups_only))- rule.onNodeWithText(str(R.string.pin)).performTextInput("99")- // Too short: Enter stays disabled; lengthen with wrong digits.- rule.onNodeWithText(str(R.string.pin)).performTextInput("99")- rule.onNodeWithText(str(R.string.enter)).performClick()- awaitText(str(R.string.incorrect_pin))- assertEquals(Route.ParentGate, bs.last())- rule.onNodeWithText(str(R.string.pin)).performTextReplacement("1234")- rule.onNodeWithText(str(R.string.enter)).performClick()- rule.waitForIdle()- assertEquals(Route.Parent, bs.last())-- val bs2 = stack(Route.Home, Route.ParentGate)- show { ParentGatePage(bs2, vm) }- rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel), useUnmergedTree = true).performClick()- assertEquals(Route.Home, bs2.last())- }-- @Test fun parentPageRendersAndEdits() {- seedLearner(Learner(name = "Maya", gradeLevel = 4, streakCount = 3, totalStars = 7, dailyGoal = 2))- runBlocking { Fx.repository(ctx).upsertSkillProgress(SkillProgress("count", stars = 2, attempts = 1)) }- val bs = stack(Route.Home, Route.Parent)- show { ParentPage(bs, vm) }- awaitText(str(R.string.parent_settings))- awaitText("Maya")- rule.onNodeWithText(str(R.string.learner)).performScrollTo().assertIsDisplayed()- rule.onNodeWithText(str(R.string.progress)).performScrollTo().assertIsDisplayed()- rule.onNodeWithText(str(R.string.module_deadlines)).performScrollTo().assertIsDisplayed()- rule.onNodeWithText("Math Fun").performScrollTo().assertIsDisplayed()- rule.onNodeWithText("Numbers").performScrollTo().assertIsDisplayed()- rule.onNodeWithText(str(R.string.security)).performScrollTo().assertIsDisplayed()- // Change the name and goal; both persist through the VM.- rule.onNodeWithText("Maya").performScrollTo().performTextReplacement("Mayaa")- val repo = Fx.repository(ctx)- val deadline = System.nanoTime() + 10_000_000_000L- var name = ""- while (System.nanoTime() < deadline) {- name = runBlocking { repo.getLearner()?.name.orEmpty() }- if (name == "Mayaa") break- Thread.sleep(10); rule.waitForIdle()- }- assertEquals("Mayaa", name)- // Daily goal + button- rule.onNodeWithText("+").performScrollTo().performClick()- var goal = 0- while (System.nanoTime() < deadline) {- goal = runBlocking { repo.getLearner()?.dailyGoal ?: 0 }- if (goal == 3) break- Thread.sleep(10)- }- assertEquals(3, goal)- // Set a PIN via the security row.- rule.onNodeWithText(str(R.string.new_pin)).performScrollTo().performTextInput("4321")- rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.save), useUnmergedTree = true).performScrollTo().performClick()- var pinSet = false- while (System.nanoTime() < deadline) {- pinSet = runBlocking { repo.getLearner()?.pinHash } != null- if (pinSet) break- Thread.sleep(10)- }- assertTrue(pinSet)- // Set-date flow opens the date picker dialog; dismiss it.- rule.onAllNodesWithText(str(R.string.set_date))[0].performScrollTo().performClick()- rule.waitForIdle()- rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel), useUnmergedTree = true).performClick()- rule.waitForIdle()- }-- @Test fun parentPageGradeAndBandDropdowns() {- seedLearner(Learner(name = "Maya", gradeLevel = 1))- val bs = stack(Route.Home, Route.Parent)- show { ParentPage(bs, vm) }- awaitText(str(R.string.parent_settings))- // Grade dropdown lists kindergarten + numbered grades.- rule.onNodeWithText(str(R.string.grade_number, 1)).performScrollTo().performClick()- rule.waitForIdle()- rule.onNodeWithText(str(R.string.grade_number, 5)).performClick()- val repo = Fx.repository(ctx)- val deadline = System.nanoTime() + 10_000_000_000L- var grade = -1- while (System.nanoTime() < deadline) {- grade = runBlocking { repo.getLearner()?.gradeLevel ?: -1 }- if (grade == 5) break- Thread.sleep(10)- }- assertEquals(5, grade)- }-- @Test fun explorerHomeSearchAndNavigate() {- // Grade 4 is the Explorer (elementary) band: only elementary courses are listed.- seedLearner(Learner(name = "Leo", gradeLevel = 4, streakCount = 2, totalStars = 5))- val bs = stack(Route.Home)- show { ExplorerHomePage(bs, vm) }- awaitText("Reading Time")- rule.onNodeWithText("Reading Time").assertIsDisplayed()- // Searching for a non-band topic filters everything out.- rule.onNodeWithText(str(R.string.find_a_topic)).performTextInput("math")- rule.waitForIdle()- assertTrue(onAllNodesWithText("Reading Time").fetchSemanticsNodes().isEmpty())- rule.onNodeWithText(str(R.string.find_a_topic)).performTextReplacement("read")- rule.waitForIdle()- rule.onNodeWithText("Reading Time").performClick()- assertEquals(Route.Course("c-read"), bs.last())- // Continue card jumps to the first unmastered unit.- val bs2 = stack(Route.Home)- show { ExplorerHomePage(bs2, vm) }- awaitText(str(R.string.jump_back_in))- rule.onNodeWithText("Stories").performClick()- assertEquals(Route.UnitScreen("u-read"), bs2.last())- }-- @Test fun explorerCourseShowsPathAndMissing() {- seedLearner(Learner(name = "Leo", gradeLevel = 4))- runBlocking { Fx.repository(ctx).upsertSkillProgress(SkillProgress("count", stars = 3)) }- val bs = stack(Route.Home, Route.Course("c-math"))- show { ExplorerCoursePage(bs, vm, "c-math") }- awaitText("Numbers")- rule.onNodeWithText("Math Fun").assertIsDisplayed()- rule.onNodeWithText("Big challenge").performScrollTo().assertIsDisplayed()- rule.onNodeWithText("Numbers").performClick()- assertEquals(Route.UnitScreen("u1"), bs.last())-- val bs2 = stack(Route.Home)- show { ExplorerCoursePage(bs2, vm, "missing-course") }- awaitText(str(R.string.this_topic_is_unavailable))- }-- @Test fun unitAndLessonPagesNavigate() {- seedLearner(Learner(name = "Leo", gradeLevel = 1))- val bs = stack(Route.Home, Route.Course("c-math"), Route.UnitScreen("u1"))- show { UnitPage(bs, vm, "u1") }- awaitText("Counting 1-3")- rule.onNodeWithText("Unit quiz").performScrollTo().assertIsDisplayed()- rule.onNodeWithText("Counting 1-3").performClick()- assertEquals(Route.LessonScreen("l1"), bs.last())-- val bs2 = stack(Route.Home, Route.UnitScreen("u1"), Route.LessonScreen("l1"))- show { LessonPage(bs2, vm, "l1") }- awaitText("Counting video")- rule.onNodeWithText("Counting practice").performClick()- assertEquals(Route.Quiz("ex1"), bs2.last())-- val bs3 = stack(Route.Home)- show { UnitPage(bs3, vm, "missing") }- awaitText(str(R.string.this_unit_is_unavailable))- val bs4 = stack(Route.Home)- show { LessonPage(bs4, vm, "missing") }- awaitText(str(R.string.this_lesson_is_unavailable))- }-- @Test fun k2HomeLessonAndReward() {- seedLearner(Learner(name = "Kid", gradeLevel = 1, streakCount = 2, totalStars = 3))- val bs = stack(Route.Home)- show { K2HomePage(bs, vm) }- awaitText("Counting 1-3")- rule.onNodeWithText("Counting 1-3").performClick()- assertEquals(Route.K2Lesson("l1"), bs.last())-- val bs2 = stack(Route.Home, Route.K2Lesson("l-k2"))- show { K2LessonPage(bs2, vm, "l-k2") }- awaitText(str(R.string.play))- rule.onNodeWithText(str(R.string.play)).performClick()- assertEquals(Route.K2Quiz("ex-k2"), bs2.last())-- val bs3 = stack(Route.Home, Route.K2Lesson("l-k2"))- show { K2RewardPage(bs3, 2) }- awaitText(str(R.string.you_did_it))- rule.onNodeWithText("⭐⭐").assertIsDisplayed()- rule.onNodeWithText(str(R.string.home_1)).performClick()- assertEquals(listOf(Route.Home), bs3.backStack)-- val bs4 = stack(Route.Home)- show { K2LessonPage(bs4, vm, "missing") }- awaitText(str(R.string.let_s_go_back))- }-- @Test fun badgesResultsAndDispatchers() {- seedLearner(Learner(name = "Maya", gradeLevel = 8, streakCount = 4, totalStars = 9))- val bs = stack(Route.Home, Route.Badges)- show { BadgesPage(bs, vm) }- awaitText("First Star")- rule.onNodeWithText("First Star").assertIsDisplayed()-- val bs2 = stack(Route.Home, Route.Quiz("ex1"), Route.Results(3, 2, 2))- show { ResultsPage(bs2, vm, total = 3, correct = 2, stars = 2) }- awaitText(str(R.string.correct, 2, 3))- rule.onNodeWithText(str(R.string.home)).performClick()- assertEquals(listOf(Route.Home), bs2.backStack)-- // Band dispatch: grade 1 -> Explorer course shell, grade 8 -> Scholar course shell.- val bs3 = stack(Route.Home)- show { CoursePage(bs3, vm, "c-math") }- awaitText("Numbers")-- val bs4 = stack(Route.Home)- show { HomePage(bs4, vm) }- awaitText("Math Fun")-- // Root navigation waits for the learner, then shows the graph.- show { RootNavigation(vm) }- awaitText("Math Fun")- show { MainGraph(vm) }- awaitText("Math Fun")- }-- @Test fun k2RewardStarCountsClamp() {- val bs = stack(Route.Home)- show { K2RewardPage(bs, 0) }- awaitText("⭐")- show { K2RewardPage(bs, 9) }- awaitText("⭐⭐⭐")- }-- @Test fun parentBandOverrideAndDeadlineDelete() = runBlocking<Unit> {- seedLearner(Learner(name = "Maya", gradeLevel = 4))- val repo = Fx.repository(ctx)- repo.upsertDeadline(com.vayunmathur.education.data.Deadline(moduleType = "UNIT", moduleId = "u1", dueEpochDay = 20_000))- val bs = stack(Route.Home, Route.Parent)- show { ParentPage(bs, vm) }- awaitText(str(R.string.parent_settings))- // With a deadline set, that unit's button reads Change and shows a delete action.- rule.onNodeWithText(str(R.string.change)).performScrollTo().assertIsDisplayed()- rule.onNodeWithContentDescription("Delete").performScrollTo().performClick()- val deadline = System.nanoTime() + 10_000_000_000L- var deleted = false- while (System.nanoTime() < deadline) {- deleted = runBlocking { repo.getDeadlineFor("UNIT", "u1") } == null- if (deleted) break- Thread.sleep(10); rule.waitForIdle()- }- assertTrue(deleted)- // Band override dropdown: pick Explorer explicitly.- rule.onNodeWithText(str(R.string.automatic_by_grade)).performScrollTo().performClick()- rule.waitForIdle()- rule.onNodeWithText("3-5 · Explorer").performClick()- var band: String? = null- while (System.nanoTime() < deadline) {- band = runBlocking { repo.getLearner()?.bandOverride }- if (band == "ELEMENTARY") break- Thread.sleep(10)- }- assertEquals("ELEMENTARY", band)- // Deadline dialog OK path: open, pick the dialog's OK (disabled until a date is chosen, so just dismiss via Cancel).- rule.onAllNodesWithText(str(R.string.set_date))[0].performScrollTo().performClick()- rule.waitForIdle()- rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel), useUnmergedTree = true).performClick()- rule.waitForIdle()- }-- @Test fun scholarHomeDeadlineAndParentAreaRoutes() = runBlocking<Unit> {- seedLearner(Learner(name = "Maya", gradeLevel = 8, onboarded = false))- Fx.repository(ctx).upsertDeadline(com.vayunmathur.education.data.Deadline(moduleType = "UNIT", moduleId = "u1", dueEpochDay = 20_000))- val bs = stack(Route.Home)- show { HomePage(bs, vm) }- // Scholar home lists the deadline by its module title and routes to the unit.- awaitText("Numbers")- rule.onNodeWithText("Numbers").performScrollTo().performClick()- assertEquals(Route.UnitScreen("u1"), bs.last())- }-- private fun onAllNodesWithText(text: String) = rule.onAllNodesWithText(text)-}
education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.kt b/education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.ktdeleted file mode 100644index 25326c5ea5..0000000000--- a/education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.kt+++ /dev/null@@ -1,273 +0,0 @@-package com.vayunmathur.education.ui--import android.content.Context-import androidx.compose.runtime.getValue-import androidx.compose.runtime.setValue-import androidx.compose.ui.test.assertIsDisplayed-import androidx.compose.ui.test.junit4.createComposeRule-import androidx.compose.ui.test.onAllNodesWithText-import androidx.compose.ui.test.onNodeWithText-import androidx.compose.ui.test.onRoot-import androidx.compose.ui.test.performClick-import androidx.compose.ui.test.performScrollTo-import androidx.compose.ui.test.performTextInput-import androidx.compose.ui.test.performTouchInput-import androidx.compose.ui.test.swipe-import androidx.compose.ui.geometry.Offset-import androidx.test.core.app.ApplicationProvider-import com.vayunmathur.education.EducationFixtures as Fx-import com.vayunmathur.education.R-import com.vayunmathur.education.content.Answer-import com.vayunmathur.education.content.ChoiceAnswer-import com.vayunmathur.education.content.MatchingAnswer-import com.vayunmathur.education.content.MultiChoiceAnswer-import com.vayunmathur.education.content.NumericAnswer-import com.vayunmathur.education.content.OrderingAnswer-import com.vayunmathur.education.content.TextAnswer-import com.vayunmathur.education.util.QuizActions-import com.vayunmathur.education.util.QuizUiState-import org.junit.Rule-import org.junit.runner.RunWith-import org.robolectric.RobolectricTestRunner-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertNotNull-import kotlin.test.assertTrue--/** Question inputs, both quiz shells, and shared UI helpers. */-@RunWith(RobolectricTestRunner::class)-class EducationQuizInputsTest {- @get:Rule val rule = createComposeRule()- private val ctx: Context get() = ApplicationProvider.getApplicationContext()- private var screenContent by androidx.compose.runtime.mutableStateOf<(@androidx.compose.runtime.Composable () -> Unit)?>(null)- private var contentSet = false-- private fun show(content: @androidx.compose.runtime.Composable () -> Unit) {- if (!contentSet) { rule.setContent { screenContent?.invoke() }; contentSet = true }- screenContent = content- rule.waitForIdle()- }- private fun str(id: Int, vararg a: Any): String = ctx.getString(id, *a)-- @Test fun multipleChoiceSelectsAndReports() {- var answer: Answer? = null- show { QuestionInput(Fx.mcq, ChoiceAnswer(0), enabled = true) { answer = it } }- rule.onNodeWithText("3").assertIsDisplayed().performClick()- assertEquals(ChoiceAnswer(1), answer)- rule.onNodeWithText("7").performClick()- assertEquals(ChoiceAnswer(2), answer)- }-- @Test fun multipleSelectTogglesSet() {- var answer: Answer? = null- show { QuestionInput(Fx.multiSelect, null, enabled = true) { answer = it } }- rule.onNodeWithText("2").performClick()- assertEquals(MultiChoiceAnswer(setOf(0)), answer)- rule.onNodeWithText("4").performClick()- assertEquals(MultiChoiceAnswer(setOf(0, 2)), answer)- rule.onNodeWithText("2").performClick()- assertEquals(MultiChoiceAnswer(setOf(2)), answer)- }-- @Test fun numericAndShortTextInputs() {- var answer: Answer? = null- show { QuestionInput(Fx.numeric, null, enabled = true) { answer = it } }- rule.onNodeWithText(str(R.string.answer_1, "apples")).performTextInput("42")- assertEquals(NumericAnswer(42.0), answer)- show { QuestionInput(Fx.shortText, null, enabled = true) { answer = it } }- rule.onNodeWithText(str(R.string.answer)).performTextInput("a")- assertEquals(TextAnswer("a"), answer)- }-- @Test fun orderingPublishesInitialAndReorders() {- var answer: Answer? = null- show { QuestionInput(Fx.ordering, null, enabled = true) { answer = it } }- rule.waitForIdle()- val initial = answer as? OrderingAnswer- assertNotNull(initial)- assertEquals(listOf(0, 1, 2), initial.order.sorted())- assertTrue(rule.onAllNodesWithText("3").fetchSemanticsNodes().isNotEmpty())- }-- @Test fun matchingPublishesWhenComplete() {- var answer: Answer? = null- show { QuestionInput(Fx.matching, null, enabled = true) { answer = it } }- // Pick the right-hand option for the first left item, then the second.- rule.onAllNodesWithText(str(R.string.choose))[0].performClick()- rule.waitForIdle()- rule.onNodeWithText("one").performClick()- rule.waitForIdle()- assertEquals(null, answer)- rule.onAllNodesWithText(str(R.string.choose))[0].performClick()- rule.waitForIdle()- rule.onNodeWithText("two").performClick()- rule.waitForIdle()- assertEquals(MatchingAnswer(listOf(0, 1)), answer)- }-- @Test fun tracingGestureCompletes() {- var traced = false- show { TracingCanvas(glyph = "B", enabled = true, onTraced = { traced = true }) }- rule.onNodeWithText("B").assertIsDisplayed()- assertEquals(false, traced)- // Long horizontal swipes across the canvas accumulate past the trace threshold.- val root = rule.onRoot()- repeat(4) {- root.performTouchInput { swipe(Offset(60f, center.y), Offset(width - 60f, center.y), 120) }- rule.waitForIdle()- }- assertEquals(true, traced)- }-- @Test fun dragMatchRendersAndMissedDropSnapsBack() {- var solved = false- show { K2DragMatch(Fx.matching, enabled = true) { solved = true } }- rule.onNodeWithText("one").assertIsDisplayed()- rule.onNodeWithText("two").assertIsDisplayed()- // Drag a chip a short distance inside its own column (no target there):- // a missed drop must snap back and not solve or mark any target.- // (Synthetic gestures cannot reproduce the per-frame bounds updates the- // hit test uses on a real device, so the correct-drop path is not- // asserted here.)- rule.onNodeWithText("one").performTouchInput {- swipe(Offset(center.x, center.y), Offset(center.x, center.y + 60f), 200)- }- rule.waitForIdle()- assertEquals(false, solved)- rule.onNodeWithText("one").assertIsDisplayed()- rule.onNodeWithText("1").assertIsDisplayed()- }-- @Test fun quizScreenFullFlowScholar() {- var finishedQuestions: Int = -1- var finishedAnswers: Map<String, Answer?>? = null- var up = false- val actions = object : QuizActions {- override fun navigateUp() { up = true }- override fun finish(questions: List<com.vayunmathur.education.content.Question>, answers: Map<String, Answer?>) {- finishedQuestions = questions.size; finishedAnswers = answers- }- }- val questions = listOf(Fx.mcq, Fx.numeric)- show { QuizScreen(QuizUiState(title = "Practice", questions = questions), actions) }- rule.onNodeWithText("Practice").assertIsDisplayed()- rule.onNodeWithText(str(R.string.question_of, 1, 2)).assertIsDisplayed()- // Check is disabled until an answer is chosen.- rule.onNodeWithText("3").performClick()- rule.onNodeWithText(str(R.string.show_a_hint)).performClick()- rule.waitForIdle()- rule.onNodeWithText("💡 Count them one by one.").assertIsDisplayed()- rule.onNodeWithText(str(R.string.check)).performClick()- rule.waitForIdle()- rule.onNodeWithText(str(R.string.correct_1)).assertIsDisplayed()- rule.onNodeWithText("There are three apples.").assertIsDisplayed()- rule.onNodeWithText(str(R.string.next)).performClick()- rule.waitForIdle()- rule.onNodeWithText(str(R.string.answer_1, "apples")).performTextInput("5")- rule.onNodeWithText(str(R.string.check)).performClick()- rule.waitForIdle()- rule.onNodeWithText(str(R.string.finish)).performClick()- assertEquals(2, finishedQuestions)- assertEquals(ChoiceAnswer(1), finishedAnswers?.get("q-mc"))- assertEquals(NumericAnswer(5.0), finishedAnswers?.get("q-num"))- assertEquals(false, up)- }-- @Test fun quizScreenEmptyAndWrongFeedback() {- show { QuizScreen(QuizUiState(title = "Empty", questions = emptyList()), QuizActions.Noop) }- rule.onNodeWithText(str(R.string.this_exercise_has_no_questions_yet)).assertIsDisplayed()- show {- QuizScreen(- QuizUiState(title = "Practice", questions = listOf(Fx.mcq)), QuizActions.Noop,- initialIndex = 0, initialChecked = true, initialAnswers = mapOf("q-mc" to ChoiceAnswer(0)),- )- }- rule.onNodeWithText(str(R.string.not_quite)).assertIsDisplayed()- }-- @Test fun k2QuizCorrectAdvancesAndFinishes() {- var finished: Int = -1- val actions = object : QuizActions {- override fun finish(questions: List<com.vayunmathur.education.content.Question>, answers: Map<String, Answer?>) { finished = questions.size }- }- show { K2QuizScreen(QuizUiState(questions = listOf(Fx.mcq, Fx.tracing)), actions) }- rule.onNodeWithText("How many apples?").assertIsDisplayed()- // Wrong choice wiggles into the error color but stays on the question.- rule.onNodeWithText("1").performClick()- rule.waitForIdle()- rule.onNodeWithText("How many apples?").assertIsDisplayed()- assertEquals(-1, finished)- // Correct choice celebrates, then advances to tracing; finish after the trace question.- rule.onNodeWithText("3").performClick()- rule.waitForIdle()- rule.onNodeWithText(str(R.string.great_job)).assertIsDisplayed()- rule.waitUntil(10_000) { rule.onAllNodesWithText("Trace the letter").fetchSemanticsNodes().isNotEmpty() }- // Trace the glyph to complete the last question; the quiz then finishes.- val root = rule.onRoot()- var swipes = 0- while (finished != 2 && swipes < 6) {- root.performTouchInput { swipe(Offset(60f, center.y), Offset(width - 60f, center.y), 120) }- rule.waitForIdle()- swipes++- }- rule.waitUntil(10_000) { finished == 2 }- }-- @Test fun k2QuizEmptyShowsGoBack() {- show { K2QuizScreen(QuizUiState(questions = emptyList()), QuizActions.Noop) }- rule.onNodeWithText(str(R.string.let_s_go_back)).assertIsDisplayed()- }-- @Test fun commonHelpers() {- show {- androidx.compose.foundation.layout.Column {- StarRow(2)- StreakChip(3)- StarsChip(7)- DeadlineChip(System.currentTimeMillis() / 86_400_000)- SectionHeader("Header text")- }- }- rule.onNodeWithText("Header text").assertIsDisplayed()- rule.onNodeWithText("7").assertIsDisplayed()- assertEquals("K-2 · Guided Playground", bandLabel(com.vayunmathur.education.content.Band.K2))- assertEquals("3-5 · Explorer", bandLabel(com.vayunmathur.education.content.Band.ELEMENTARY))- assertEquals("6-12 · Scholar", bandLabel(com.vayunmathur.education.content.Band.SCHOLAR))- assertEquals(0, averageStars(emptyList(), emptyMap()))- assertEquals(2, averageStars(listOf("a", "b"), mapOf("a" to com.vayunmathur.education.data.SkillProgress("a", stars = 3), "b" to com.vayunmathur.education.data.SkillProgress("b", stars = 1))))- assertTrue(formatEpochDay(ctx, 20_000).isNotEmpty())- // Subject colors are defined for every subject.- show {- androidx.compose.foundation.layout.Column {- com.vayunmathur.education.content.Subject.entries.forEach { s -> Text2Colors(s) }- }- }- rule.waitForIdle()- }-- @androidx.compose.runtime.Composable- private fun Text2Colors(s: com.vayunmathur.education.content.Subject) {- val c = subjectColors(s)- com.vayunmathur.library.ui.Text(s.name + ":" + c.container.value.toString())- }-- @Test fun rememberNarratorComposesAndDisposes() {- show {- val narrator = com.vayunmathur.education.util.rememberNarrator()- androidx.compose.runtime.LaunchedEffect(Unit) { narrator.narrate("Ready to learn") }- com.vayunmathur.library.ui.Text("narrator up")- }- rule.onNodeWithText("narrator up").assertIsDisplayed()- // Swapping content disposes the narrator (TTS shutdown under Robolectric).- show { com.vayunmathur.library.ui.Text("gone") }- rule.onNodeWithText("gone").assertIsDisplayed()- }-- @Test fun videoPlayerRendersTitle() {- val bs = com.vayunmathur.library.util.NavBackStack<com.vayunmathur.education.Route>(arrayOf(com.vayunmathur.education.Route.Home))- show { VideoPlayerPage(bs, "http://127.0.0.1:9/none.mp4", "Space video") }- rule.onNodeWithText("Space video").assertIsDisplayed()- }-- private fun onAllNodesWithText(text: String) = rule.onAllNodesWithText(text)-}
education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.kt b/education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.ktdeleted file mode 100644index d3f00aebe0..0000000000--- a/education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.kt+++ /dev/null@@ -1,288 +0,0 @@-package com.vayunmathur.education.util--import android.app.Application-import android.content.Context-import androidx.test.core.app.ApplicationProvider-import com.vayunmathur.education.EducationFixtures as Fx-import com.vayunmathur.education.content.Band-import com.vayunmathur.education.content.ChoiceAnswer-import com.vayunmathur.education.content.ContentRepository-import com.vayunmathur.education.content.MatchingAnswer-import com.vayunmathur.education.content.ModuleType-import com.vayunmathur.education.content.MultiChoiceAnswer-import com.vayunmathur.education.content.NumericAnswer-import com.vayunmathur.education.content.OrderingAnswer-import com.vayunmathur.education.content.TextAnswer-import com.vayunmathur.education.content.TraceAnswer-import com.vayunmathur.education.data.Deadline-import com.vayunmathur.education.data.Learner-import com.vayunmathur.education.data.SkillProgress-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.cancel-import kotlinx.coroutines.launch-import kotlinx.coroutines.runBlocking-import org.junit.After-import org.junit.Before-import org.junit.runner.RunWith-import org.robolectric.RobolectricTestRunner-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertNotNull-import kotlin.test.assertNull-import kotlin.test.assertTrue--@RunWith(RobolectricTestRunner::class)-class EducationViewModelTest {- private val app: Application get() = ApplicationProvider.getApplicationContext()- private val ctx: Context get() = app- private val store = androidx.lifecycle.ViewModelStore()- private val collectScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default)- private lateinit var vm: EducationViewModel-- @Before fun setUp() = runBlocking<Unit> {- val db = Fx.seedDb(ctx)- db.clearAllTables()- vm = androidx.lifecycle.ViewModelProvider(- store,- EducationViewModelFactory(app, Fx.content(), Fx.repository(ctx)),- )[EducationViewModel::class.java]- // The VM's flows are WhileSubscribed: keep collectors running so .value updates.- collectScope.launch { vm.learner.collect {} }- collectScope.launch { vm.progress.collect {} }- collectScope.launch { vm.deadlines.collect {} }- }-- @After fun tearDown() { collectScope.cancel(); store.clear() }-- private fun awaitVm(label: String, cond: () -> Boolean) {- // viewModelScope runs on the (paused) Robolectric main looper: pump it while waiting.- val deadline = System.nanoTime() + 10_000_000_000L- while (!cond() && System.nanoTime() < deadline) {- org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()- Thread.sleep(10)- }- assertTrue(cond(), "timed out awaiting: $label")- }-- // --- DAO / repository --------------------------------------------------- @Test fun daoCrudAndFlows() = runBlocking<Unit> {- val repo = Fx.repository(ctx)- assertNull(repo.getLearner())- repo.upsertLearner(Learner(name = "Maya", gradeLevel = 3, totalStars = 4))- assertEquals("Maya", repo.getLearner()?.name)- assertEquals("Maya", repo.learnerFlow().first()?.name)- repo.upsertLearner(Learner(name = "Leo"))- assertEquals(1L, repo.getLearner()?.id); assertEquals("Leo", repo.getLearner()?.name)-- repo.upsertSkillProgress(SkillProgress("count", stars = 2, attempts = 1, lastPracticedEpochDay = 10))- repo.upsertSkillProgress(SkillProgress("add", stars = 3))- assertEquals(2, repo.getAllSkillProgress().size)- assertEquals(2, repo.skillProgressFlow().first().size)- assertEquals(3, repo.getSkillProgress("add")?.stars)- assertNull(repo.getSkillProgress("nope"))-- repo.upsertDeadline(Deadline(moduleType = "UNIT", moduleId = "u1", dueEpochDay = 100, note = "n"))- repo.upsertDeadline(Deadline(moduleType = "UNIT", moduleId = "u2", dueEpochDay = 50))- assertEquals(listOf(50L, 100L), repo.deadlinesFlow().first().map { it.dueEpochDay })- val found = repo.getDeadlineFor("UNIT", "u1"); assertNotNull(found)- repo.deleteDeadline(found)- assertNull(repo.getDeadlineFor("UNIT", "u1"))- assertEquals(1, repo.deadlinesFlow().first().size)- }-- @Test fun repositoryIsSingleton() {- assertTrue(Fx.repository(ctx) === Fx.repository(ctx))- }-- // --- Content repository ------------------------------------------------ @Test fun contentRepositoryIndexesAndQueries() {- val content = Fx.content()- assertEquals(3, content.courses.size)- assertEquals(setOf("q-mc", "q-ms", "q-num", "q-text", "q-ord", "q-match", "q-trace"), content.questions.keys)- assertEquals(Fx.mathCourse, content.course("c-math")); assertNull(content.course("nope"))- assertEquals(Fx.unit, content.unit("u1")); assertEquals(Fx.lesson, content.lesson("l1"))- assertEquals(Fx.exercise, content.exercise("ex1")); assertEquals(Fx.unitQuiz, content.exercise("quiz-u1"))- assertEquals(Fx.challenge, content.exercise("ch1")); assertNull(content.exercise("nope"))- assertEquals(Fx.mathCourse, content.courseOfUnit("u1")); assertNull(content.courseOfUnit("nope"))- assertEquals(Fx.allQuestions, content.questionsFor(Fx.exercise))- assertEquals(listOf("count"), content.skillIdsOf(Fx.unitQuiz.copy(questionIds = listOf("q-mc"))))- assertTrue(content.skillIdsOfCourse(Fx.mathCourse).containsAll(listOf("count", "add", "read", "write")))- assertEquals("Math Fun", content.moduleTitle(ModuleType.COURSE, "c-math"))- assertEquals("Numbers", content.moduleTitle(ModuleType.UNIT, "u1"))- assertEquals("Counting 1-3", content.moduleTitle(ModuleType.LESSON, "l1"))- assertNull(content.moduleTitle(ModuleType.LESSON, "nope"))- assertEquals(listOf(Fx.mathCourse), content.coursesForBand(Band.K2))- assertEquals(listOf(Fx.readingCourse), content.coursesForBand(Band.ELEMENTARY))- assertEquals(listOf(Fx.scholarCourse), content.coursesForBand(Band.SCHOLAR))- assertEquals(listOf(Fx.mathCourse), content.coursesForSubject(com.vayunmathur.education.content.Subject.MATH))- assertEquals(emptyList(), content.coursesForSubject(com.vayunmathur.education.content.Subject.MATH, Band.SCHOLAR))- assertEquals(listOf(com.vayunmathur.education.content.Subject.MATH, com.vayunmathur.education.content.Subject.SCIENCE, com.vayunmathur.education.content.Subject.READING), content.subjects)- val empty = ContentRepository(emptyList())- assertTrue(empty.courses.isEmpty() && empty.questions.isEmpty() && empty.subjects.isEmpty())- }-- @Test fun contentRepositoryLoadsBundledAssets() {- val loaded = ContentRepository.load(ctx)- assertTrue(loaded.courses.isNotEmpty(), "bundled content packs should parse")- assertTrue(loaded.questions.isNotEmpty())- assertTrue(loaded.courses.all { it.units.isNotEmpty() })- }-- // --- Pure VM logic -------------------------------------------------------- @Test fun gradeCoversEveryQuestionType() {- val allRight = mapOf(- "q-mc" to ChoiceAnswer(1), "q-ms" to MultiChoiceAnswer(setOf(0, 2)),- "q-num" to NumericAnswer(5.05), "q-text" to TextAnswer(" A "),- "q-ord" to OrderingAnswer(listOf(0, 1, 2)), "q-match" to MatchingAnswer(listOf(0, 1)),- "q-trace" to TraceAnswer,- )- val perfect = vm.grade(Fx.allQuestions, allRight)- assertEquals(7, perfect.total); assertEquals(7, perfect.correct); assertEquals(3, perfect.stars)- assertEquals(3, perfect.perSkillStars["count"])-- val allWrong = mapOf(- "q-mc" to ChoiceAnswer(0), "q-ms" to MultiChoiceAnswer(setOf(1)),- "q-num" to NumericAnswer(6.0), "q-text" to TextAnswer("z"),- "q-ord" to OrderingAnswer(listOf(2, 1, 0)), "q-match" to MatchingAnswer(listOf(1, 0)),- "q-trace" to ChoiceAnswer(0),- )- val zero = vm.grade(Fx.allQuestions, allWrong)- assertEquals(0, zero.correct); assertEquals(0, zero.stars)- // Missing answers count as wrong, empty quiz is 0 stars.- assertEquals(0, vm.grade(Fx.allQuestions, emptyMap()).correct)- assertEquals(QuizResult(0, 0, 0, emptyMap()), vm.grade(emptyList(), emptyMap()))- }-- @Test fun bandOfHonoursOverrideAndGrades() = runBlocking<Unit> {- assertEquals(Ban
Diff truncated.