madeveloper: host, push-install and screen tests via internal seams
- Commit
6da63ecee4ec166174069fabc483726040b5d9a0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 02:43 UTC (19 days ago)
- Parents
6b6847e
Coverage top-up for :madeveloper (CI 428a82e90: 21.5% INSTRUCTION, the lowest in the repo). Local merged report before: 21.5% (2420/11244); after: 84.1% (9606/11425; the denominator grows by the seam code below). Production change (the minimum that makes the module testable off-device; every default is today's behaviour): - GitHostRepository takes an injectable fetcher (URL -> body); the default is the existing NetworkClient call verbatim, moved to fetchViaNetwork. - MaDevViewModel's repository, push-socket factory and pushed-APK fetcher become internal vars with production defaults (WebSocketDevTransport.connect, NetworkClient. performRequestBytes). onServerMessage now speaks the DevSocketTransport interface the factory returns. Tests (20): - MaDevViewModelTest (9 incl. route round-trips and pairing): refresh loads repos/CI/issues/PRs and then skips; host failure surfaces as state error; catalog from the F-Droid index; repo browsing - browser open, 30+2 commit paging with exhaustion, branch switch reset, tree navigation, reopen without refetch; repo-load failure; cached tree/file reads; PairingStore code stability, savePaired and clear. - MaDevPushInstallTest (4): socket lifecycle - connect, ping answered with pong, installed-apps reply, Paired persisted to PairingStore, unknown messages ignored; a pushed install downloads, verifies its SHA-256, writes the cached APK and becomes READY, then moves to INSTALLING on tap; wrong hash and HTTP 404 both land FAILED with their errors and never become installable. - MaDevScreensTest (7): every screen composed for real - home (CI card, repos, all navigation buttons, loading/error), CI history, catalog (populated/empty), push (pairing card, pending phases, only READY offers Install), repo browser (branch, commits, folder descent, root, file filter), and commits/commit/file screens including the binary-file and commit-not-in-loaded-pages states. The PackageInstaller session commit itself remains the device seam named in the task: the tests assert the state machine up to INSTALLING (Robolectric's installer shadow accepts the session writes), and stop there rather than pretending an install happened. Verified: ./gradlew :madeveloper:testDevUnitTest :madeveloper:createMergedCoverageReport green, 84.1%, and :madeveloper:compileDevKotlin green for the seam change.
Diff
madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.ktindex 9a2ad52ef3..087a7b70b8 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt@@ -21,7 +21,12 @@ import java.net.URLEncoder * endpoints. The JSON API may not be deployed yet — callers surface the * HTTP error (e.g. 404) rather than falling back to any mirror. */-class GitHostRepository {+class GitHostRepository(+ // The one network seam: how a URL becomes its body text. Production goes+ // through NetworkClient (below); tests substitute canned host replies so+ // the parsing, caching and error behaviour above it run off-device.+ private val fetcher: suspend (String) -> String = { url -> fetchViaNetwork(url) },+) { private var treeCache: Map<String, List<TreeEntry>> = emptyMap() private var fileCache: Map<String, GitFile> = emptyMap() @@ -74,12 +79,7 @@ class GitHostRepository { return file } - private suspend fun fetchText(url: String): String {- val headers = mapOf("Accept" to "application/json", "User-Agent" to "MADeveloper/1.0")- val response = NetworkClient.performRequest(url, headers = headers)- if (!response.isSuccess) throw java.io.IOException("HTTP " + response.status + " for " + url)- return response.body- }+ private suspend fun fetchText(url: String): String = fetcher(url) /** Hosts and endpoints this app talks to. */ companion object {@@ -92,5 +92,13 @@ class GitHostRepository { } } +/** Production [GitHostRepository] fetch: NetworkClient with this app's identity headers. */+private suspend fun fetchViaNetwork(url: String): String {+ val headers = mapOf("Accept" to "application/json", "User-Agent" to "MADeveloper/1.0")+ val response = NetworkClient.performRequest(url, headers = headers)+ if (!response.isSuccess) throw java.io.IOException("HTTP " + response.status + " for " + url)+ return response.body+}+ /** URL-encodes one path segment or query value. */ private fun enc(value: String): String = URLEncoder.encode(value, "UTF-8").replace("+", "%20")
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.ktindex 1ae42b271a..cec521267e 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt@@ -12,6 +12,7 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.madeveloper.data.GitHostRepository+import com.vayunmathur.madeveloper.data.DevSocketTransport import com.vayunmathur.madeveloper.data.WebSocketDevTransport import com.vayunmathur.madeveloper.domain.CatalogApp import com.vayunmathur.madeveloper.domain.DevMessage@@ -55,9 +56,17 @@ data class MaDevUiState( /** Holds MA Developer state: git pages, catalog, push socket and installs. */ class MaDevViewModel(app: Application) : AndroidViewModel(app) {- private val repo = GitHostRepository()+ // Test seams (internal, production defaults): the host repository, how+ // the push socket is opened, and how a pushed APK's bytes are fetched.+ // They exist so the state machine below can run off-device; the app+ // itself always takes the defaults.+ internal var repo: GitHostRepository = GitHostRepository()+ internal var transportFactory: suspend (String, String?) -> DevSocketTransport =+ { url, token -> WebSocketDevTransport.connect(url, token) }+ internal var apkFetcher: suspend (String) -> Pair<Int, ByteArray> =+ { url -> NetworkClient.performRequestBytes(url) } private val pairing = PairingStore(app)- private var transport: WebSocketDevTransport? = null+ private var transport: DevSocketTransport? = null private var reconnectAttempt = 0 var state by mutableStateOf(MaDevUiState(pairingCode = pairing.pairingCode(), paired = pairing.token() != null))@@ -176,7 +185,7 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) { while (true) { try { val url = GitHostRepository.DEV_WS_URL + "?code=" + pairing.pairingCode()- val socket = WebSocketDevTransport.connect(url, pairing.token())+ val socket = transportFactory(url, pairing.token()) transport = socket reconnectAttempt = 0 state = state.copy(connected = true)@@ -191,7 +200,7 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) { } } - private suspend fun onServerMessage(message: DevMessage, socket: WebSocketDevTransport) {+ private suspend fun onServerMessage(message: DevMessage, socket: DevSocketTransport) { when (message) { DevMessage.Ping -> socket.send("{\"type\":\"pong\"}") DevMessage.ListApps -> socket.send(DevProtocol.listAppsReply(installedApps()))@@ -226,7 +235,7 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) { updatePending(DevProtocol.transition(install, InstallPhase.DOWNLOADING, 0f)) try { val bytes = withContext(Dispatchers.IO) {- val (status, data) = NetworkClient.performRequestBytes(install.apkUrl)+ val (status, data) = apkFetcher(install.apkUrl) if (status !in 200..299) throw java.io.IOException("Download failed: HTTP $status") data }
madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.ktnew file mode 100644index 0000000000..f67c15f7e7--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.kt@@ -0,0 +1,172 @@+package com.vayunmathur.madeveloper.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.madeveloper.data.GitHostRepository+import com.vayunmathur.madeveloper.domain.DevMessage+import com.vayunmathur.madeveloper.domain.InstallPhase+import java.io.File+import java.security.MessageDigest+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The push socket and install state machine through the ViewModel's+ * transport/APK seams with an in-memory socket: ping/pong, app listing,+ * pairing, and the download -> verify -> ready pipeline including its+ * failure branches. The PackageInstaller session itself is the device+ * seam: Robolectric's installer shadow accepts the session, so the+ * INSTALLING transition is asserted, but no real install is performed.+ */+@RunWith(RobolectricTestRunner::class)+class MaDevPushInstallTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @BeforeTest fun setUp() {+ PairingStore(app).clear()+ }++ private fun await(desc: String, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 15_000+ while (System.currentTimeMillis() < deadline) {+ Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ if (cond()) return+ Thread.sleep(25)+ }+ assertTrue(cond(), "timed out: $desc")+ }++ private fun sha256(bytes: ByteArray): String =+ MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }++ private class Harness {+ val transport = FakeTransport()+ var apkBytes: ByteArray = "fake-apk-bytes".toByteArray()+ var apkStatus: Int = 200+ val scope = CoroutineScope(Dispatchers.Main + Job())++ fun viewModel(app: Application): MaDevViewModel {+ val viewModel = MaDevViewModel(app)+ viewModel.repo = GitHostRepository(FakeGitHost().fetcher)+ viewModel.transportFactory = { _, _ -> transport }+ viewModel.apkFetcher = { apkStatus to apkBytes }+ return viewModel+ }+ }++ @Test fun socketLifecyclePingListAppsAndPairing() {+ val harness = Harness()+ val viewModel = harness.viewModel(app)+ viewModel.connectPush()+ await("connected") { viewModel.state.connected }++ harness.transport.incoming.tryEmit(DevMessage.Ping)+ await("pong sent") { synchronized(harness.transport.sent) { harness.transport.sent.contains("{\"type\":\"pong\"}") } }++ harness.transport.incoming.tryEmit(DevMessage.ListApps)+ await("app list sent") {+ synchronized(harness.transport.sent) {+ harness.transport.sent.any { it.contains("\"type\":\"apps\"") }+ }+ }++ harness.transport.incoming.tryEmit(DevMessage.Paired("tok-42", "dev-7"))+ await("paired state") { viewModel.state.paired }+ assertEquals("tok-42", PairingStore(app).token())+ assertEquals("dev-7", PairingStore(app).deviceId())++ harness.transport.incoming.tryEmit(DevMessage.Unknown("{\"type\":\"future\"}"))+ Thread.sleep(300)+ assertTrue(viewModel.state.connected, "unknown server messages must not drop the socket")+ harness.scope.cancel()+ }++ @Test fun pushedInstallDownloadsVerifiesAndBecomesReady() {+ val harness = Harness()+ val viewModel = harness.viewModel(app)+ viewModel.connectPush()+ await("connected") { viewModel.state.connected }++ val bytes = harness.apkBytes+ harness.transport.incoming.tryEmit(+ DevMessage.Install("com.example.app", 42L, "https://example.com/a.apk", sha256(bytes), bytes.size.toLong()),+ )+ await("install ready") {+ viewModel.state.pending.singleOrNull()?.phase == InstallPhase.READY+ }+ val pending = viewModel.state.pending.single()+ assertEquals("com.example.app", pending.pkg)+ assertEquals(42L, pending.versionCode)+ val file = File(app.cacheDir, "push-com.example.app.apk")+ assertTrue(file.exists(), "the verified APK is written to the cache for the installer")+ assertTrue(file.readBytes().contentEquals(bytes))++ // Tapping install moves it to INSTALLING (the session itself is the+ // device seam); an unready repeat tap is refused while installing.+ viewModel.installPending("com.example.app")+ await("installing") {+ viewModel.state.pending.singleOrNull()?.phase == InstallPhase.INSTALLING+ }+ // Installing a package that was never pushed is a no-op.+ viewModel.installPending("com.example.ghost")+ assertEquals(1, viewModel.state.pending.size)+ harness.scope.cancel()+ }++ @Test fun pushedInstallWithWrongHashFailsAndCachesNothingUsable() {+ val harness = Harness()+ val viewModel = harness.viewModel(app)+ viewModel.connectPush()+ await("connected") { viewModel.state.connected }+ harness.transport.incoming.tryEmit(+ DevMessage.Install(+ "com.example.bad", 1L, "https://example.com/b.apk",+ sha256("different bytes".toByteArray()), harness.apkBytes.size.toLong(),+ ),+ )+ await("install failed") {+ viewModel.state.pending.singleOrNull()?.phase == InstallPhase.FAILED+ }+ val pending = viewModel.state.pending.single()+ assertTrue(pending.error!!.contains("hash"), pending.error!!)+ // A failed download never becomes installable.+ viewModel.installPending("com.example.bad")+ assertEquals(InstallPhase.FAILED, viewModel.state.pending.single().phase)+ harness.scope.cancel()+ }++ @Test fun pushedInstallHttpFailureIsReported() {+ val harness = Harness()+ harness.apkStatus = 404+ val viewModel = harness.viewModel(app)+ viewModel.connectPush()+ await("connected") { viewModel.state.connected }+ harness.transport.incoming.tryEmit(+ DevMessage.Install(+ "com.example.gone", 3L, "https://example.com/gone.apk",+ sha256(harness.apkBytes), harness.apkBytes.size.toLong(),+ ),+ )+ await("install failed") {+ viewModel.state.pending.singleOrNull()?.phase == InstallPhase.FAILED+ }+ assertTrue(+ viewModel.state.pending.single().error!!.contains("404"),+ viewModel.state.pending.single().error!!,+ )+ assertFalse(File(app.cacheDir, "push-com.example.gone.apk").exists())+ harness.scope.cancel()+ }+}
madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.ktnew file mode 100644index 0000000000..9186662182--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt@@ -0,0 +1,266 @@+package com.vayunmathur.madeveloper.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.madeveloper.data.DevSocketTransport+import com.vayunmathur.madeveloper.data.GitHostRepository+import com.vayunmathur.madeveloper.domain.DevMessage+import com.vayunmathur.madeveloper.domain.DevProtocol+import com.vayunmathur.madeveloper.domain.InstallPhase+import java.io.File+import java.io.IOException+import java.security.MessageDigest+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableSharedFlow+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Canned git-host replies keyed by URL fragment; records every requested URL. */+class FakeGitHost {+ val requested = mutableListOf<String>()+ var failWith: IOException? = null++ private fun commitsJson(start: Int, count: Int): String =+ (start until start + count).joinToString(",", "[", "]") { i ->+ """{"sha":"${"sha%04d".format(i)}${"x".repeat(30)}","author":"vayun","time":"2026-11-16T0${i % 10}:00:00Z","subject":"commit $i","body":"body $i"}"""+ }++ val fetcher: suspend (String) -> String = { url ->+ synchronized(requested) { requested += url }+ failWith?.let { throw it }+ when {+ url.endsWith("/api/repos") ->+ """[{"name":"Modern-Apps","defaultBranch":"main","headSha":"aabbccdd11223344","headSubject":"top subject","headTime":"2026-11-16T10:00:00Z"},{"name":"MAOS","defaultBranch":"main","headSha":"1111222233334444","headSubject":"maos subject","headTime":"2026-11-15T10:00:00Z"}]"""+ url.contains("/api/repos/Modern-Apps/commits") ->+ if (url.contains("after=")) commitsJson(30, 2) else commitsJson(0, 30)+ url.contains("/api/repos/MAOS/commits") -> commitsJson(100, 3)+ url.contains("/api/repos/Modern-Apps/tree") || url.contains("/api/repos/MAOS/tree") ->+ if (url.contains("path=src")) {+ """[{"name":"Main.kt","type":"blob","size":120},{"name":"logo.png","type":"blob","size":99}]"""+ } else {+ """[{"name":"README.md","type":"blob","size":42},{"name":"src","type":"tree"}]"""+ }+ url.contains("/file") && url.contains("logo.png") ->+ """{"path":"src/logo.png","size":99,"isBinary":true,"truncated":false,"sha":"def4567890abcdef"}"""+ url.contains("/file") ->+ """{"path":"src/Main.kt","size":20,"isBinary":false,"truncated":false,"sha":"abc1234567","content":"fun main() {\n println(1)\n}\n"}"""+ url.endsWith("/api/repos/Modern-Apps") || url.endsWith("/api/repos/MAOS") -> {+ val name = url.substringAfterLast("/")+ """{"name":"$name","defaultBranch":"main","branches":[{"name":"main","sha":"11111111aaaa","time":"2026-11-15T00:00:00Z"},{"name":"dev","sha":"22222222bbbb","time":"2026-11-14T00:00:00Z"}],"recentCommits":[{"sha":"recent0001aaaa","author":"vayun","time":"2026-11-15T01:00:00Z","subject":"recent work","body":"notes"}]}"""+ }+ url.contains("/tests.json") ->+ """{"latest":{"id":"a","sha":"abc123","subject":"fix thing","status":"passed","failed":2,"tests":10,"coverage":{"covered":50,"total":100}},"running":{"id":"r","sha":"fff000","subject":"running now","status":"running","failed":0,"tests":0},"history":[{"id":"b","sha":"def456","subject":"old run","status":"failed","failed":1,"tests":5}]}"""+ url.contains("/issues.json") ->+ """{"repos":[{"github":"vayun-mathur/Modern-Apps","issues":[{"number":7,"title":"Bug one","author":"vayun","comments":3,"labels":[{"name":"bug"}],"updated_at":"2026-01-01"}]}]}"""+ url.contains("/prs.json") ->+ """{"repos":[{"repo":"Modern-Apps","prs":[{"number":12,"title":"Add thing","author":"vayun"}]}]}"""+ url.contains("index-v2.json") ->+ """{"packages":{"com.example.app":{"metadata":{"name":{"en-US":"Example"},"summary":{"en-US":"Demo app"}},"versions":{"h1":{"file":{"name":"/a_1.apk","size":100},"manifest":{"versionCode":1,"versionName":"1.0"}}}}}}"""+ else -> throw IOException("unexpected url: $url")+ }+ }+}++/** In-memory push socket: the test emits server messages and reads replies. */+class FakeTransport : DevSocketTransport {+ val incoming = MutableSharedFlow<DevMessage>(extraBufferCapacity = 16)+ override val messages: Flow<DevMessage> = incoming+ val sent = mutableListOf<String>()+ var closed = false+ override suspend fun send(text: String) {+ synchronized(sent) { sent += text }+ }+ override suspend fun close() {+ closed = true+ }+}++@RunWith(RobolectricTestRunner::class)+class MaDevViewModelTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val host = FakeGitHost()++ @BeforeTest fun setUp() {+ PairingStore(app).clear()+ }++ private fun vm(): MaDevViewModel {+ val viewModel = MaDevViewModel(app)+ viewModel.repo = GitHostRepository(host.fetcher)+ return viewModel+ }++ private fun await(desc: String, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 15_000+ while (System.currentTimeMillis() < deadline) {+ Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ if (cond()) return+ Thread.sleep(25)+ }+ assertTrue(cond(), "timed out: $desc")+ }++ @Test fun refreshLoadsHomeStateAndSkipsWhenLoaded() {+ val viewModel = vm()+ viewModel.refresh()+ await("home loaded") { viewModel.state.repos.size == 2 && viewModel.state.tests != null }+ assertEquals(false, viewModel.state.loading)+ assertNull(viewModel.state.error)+ assertEquals("Modern-Apps", viewModel.state.repos[0].name)+ assertEquals("passed", viewModel.state.tests?.latest?.status)+ assertEquals(50.0, viewModel.state.tests?.coveragePct ?: 0.0, 0.01)+ assertEquals("Bug one", viewModel.state.issues.single().title)+ assertEquals("Add thing", viewModel.state.prs.single().title)+ val requestCount = synchronized(host.requested) { host.requested.size }+ viewModel.loadHome()+ // loadHome is a no-op once repos are present (and starts no reload).+ assertEquals(requestCount, synchronized(host.requested) { host.requested.size })+ assertEquals("Modern-Apps", viewModel.repoByName("Modern-Apps")?.name)+ assertNull(viewModel.repoByName("nope"))+ }++ @Test fun refreshSurfacesHostFailureAsError() {+ host.failWith = IOException("HTTP 404 for https://git.maproj.org/api/repos")+ val viewModel = vm()+ viewModel.refresh()+ await("error shown") { viewModel.state.error != null }+ assertTrue(viewModel.state.error!!.contains("404"), viewModel.state.error!!)+ assertFalse(viewModel.state.loading)+ }++ @Test fun catalogLoadsFromFdroidIndex() {+ val viewModel = vm()+ viewModel.loadCatalog()+ await("catalog loaded") { viewModel.state.catalog.isNotEmpty() }+ val entry = viewModel.state.catalog.single()+ assertEquals("Example", entry.name)+ assertEquals("com.example.app", entry.packageName)+ assertEquals(1L, entry.versionCode)+ }++ @Test fun repoBrowsingBranchSwitchAndCommitPaging() {+ val viewModel = vm()+ viewModel.loadRepo("Modern-Apps")+ await("browser open") { viewModel.browser("Modern-Apps") != null }+ val browser = viewModel.browser("Modern-Apps")!!+ assertEquals("main", browser.branch)+ assertEquals(listOf("main", "dev"), browser.branches.map { it.name })+ assertEquals("recent work", browser.commits.single().subject)++ // A fresh first page replaces the recent-commits preview.+ viewModel.loadCommits("Modern-Apps", loadMore = false)+ await("first page") { viewModel.browser("Modern-Apps")!!.commits.size == 30 }+ assertFalse(viewModel.browser("Modern-Apps")!!.commitsExhausted)++ viewModel.loadCommits("Modern-Apps", loadMore = true)+ await("second page appended") { viewModel.browser("Modern-Apps")!!.commits.size == 32 }+ assertTrue(viewModel.browser("Modern-Apps")!!.commitsExhausted)+ // No further page is fetched once exhausted.+ val commitsRequests = synchronized(host.requested) { host.requested.count { it.contains("/commits") } }+ viewModel.loadCommits("Modern-Apps", loadMore = true)+ Thread.sleep(300)+ assertEquals(commitsRequests, synchronized(host.requested) { host.requested.count { it.contains("/commits") } })++ // Branch switch resets path/commits and reloads on the new branch.+ viewModel.selectBranch("Modern-Apps", "dev")+ assertEquals("dev", viewModel.browser("Modern-Apps")!!.branch)+ assertEquals("", viewModel.browser("Modern-Apps")!!.path)++ // Tree navigation is pure state.+ viewModel.navigateTree("Modern-Apps", "src")+ assertEquals("src", viewModel.browser("Modern-Apps")!!.path)+ assertEquals(listOf("src" to "src"), viewModel.browser("Modern-Apps")!!.breadcrumbs)+ viewModel.navigateTree("Modern-Apps", "")+ assertEquals("", viewModel.browser("Modern-Apps")!!.path)++ // Reopening an already-open repo does not refetch its detail.+ val detailRequests = synchronized(host.requested) {+ host.requested.count { it.endsWith("/api/repos/Modern-Apps") }+ }+ viewModel.loadRepo("Modern-Apps")+ assertEquals(detailRequests, synchronized(host.requested) {+ host.requested.count { it.endsWith("/api/repos/Modern-Apps") }+ })++ // Unknown repos have no browser and ignore navigation calls.+ assertNull(viewModel.browser("nope"))+ viewModel.selectBranch("nope", "dev")+ viewModel.navigateTree("nope", "src")+ viewModel.loadCommits("nope", loadMore = false)+ }++ @Test fun repoLoadFailureSetsRepoError() {+ host.failWith = IOException("HTTP 404 for repo")+ val viewModel = vm()+ viewModel.loadRepo("Modern-Apps")+ await("repo error") { viewModel.state.repoError != null }+ assertTrue(viewModel.state.repoError!!.contains("404"))+ assertNull(viewModel.browser("Modern-Apps"))+ }++ @Test fun treeAndFileReadsGoThroughRepositoryCaches() = kotlinx.coroutines.test.runTest {+ val viewModel = vm()+ val entries = viewModel.tree("Modern-Apps", "main", "")+ assertEquals(listOf("src", "README.md"), entries.map { it.name })+ val requestsAfterTree = synchronized(host.requested) { host.requested.size }+ viewModel.tree("Modern-Apps", "main", "")+ assertEquals(requestsAfterTree, synchronized(host.requested) { host.requested.size }, "tree reads are cached")+ val file = viewModel.file("Modern-Apps", "main", "src/Main.kt")+ assertTrue(file.content!!.contains("fun main()"))+ viewModel.file("Modern-Apps", "main", "src/Main.kt")+ assertEquals(requestsAfterTree + 1, synchronized(host.requested) { host.requested.size }, "file reads are cached")+ }++ @Test fun shaHelperMatchesMessageDigest() {+ val viewModel = vm()+ val bytes = "hello world".toByteArray()+ val expected = MessageDigest.getInstance("SHA-256").digest(bytes)+ .joinToString("") { "%02x".format(it) }+ assertEquals(expected, viewModel.shaOf(bytes))+ assertFalse(viewModel.canInstall(), "host JVM never holds the install permission")+ }++ @Test fun pairingStoreCodeIsStableAndPairingPersists() {+ val store = PairingStore(app)+ val code = store.pairingCode()+ assertEquals(6, code.length)+ assertEquals(code, store.pairingCode(), "the code is generated once and kept")+ assertNull(store.token())+ assertFalse(MaDevViewModel(app).state.paired)+ store.savePaired("token-1", "device-9")+ assertEquals("token-1", store.token())+ assertEquals("device-9", store.deviceId())+ assertTrue(MaDevViewModel(app).state.paired)+ store.clear()+ assertNull(store.token())+ }+}++/** The back stack is saved through the Route serializer; every destination must round-trip. */+class MaDevRouteTest {+ @Test fun everyRouteRoundTrips() {+ val json = kotlinx.serialization.json.Json+ val routes: List<com.vayunmathur.madeveloper.Route> = listOf(+ com.vayunmathur.madeveloper.Route.Home,+ com.vayunmathur.madeveloper.Route.Repo("Modern-Apps"),+ com.vayunmathur.madeveloper.Route.Commits("Modern-Apps", "main"),+ com.vayunmathur.madeveloper.Route.Commit("Modern-Apps", "main", "abc123"),+ com.vayunmathur.madeveloper.Route.File("Modern-Apps", "src/Main.kt", "dev"),+ com.vayunmathur.madeveloper.Route.Tests,+ com.vayunmathur.madeveloper.Route.Catalog,+ com.vayunmathur.madeveloper.Route.Push,+ )+ for (route in routes) {+ val encoded = json.encodeToString(com.vayunmathur.madeveloper.Route.serializer(), route)+ assertEquals(route, json.decodeFromString(com.vayunmathur.madeveloper.Route.serializer(), encoded), encoded)+ }+ }+}
madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.ktnew file mode 100644index 0000000000..a3660475ef--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.kt@@ -0,0 +1,265 @@+package com.vayunmathur.madeveloper.ui++import android.app.Application+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.performClick+import androidx.compose.ui.test.performScrollToNode+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.madeveloper.data.GitHostRepository+import com.vayunmathur.madeveloper.domain.CatalogApp+import com.vayunmathur.madeveloper.domain.InstallPhase+import com.vayunmathur.madeveloper.domain.PendingInstall+import com.vayunmathur.madeveloper.domain.TestRun+import com.vayunmathur.madeveloper.domain.TestsStatus+import com.vayunmathur.madeveloper.platform.FakeGitHost+import com.vayunmathur.madeveloper.platform.MaDevUiState+import com.vayunmathur.madeveloper.platform.MaDevViewModel+import com.vayunmathur.madeveloper.platform.PairingStore+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Every MADeveloper screen rendered for real: the state-driven screens+ * over hand-built state, and the ViewModel-driven repo/commits/commit/+ * file screens over the fake git host, exercising buttons, the branch+ * selector, the file filter and the tree navigation.+ */+@RunWith(RobolectricTestRunner::class)+class MaDevScreensTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val host = FakeGitHost()++ @BeforeTest fun setUp() {+ PairingStore(app).clear()+ }++ private fun vm(): MaDevViewModel {+ val viewModel = MaDevViewModel(app)+ viewModel.repo = GitHostRepository(host.fetcher)+ return viewModel+ }++ private fun await(desc: String, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 15_000+ while (System.currentTimeMillis() < deadline) {+ Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ rule.waitForIdle()+ if (runCatching { cond() }.getOrDefault(false)) return+ Thread.sleep(25)+ }+ assertTrue(cond(), "timed out: $desc")+ }++ private fun awaitText(text: String, substring: Boolean = false) {+ await("text '$text'") {+ rule.onAllNodesWithText(text, substring = substring).fetchSemanticsNodes().isNotEmpty()+ }+ }++ private fun clickButton(text: String) {+ rule.onNode(androidx.compose.ui.test.hasScrollAction())+ .performScrollToNode(androidx.compose.ui.test.hasText(text))+ rule.onAllNodesWithText(text, useUnmergedTree = true)[0].performClick()+ }++ private fun state() = MaDevUiState(+ pairingCode = "ABC234",+ tests = TestsStatus(+ latest = TestRun("a", "abc123", "fix thing", "passed", 2, 10, null),+ running = TestRun("r", "fff000", "running now", "running", 0, 0, null),+ history = listOf(TestRun("b", "def456", "old run", "failed", 1, 5, null)),+ coveragePct = 50.0,+ ),+ repos = listOf(+ com.vayunmathur.madeveloper.domain.GitRepo("Modern-Apps", "main", "aabbccdd11223344", "top subject", "2026-11-16"),+ com.vayunmathur.madeveloper.domain.GitRepo("MAOS", "main", "1111222233334444", "maos subject", "2026-11-15"),+ ),+ catalog = listOf(+ CatalogApp("com.example.app", "Example", "Demo app", "1.0", 1L, 2048L, "/a_1.apk"),+ ),+ )++ @Test fun homeShowsCiReposAndFiresNavigation() {+ var openedRepo: String? = null+ var testsOpened = 0+ var catalogOpened = 0+ var pushOpened = 0+ var refreshes = 0+ rule.setContent {+ HomeScreen(+ state(),+ onRefresh = { refreshes++ },+ onOpenRepo = { openedRepo = it },+ onOpenTests = { testsOpened++ },+ onOpenCatalog = { catalogOpened++ },+ onOpenPush = { pushOpened++ },+ )+ }+ rule.onNodeWithText("MA Developer").assertIsDisplayed()+ rule.onNodeWithText("Push socket offline").assertIsDisplayed()+ rule.onNodeWithText("Pairing code: ABC234").assertIsDisplayed()+ rule.onNodeWithText("CI: passed").assertIsDisplayed()+ rule.onNodeWithText("Coverage 50.0%").assertIsDisplayed()+ rule.onNode(androidx.compose.ui.test.hasScrollAction())+ .performScrollToNode(androidx.compose.ui.test.hasText("Open Modern-Apps"))+ clickButton("Pushed installs")+ clickButton("Test history")+ clickButton("Available builds (read-only catalog)")+ clickButton("Refresh")+ clickButton("Open Modern-Apps")+ assertEquals("Modern-Apps", openedRepo)+ assertEquals(1, testsOpened)+ assertEquals(1, catalogOpened)+ assertEquals(1, pushOpened)+ assertEquals(1, refreshes)+ }++ @Test fun homeLoadingAndErrorStatesRender() {+ rule.setContent {+ HomeScreen(+ MaDevUiState(loading = true, error = "HTTP 404 for repos"),+ {}, {}, {}, {}, {},+ )+ }+ rule.onNodeWithText("HTTP 404 for repos").assertIsDisplayed()+ }++ @Test fun testsAndCatalogScreensListTheirRows() {+ var page by androidx.compose.runtime.mutableStateOf(0)+ rule.setContent {+ when (page) {+ 0 -> TestsScreen(state()) {}+ 1 -> CatalogScreen(state()) {}+ 2 -> TestsScreen(MaDevUiState()) {}+ else -> CatalogScreen(MaDevUiState()) {}+ }+ }+ rule.onNodeWithText("Running: running now").assertIsDisplayed()+ rule.onNodeWithText("old run").assertIsDisplayed()+ rule.runOnIdle { page = 1 }+ rule.onNodeWithText("Example").assertIsDisplayed()+ rule.onNodeWithText("com.example.app · 1.0 (1) · 2 KB", substring = true).assertIsDisplayed()+ rule.runOnIdle { page = 2 }+ rule.onNodeWithText("No CI data loaded yet.").assertIsDisplayed()+ rule.runOnIdle { page = 3 }+ rule.onNodeWithText("No catalog loaded yet.").assertIsDisplayed()+ }++ @Test fun pushScreenShowsPairingPendingAndReadyInstall() {+ var installed: String? = null+ val pending = listOf(+ PendingInstall("com.example.ready", 7L, "https://x/a.apk", "sha", 10L, InstallPhase.READY, 1f),+ PendingInstall("com.example.busy", 7L, "https://x/b.apk", "sha", 10L, InstallPhase.DOWNLOADING, 0.5f),+ PendingInstall("com.example.bad", 7L, "https://x/c.apk", "sha", 10L, InstallPhase.FAILED, 0f, "hash mismatch"),+ )+ rule.setContent {+ PushScreen(MaDevUiState(pairingCode = "XYZ789", pending = pending), onInstall = { installed = it }, onBack = {})+ }+ rule.onNodeWithText("Pairing code: XYZ789").assertIsDisplayed()+ rule.onNodeWithText("Socket offline; reconnecting with backoff").assertIsDisplayed()+ rule.onNodeWithText("com.example.ready").assertIsDisplayed()+ // Only the READY push gets an Install button.+ assertEquals(1, rule.onAllNodesWithText("Install").fetchSemanticsNodes().size)+ clickButton("Install")+ assertEquals("com.example.ready", installed)+ }++ @Test fun pushScreenPairedAndEmpty() {+ rule.setContent { PushScreen(MaDevUiState(connected = true, paired = true), onInstall = {}) {} }+ rule.onNodeWithText("Paired").assertIsDisplayed()+ rule.onNodeWithText("Socket connected to api.maproj.org").assertIsDisplayed()+ rule.onNodeWithText("No pushed installs yet. Installs always need your tap; nothing installs silently.")+ .assertIsDisplayed()+ }++ @Test fun repoScreenBrowsesTreeFilterAndCommits() {+ val viewModel = vm()+ var openedFile: Pair<String, String>? = null+ var openedCommits: String? = null+ var openedCommit: Pair<String, String>? = null+ rule.setContent {+ RepoScreen(+ "Modern-Apps", viewModel,+ onOpenFile = { branch, path -> openedFile = branch to path },+ onOpenCommits = { openedCommits = it },+ onOpenCommit = { branch, sha -> openedCommit = branch to sha },+ ) {}+ }+ await("repo loaded") { viewModel.browser("Modern-Apps") != null }+ rule.onNodeWithText("Clone: https://git.maproj.org/Modern-Apps.git").assertIsDisplayed()+ rule.onNodeWithText("Recent commits").assertIsDisplayed()+ rule.onNodeWithText("recent work").assertIsDisplayed()+ rule.onNode(androidx.compose.ui.test.hasScrollAction())+ .performScrollToNode(androidx.compose.ui.test.hasText("src"))+ rule.onNodeWithText("src").assertIsDisplayed()+ // Descend into the folder, then read the file inside it.+ rule.onNode(androidx.compose.ui.test.hasScrollAction())+ .performScrollToNode(androidx.compose.ui.test.hasText("Open folder"))+ clickButton("Open folder")+ await("descended") { viewModel.browser("Modern-Apps")!!.path == "src" }+ rule.onNodeWithText("Main.kt").assertIsDisplayed()+ clickButton("Root")+ await("back at root") { viewModel.browser("Modern-Apps")!!.path == "" }+ // The file filter narrows the tree listing.+ rule.onNodeWithText("Filter files").performTextInput("read")+ rule.waitForIdle()+ assertEquals(0, rule.onAllNodesWithText("src").fetchSemanticsNodes().size)+ rule.onNodeWithText("README.md").assertIsDisplayed()+ // Commit + commits navigation callbacks fire.+ clickButton("View commit")+ assertEquals("main", openedCommit!!.first)+ clickButton("All commits")+ assertEquals("main", openedCommits)+ assertEquals(null, openedFile)+ }++ @Test fun commitsCommitAndFileScreensRenderLoadedData() {+ val viewModel = vm()+ var openedCommit: String? = null+ var page by androidx.compose.runtime.mutableStateOf(0)+ rule.setContent {+ when (page) {+ 0 -> CommitsScreen("Modern-Apps", "main", viewModel, onOpenCommit = { openedCommit = it }) {}+ 1 -> CommitScreen("Modern-Apps", "recent0001aaaa", viewModel) {}+ 2 -> FileScreen("Modern-Apps", "src/Main.kt", "main", viewModel) {}+ 3 -> FileScreen("Modern-Apps", "src/logo.png", "main", viewModel) {}+ else -> CommitScreen("Modern-Apps", "missing0000", viewModel) {}+ }+ }+ await("commits loaded") { viewModel.browser("Modern-Apps")?.commits?.isNotEmpty() == true }+ rule.onNodeWithText("recent work").assertIsDisplayed()+ clickButton("View commit")+ assertEquals("recent0001aaaa", openedCommit)++ rule.runOnIdle { page = 1 }+ rule.onNodeWithText("recent work").assertIsDisplayed()+ rule.onNodeWithText("Author: vayun").assertIsDisplayed()+ rule.onNodeWithText("SHA: recent0001aaaa").assertIsDisplayed()+ rule.onNodeWithText("notes").assertIsDisplayed()++ rule.runOnIdle { page = 2 }+ awaitText("println(1)", substring = true)+ rule.runOnIdle { page = 3 }+ awaitText("Binary file", substring = true)++ // A commit outside the loaded pages says so instead of inventing data.+ rule.runOnIdle { page = 4 }+ rule.onNodeWithText("Commit not in the loaded pages. Open the commits list and load more, or view it on the git host.")+ .assertIsDisplayed()+ }+}