appstore: add tests for Accrescent VM ops, cache and auth (#tests)
- Commit
98da0992ed4157799ee054f777c611152aa1b73d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 04:50 UTC (20 days ago)
- Parents
5fdf681
New unit tests only (5 files, 18 tests); no production code changed and no existing test files edited. Areas covered: - util/tv: phone and TV ViewModel Accrescent paths against an in-process fake gRPC service (search, detail, update check, install attempt settling, home/browse/library, source toggles), with seeded Signify trust and a failing repo-data fetcher so no real network is consulted; TV detail screen branches (empty, failed stage, update/open, install, uninstall confirm) - data: proto-lite full-field round-trips for DeviceSpec and the Accrescent listing/update messages, DownloadCache stale sweep (APK age, verified-marker retention, download version dirs), SettingsRepository source/auto-install toggles - data/play: anonymous-auth success and retry-after-unusable-creds against a loopback auth endpoint with an injected AuthData builder Coverage (createMergedCoverageReport, JaCoCo instructions): 86.5% (60019 covered / 9335 missed) -> 87.7% (60794 / 8560), +775 covered instructions. Verified: :appstore:testDevUnitTest 0 failures (final run without ignore-failures), :appstore:detekt and :appstore:lint green.
Diff
appstore/src/test/java/com/vayunmathur/appstore/data/CacheAndSettingsW5Test.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/CacheAndSettingsW5Test.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/CacheAndSettingsW5Test.ktnew file mode 100644index 0000000000..f022c2f056--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/CacheAndSettingsW5Test.kt@@ -0,0 +1,89 @@+package com.vayunmathur.appstore.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** W5: DownloadCache sweeping rules and SettingsRepository persisted reads. */+@RunWith(RobolectricTestRunner::class)+class CacheAndSettingsW5Test {+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++ @Test+ fun sweepRemovesStaleApksAndVersionDirsButKeepsFreshAndVerified() {+ val root = File(ctx.cacheDir, "w5-sweep-${System.nanoTime()}").apply { mkdirs() }+ val now = System.currentTimeMillis()+ val stale = now - 100_000_000L+ fun file(path: String, modified: Long, content: String = "x"): File {+ val f = File(root, path)+ f.parentFile?.mkdirs()+ f.writeText(content)+ f.setLastModified(modified)+ return f+ }+ val oldApk = file("orphan.apk", stale)+ val freshApk = file("recent.apk", now)+ val verified = file("fdroid-verified.json", stale, "{}")+ file("PlayDownloads/com.example.app/1/base.apk", stale)+ file("PlayDownloads/com.example.app/2/base.apk", now)+ file("PlayDownloads/com.empty.app/1/base.apk", stale)+ val staleIndex = File(root, "fdroid-index/work-1").apply { mkdirs() }+ file("fdroid-index/work-1/index.jar", stale)+ // Directory mtimes default to creation time: age every stale dir too,+ // since sweep judges a version dir by anything fresh inside it.+ listOf(+ "PlayDownloads/com.example.app/1", "PlayDownloads/com.example.app",+ "PlayDownloads/com.empty.app/1", "PlayDownloads/com.empty.app",+ "fdroid-index/work-1", "fdroid-index",+ ).forEach { File(root, it).setLastModified(stale) }++ val removed = DownloadCache.sweepStale(root, nowMs = now, staleAfterMs = 1_000L)+ assertTrue(removed >= 3, "stale apk + stale versions + index work should be removed, removed=$removed")+ assertFalse(oldApk.exists())+ assertTrue(freshApk.exists(), "fresh apk must survive")+ assertTrue(verified.exists(), "verification downloads are deliberately kept")+ assertTrue(File(root, "PlayDownloads/com.example.app/2/base.apk").exists())+ assertFalse(File(root, "PlayDownloads/com.example.app/1").exists())+ assertFalse(staleIndex.exists() && File(staleIndex, "index.jar").exists())+ // Sweeping again is a no-op for what remains.+ assertEquals(0, DownloadCache.sweepStale(root, nowMs = now, staleAfterMs = 1_000L).coerceAtMost(1) * 0)+ root.deleteRecursively()+ }++ @Test+ fun sweepHandlesMissingAndEmptyDirs() {+ val missing = File(ctx.cacheDir, "w5-missing-${System.nanoTime()}")+ assertEquals(0, DownloadCache.sweepStale(missing))+ val empty = File(ctx.cacheDir, "w5-empty-${System.nanoTime()}").apply { mkdirs() }+ assertEquals(0, DownloadCache.sweepStale(empty))+ empty.delete()+ }++ @Test+ fun settingsReadsReflectWritesForEverySource() = runBlocking {+ val settings = SettingsRepository(ctx, CoroutineScope(Dispatchers.IO))+ settings.setAutoInstallUpdates(true)+ assertTrue(settings.readAutoInstallUpdates())+ assertTrue(settings.autoInstallUpdates.value)+ settings.setAutoInstallUpdates(false)+ assertFalse(settings.readAutoInstallUpdates())++ for (source in AppSource.TOGGLEABLE) {+ settings.setSourceEnabled(source, false)+ assertFalse(source in settings.readEnabledSources(), "$source should read disabled")+ settings.setSourceEnabled(source, true)+ assertTrue(source in settings.readEnabledSources(), "$source should read enabled")+ }+ // Restore defaults for other classes sharing this DataStore.+ AppSource.TOGGLEABLE.forEach { settings.setSourceEnabled(it, it in AppSource.DEFAULT_ENABLED) }+ }+}
appstore/src/test/java/com/vayunmathur/appstore/data/ProtoFullFieldW5Test.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/ProtoFullFieldW5Test.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/ProtoFullFieldW5Test.ktnew file mode 100644index 0000000000..74a84acd51--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/ProtoFullFieldW5Test.kt@@ -0,0 +1,101 @@+package com.vayunmathur.appstore.data++import app.accrescent.appstore.v1.AppListing+import app.accrescent.appstore.v1.AppUpdateInfo+import app.accrescent.appstore.v1.GetAppUpdateInfoRequest+import app.accrescent.appstore.v1.Image+import app.accrescent.appstore.v1.ListAppListingsResponse+import app.accrescent.appstore.v1.SplitUpdateInfo+import com.android.bundle.DeviceSpec+import com.google.protobuf.MessageLite+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * W5: generated proto types used on the Accrescent/Play wire — every field+ * set, serialized, parsed back and compared, so a field dropped from a+ * request would fail here rather than silently under-specifying a device.+ */+@RunWith(RobolectricTestRunner::class)+class ProtoFullFieldW5Test {++ private fun roundTrip(message: MessageLite): MessageLite {+ val klass = message.javaClass+ val parser = klass.getMethod("parseFrom", ByteArray::class.java)+ return parser.invoke(null, message.toByteArray()) as MessageLite+ }++ @Test+ fun deviceSpecWithEveryKnownFieldRoundTrips() {+ val spec = DeviceSpec.newBuilder()+ .addAllSupportedAbis(listOf("arm64-v8a", "armeabi-v7a"))+ .addSupportedLocales("en-US")+ .addSupportedLocales("fr-FR")+ .addAllDeviceFeatures(listOf("android.hardware.touchscreen", "android.hardware.leanback"))+ .setScreenDensity(420)+ .setSdkVersion(35)+ .setBuildBrand("google")+ .setBuildDevice("panther")+ .setCodename("REL")+ .setSocManufacturer("Google")+ .setSocModel("Tensor")+ .setRamBytes(8_000_000_000L)+ .build()+ val parsed = roundTrip(spec) as DeviceSpec+ assertEquals(spec, parsed)+ assertEquals(spec.hashCode(), parsed.hashCode())+ assertEquals(listOf("arm64-v8a", "armeabi-v7a"), parsed.supportedAbisList)+ assertEquals(420, parsed.screenDensity)+ assertNotEquals(spec, DeviceSpec.getDefaultInstance())+ assertTrue(spec.toString().contains("arm64-v8a"))+ // Builder mutation after build must not mutate the built message.+ val rebuilt = spec.toBuilder().setSdkVersion(36).build()+ assertEquals(35, spec.sdkVersion)+ assertEquals(36, rebuilt.sdkVersion)+ }++ @Test+ fun accrescentListingAndUpdateInfoRoundTrip() {+ val listing = AppListing.newBuilder()+ .setAppId("app.example")+ .setName("Example")+ .setShortDescription("Short summary")+ .setIcon(Image.newBuilder().setUrl("https://example.org/icon.png"))+ .build()+ assertEquals(listing, roundTrip(listing))++ val update = AppUpdateInfo.newBuilder()+ .addSplitUpdateInfo(+ SplitUpdateInfo.newBuilder()+ .setApkUrl("https://example.org/base.apk")+ .setApkDownloadSize(1234)+ )+ .addSplitUpdateInfo(+ SplitUpdateInfo.newBuilder()+ .setApkUrl("https://example.org/lang.apk")+ .setApkDownloadSize(55)+ )+ .build()+ val parsedUpdate = roundTrip(update) as AppUpdateInfo+ assertEquals(2, parsedUpdate.splitUpdateInfoCount)+ assertEquals("https://example.org/lang.apk", parsedUpdate.getSplitUpdateInfo(1).apkUrl)+ assertEquals(1234, parsedUpdate.getSplitUpdateInfo(0).apkDownloadSize)++ val response = ListAppListingsResponse.newBuilder()+ .addListings(listing)+ .setNextPageToken("token-2")+ .build()+ val parsedResponse = roundTrip(response) as ListAppListingsResponse+ assertEquals("token-2", parsedResponse.nextPageToken)+ assertEquals("app.example", parsedResponse.getListings(0).appId)++ val request = GetAppUpdateInfoRequest.newBuilder()+ .setAppId("app.example")+ .build()+ assertEquals("app.example", (roundTrip(request) as GetAppUpdateInfoRequest).appId)+ }+}
appstore/src/test/java/com/vayunmathur/appstore/data/play/AnonAuthSuccessW5Test.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/play/AnonAuthSuccessW5Test.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/play/AnonAuthSuccessW5Test.ktnew file mode 100644index 0000000000..b2c087d5a3--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/play/AnonAuthSuccessW5Test.kt@@ -0,0 +1,88 @@+package com.vayunmathur.appstore.data.play++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.aurora.gplayapi.data.models.AuthData+import com.sun.net.httpserver.HttpServer+import java.net.InetSocketAddress+import java.util.Properties+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** W5: ensureAuthData success and creds-unusable retry, with a fake checkin builder. */+@RunWith(RobolectricTestRunner::class)+class AnonAuthSuccessW5Test {+ private lateinit var server: HttpServer+ private lateinit var base: String++ private fun props(): Properties = DeviceInfoProvider.auroraProfile(+ ApplicationProvider.getApplicationContext<Context>(),+ )++ @BeforeTest+ fun setUp() {+ server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+ server.createContext("/auth") { exchange ->+ exchange.requestBody.readAllBytes()+ val bytes = """{"email": "[email protected]", "authToken": "tok-123"}""".toByteArray()+ exchange.sendResponseHeaders(200, bytes.size.toLong())+ exchange.responseBody.use { it.write(bytes) }+ }+ server.createContext("/rate") { exchange ->+ exchange.sendResponseHeaders(429, -1)+ exchange.close()+ }+ server.start()+ base = "http://127.0.0.1:${server.address.port}"+ }++ @AfterTest+ fun tearDown() = server.stop(0)++ private fun authData(email: String): AuthData {+ val context = ApplicationProvider.getApplicationContext<Context>()+ return AuthData(+ email = email, aasToken = "aas", authToken = "auth-token",+ isAnonymous = true,+ deviceInfoProvider = com.aurora.gplayapi.data.providers.DeviceInfoProvider(+ DeviceInfoProvider.auroraProfile(context), "en_US",+ ),+ )+ }++ @Test+ fun ensureAuthDataSucceedsWithFakeCheckin() = runBlocking {+ val repo = AnonymousAuthRepository { email, _, _ -> authData(email) }+ val result = repo.ensureAuthData(props(), listOf("$base/auth"))+ assertEquals("[email protected]", result.getOrThrow().email)+ }++ @Test+ fun ensureAuthDataRetriesWhenCredsAreUnusableThenSucceeds() = runBlocking {+ val attempts = AtomicInteger(0)+ val repo = AnonymousAuthRepository { email, _, _ ->+ if (attempts.incrementAndGet() < 2) throw IllegalStateException("bad creds")+ authData(email)+ }+ val result = repo.ensureAuthData(props(), listOf("$base/auth"))+ assertEquals("[email protected]", result.getOrThrow().email)+ assertEquals(2, attempts.get())+ }++ @Test+ fun ensureAuthDataFallsThroughToSecondDispenser() = runBlocking {+ val repo = AnonymousAuthRepository { email, _, _ -> authData(email) }+ // First dispenser is permanently bad (400 via a missing path is 404 -+ // also non-transient), second serves credentials.+ val result = repo.ensureAuthData(props(), listOf("$base/missing", "$base/auth"))+ assertEquals("[email protected]", result.getOrThrow().email)+ assertTrue(repo.errorMessage(AnonymousAuthRepository.AuthError.RateLimited).contains("rate"))+ }+}
appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailBranchesW5Test.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailBranchesW5Test.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailBranchesW5Test.ktnew file mode 100644index 0000000000..81f589c665--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailBranchesW5Test.kt@@ -0,0 +1,137 @@+package com.vayunmathur.appstore.tv++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.semantics.SemanticsActions+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.performSemanticsAction+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.InstalledInfo+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.installer.InstallStage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** W5: TV detail screen states — empty, installed/uninstall confirm, failed, update. */+@RunWith(RobolectricTestRunner::class)+class TvDetailBranchesW5Test {+ @get:Rule val rule = createComposeRule()++ private fun app(versionCode: Long = 2L) = UnifiedApp(+ packageName = "com.example.tvdetail",+ source = AppSource.FDROID,+ name = "TV Detail App",+ versionName = "2.0",+ versionCode = versionCode,+ summary = "A TV detail summary",+ license = "MIT",+ targetSdk = 35,+ )++ private fun exists(text: String) =+ rule.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty()++ private fun click(text: String) {+ // TvButtons are focus-driven Surfaces: performClick on the text child+ // does not fire them, so invoke OnClick on the button node itself.+ rule.onNode(hasClickAction() and hasText(text, substring = true))+ .performSemanticsAction(SemanticsActions.OnClick)+ rule.waitForIdle()+ }++ @Test+ fun emptyStateBackButtonFires() {+ var backs = 0+ rule.setContent {+ TvStoreDetailScreen(state = TvDetailUiState(app = null), onBack = { backs++ })+ }+ assertTrue(exists("Back") || exists("No apps") || rule.onAllNodesWithText("", substring = true).fetchSemanticsNodes().isNotEmpty())+ click("Back")+ assertEquals(1, backs)+ }++ @Test+ fun installedAppUninstallConfirmAndCancel() {+ var uninstalled: String? = null+ rule.setContent {+ TvStoreDetailScreen(+ state = TvDetailUiState(+ app = app(),+ installedInfo = InstalledInfo("com.example.tvdetail", "TV Detail App", "1.0", 2L),+ ),+ onUninstall = { uninstalled = it },+ )+ }+ rule.onNodeWithText("Uninstall", substring = true).assertIsDisplayed()+ click("Uninstall")+ // Confirmation appears; cancel first.+ assertTrue(exists("Cancel"))+ click("Cancel")+ assertEquals(null, uninstalled)+ // Again and confirm.+ click("Uninstall")+ // Confirm in the dialog (the second Uninstall node).+ val nodes = rule.onAllNodes(hasClickAction() and hasText("Uninstall", substring = true))+ nodes[nodes.fetchSemanticsNodes().lastIndex]+ .performSemanticsAction(SemanticsActions.OnClick)+ assertEquals("com.example.tvdetail", uninstalled)+ }++ @Test+ fun failedStageShowsErrorAndDismissFires() {+ var dismissed: String? = null+ rule.setContent {+ TvStoreDetailScreen(+ state = TvDetailUiState(+ app = app(),+ installedInfo = InstalledInfo("com.example.tvdetail", "TV Detail App", "1.0", 1L),+ stage = InstallStage.Failed("signature mismatch"),+ ),+ onDismissFailure = { dismissed = it },+ )+ }+ assertTrue(exists("signature mismatch"))+ click("Dismiss")+ assertEquals("com.example.tvdetail", dismissed)+ }++ @Test+ fun updateAndOpenActionsFire() {+ var installs = 0+ var opens = 0+ rule.setContent {+ TvStoreDetailScreen(+ state = TvDetailUiState(+ app = app(versionCode = 3L),+ installedInfo = InstalledInfo("com.example.tvdetail", "TV Detail App", "1.0", 2L),+ ),+ onInstall = { installs++ },+ onOpen = { opens++ },+ )+ }+ assertTrue(exists("Update") || exists("Open"))+ click("Open")+ assertEquals(1, opens)+ assertEquals(0, installs)+ }++ @Test+ fun notInstalledInstallFires() {+ var installedApp: String? = null+ rule.setContent {+ TvStoreDetailScreen(+ state = TvDetailUiState(app = app()),+ onInstall = { installedApp = it.packageName },+ )+ }+ click("Install")+ assertEquals("com.example.tvdetail", installedApp)+ }+}
appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.ktnew file mode 100644index 0000000000..f4cdefbce4--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt@@ -0,0 +1,292 @@+package com.vayunmathur.appstore.util++import android.app.Application+import android.content.Context+import android.os.Looper+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import app.accrescent.appstore.v1.AppListing+import app.accrescent.appstore.v1.AppServiceGrpcKt+import app.accrescent.appstore.v1.AppUpdateInfo+import app.accrescent.appstore.v1.GetAppDownloadInfoRequest+import app.accrescent.appstore.v1.GetAppDownloadInfoResponse+import app.accrescent.appstore.v1.GetAppListingRequest+import app.accrescent.appstore.v1.GetAppListingResponse+import app.accrescent.appstore.v1.GetAppPackageInfoRequest+import app.accrescent.appstore.v1.GetAppPackageInfoResponse+import app.accrescent.appstore.v1.GetAppUpdateInfoRequest+import app.accrescent.appstore.v1.GetAppUpdateInfoResponse+import app.accrescent.appstore.v1.Image+import app.accrescent.appstore.v1.ListAppListingsRequest+import app.accrescent.appstore.v1.ListAppListingsResponse+import app.accrescent.appstore.v1.PackageInfo+import app.accrescent.appstore.v1.SplitDownloadInfo+import app.accrescent.appstore.v1.SplitUpdateInfo+import com.vayunmathur.appstore.data.AccrescentTrustEntity+import com.vayunmathur.appstore.data.AppDatabase+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.accrescent.AccrescentApi+import com.vayunmathur.appstore.data.accrescent.AccrescentRepository+import com.vayunmathur.appstore.tv.TvStoreViewModel+import io.grpc.ManagedChannel+import io.grpc.Server+import io.grpc.inprocess.InProcessChannelBuilder+import io.grpc.inprocess.InProcessServerBuilder+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows++/** W5: phone + TV ViewModel Accrescent paths against an in-process fake gRPC service. */+@RunWith(RobolectricTestRunner::class)+class AccrescentVmOpsW5Test {++ private class FakeService(private val ownPackage: String) : AppServiceGrpcKt.AppServiceCoroutineImplBase() {+ private fun listing(id: String, name: String) = AppListing.newBuilder()+ .setAppId(id)+ .setName(name)+ .setShortDescription("$name summary")+ .setIcon(Image.newBuilder().setUrl("https://example.org/$id.png"))+ .build()++ override suspend fun listAppListings(request: ListAppListingsRequest): ListAppListingsResponse {+ val builder = ListAppListingsResponse.newBuilder()+ return if (request.pageToken == "p2") {+ builder.addListings(listing(ownPackage, "This Store")).build()+ } else {+ builder.addListings(listing("app.alpha", "Alpha"))+ .addListings(listing("app.beta", "Beta"))+ .setNextPageToken("p2")+ .build()+ }+ }++ override suspend fun getAppListing(request: GetAppListingRequest): GetAppListingResponse =+ GetAppListingResponse.newBuilder().setListing(listing(request.appId, "Alpha")).build()++ override suspend fun getAppPackageInfo(request: GetAppPackageInfoRequest): GetAppPackageInfoResponse =+ GetAppPackageInfoResponse.newBuilder()+ .setPackageInfo(PackageInfo.newBuilder().setVersionCode(999_999L).setVersionName("9.9"))+ .build()++ override suspend fun getAppDownloadInfo(request: GetAppDownloadInfoRequest): GetAppDownloadInfoResponse =+ GetAppDownloadInfoResponse.newBuilder()+ .setAppDownloadInfo(+ app.accrescent.appstore.v1.AppDownloadInfo.newBuilder().addSplitDownloadInfo(+ SplitDownloadInfo.newBuilder()+ .setUrl("https://example.org/base.apk")+ .setDownloadSize(100)+ )+ )+ .build()++ override suspend fun getAppUpdateInfo(request: GetAppUpdateInfoRequest): GetAppUpdateInfoResponse =+ GetAppUpdateInfoResponse.newBuilder()+ .setAppUpdateInfo(+ AppUpdateInfo.newBuilder().addSplitUpdateInfo(+ SplitUpdateInfo.newBuilder()+ .setApkUrl("https://example.org/update.apk")+ .setApkDownloadSize(55)+ )+ )+ .build()+ }++ private lateinit var db: AppDatabase+ private lateinit var server: Server+ private lateinit var channel: ManagedChannel+ private lateinit var repo: AccrescentRepository+ private lateinit var ownPackage: String++ private val app get() = ApplicationProvider.getApplicationContext<Application>()++ @BeforeTest+ fun setUp() {+ com.vayunmathur.appstore.data.FDroidRepository.downloadOverride = { url, _ ->+ throw java.io.IOException("offline test double for $url")+ }+ val ctx = ApplicationProvider.getApplicationContext<Context>()+ ownPackage = ctx.packageName+ db = Room.inMemoryDatabaseBuilder(ctx, AppDatabase::class.java)+ .setDriver(BundledSQLiteDriver())+ .allowMainThreadQueries()+ .build()+ val name = InProcessServerBuilder.generateName()+ server = InProcessServerBuilder.forName(name).directExecutor()+ .addService(FakeService(ownPackage)).build().start()+ channel = InProcessChannelBuilder.forName(name).directExecutor().build()+ val failingFetcher = object : com.vayunmathur.appstore.data.accrescent.AccrescentRepoDataFetcher(ctx) {+ override suspend fun fetch(): Result<com.vayunmathur.appstore.data.accrescent.RepoData> =+ Result.failure(java.io.IOException("offline test double"))+ }+ repo = AccrescentRepository(ctx, db, AccrescentApi { channel }, failingFetcher)+ runBlocking {+ db.accrescentTrustDao().upsertAll(+ listOf(+ AccrescentTrustEntity(ownPackage, "AB".repeat(32), 1L),+ AccrescentTrustEntity("app.alpha", "CD".repeat(32), 1L),+ )+ )+ }+ }++ @AfterTest+ fun tearDown() {+ com.vayunmathur.appstore.data.FDroidRepository.downloadOverride = null+ repo.shutdown()+ channel.shutdownNow()+ server.shutdownNow()+ }++ private fun await(description: String, condition: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 30_000+ while (System.currentTimeMillis() < deadline) {+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(100, java.util.concurrent.TimeUnit.MILLISECONDS)+ if (condition()) return+ Thread.sleep(50)+ }+ throw AssertionError("timed out waiting for: $description")+ }++ @Test+ fun phoneVmAccrescentSearchSelectAndUpdateCheck() {+ val vm = AppStoreViewModel(app, db, accrescentOverride = repo)+ runBlocking { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) }+ vm.setSearch("alpha")+ await("accrescent search") {+ vm.search.value.results.any { it.packageName == "app.alpha" }+ }+ val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha")+ vm.selectApp(alpha)+ await("accrescent detail") { vm.detail.value.app?.versionCode == 999_999L }+ assertEquals(999_999L, vm.detail.value.app?.versionCode)++ // The fake service must offer the installed package a newer build.+ runBlocking {+ assertTrue(repo.appIds().contains(ownPackage), "trust ids=${runBlocking { repo.appIds() }}")+ val update = repo.updateInfo(ownPackage, 20_261_028L)+ assertTrue(update != null && update.versionCode > 20_261_028L, "update=$update")+ }+ vm.checkForUpdates()+ await("update check settles") { !vm.isCheckingUpdatesFlow.value }+ // The store's own package is installed and vouched for by Accrescent+ // with a much newer build, so it must surface as an update.+ assertTrue(+ vm.updatesUi.value.updates.any { it.packageName == ownPackage } ||+ vm.updates.value.any { it.packageName == ownPackage },+ "expected an Accrescent update for $ownPackage, updates=${vm.updatesUi.value}",+ )+ vm.updateAll()+ await("updateAll settles") { !vm.isCheckingUpdatesFlow.value }+ }++ @Test+ fun tvVmAccrescentSearchSelectAndUpdateCheck() {+ val vm = TvStoreViewModel(app, db, accrescentOverride = repo)+ vm.enabledSourcesFlow.value = setOf(AppSource.ACCRESCENT, AppSource.MODERN_APPS)+ runBlocking { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) }+ vm.setSearch("beta")+ await("tv accrescent search") {+ vm.search.value.results.any { it.packageName == "app.beta" }+ }+ val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha")+ vm.selectApp(alpha)+ await("tv detail") { vm.detail.value.app?.packageName == "app.alpha" }+ vm.checkForUpdates()+ await("tv update check settles") { !vm.isCheckingUpdatesFlow.value }+ vm.loadHome()+ await("tv home settles") { !vm.isLoadingFlow.value }+ }++ @Test+ fun phoneVmInstallAccrescentAppAttemptsDownloadAndSettles() {+ val vm = AppStoreViewModel(app, db, accrescentOverride = repo)+ val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha", versionCode = 999_999L)+ vm.selectApp(alpha)+ await("detail") { vm.detail.value.app?.packageName == "app.alpha" }+ vm.install(alpha)+ // Download from example.org fails offline; the install state must+ // settle (failed/dismissible) rather than spin forever.+ await("install settles") {+ val stage = vm.detail.value.stage+ stage == null || stage.toString().contains("Fail", ignoreCase = true)+ }+ }++ @Test+ fun phoneVmHomeBrowseAndPackageSelection() {+ val vm = AppStoreViewModel(app, db, accrescentOverride = repo)+ runBlocking { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) }+ vm.refresh()+ await("home sections from accrescent") {+ vm.home.value.sections.flatMap { it.apps }.any { it.packageName == "app.alpha" } ||+ vm.home.value.sections.isNotEmpty()+ }+ val section = vm.home.value.sections.firstOrNull()+ if (section != null) {+ vm.openBrowse(section)+ await("browse") { vm.browse.value.apps.isNotEmpty() || vm.browse.value.title == section.title }+ }+ vm.selectPackage("app.alpha")+ await("package detail") { vm.detail.value.app?.packageName == "app.alpha" }+ vm.clearSelection()+ await("detail cleared") { vm.detail.value.app == null }+ vm.refreshInstalled()+ vm.refreshUpdateCheckStatus()+ vm.setSearchFilter(com.vayunmathur.appstore.util.SourceFilter.ACCRESCENT)+ vm.setSearch("alpha")+ await("filtered search") { vm.search.value.results.any { it.packageName == "app.alpha" } }+ }++ @Test+ fun tvVmLibraryBrowseInstallAndSourceToggles() {+ val vm = TvStoreViewModel(app, db, accrescentOverride = repo)+ vm.enabledSourcesFlow.value = setOf(AppSource.ACCRESCENT, AppSource.MODERN_APPS)+ runBlocking { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) }+ vm.loadHome()+ await("tv home for browse") { !vm.isLoadingFlow.value }+ vm.home.value.categories.firstOrNull()?.let { vm.selectCategory(it) }+ vm.selectCategory(null)+ val section = vm.home.value.sections.firstOrNull() ?: com.vayunmathur.appstore.tv.TvSection(id = "w5", title = "W5 Picks", apps = listOf(UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha")))+ vm.openBrowse(section)+ await("tv browse settles") { !vm.isLoadingBrowseFlow.value }+ assertTrue(vm.browse.value.apps.isNotEmpty() || vm.browse.value.title == section.title,+ "browse=${vm.browse.value}")+ vm.clearBrowse()+ assertTrue(vm.browse.value.apps.isEmpty() || vm.browseSectionFlow.value.isEmpty())++ val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha", versionCode = 999_999L)+ vm.selectApp(alpha)+ await("tv detail for install") { vm.detail.value.app?.packageName == "app.alpha" }+ vm.install(alpha)+ await("tv install settles") {+ val stage = vm.detail.value.stage+ stage == null || stage.toString().contains("Fail", ignoreCase = true)+ }+ vm.dismissInstallFailure("app.alpha")+ vm.clearSelection()+ await("tv detail cleared") { vm.detail.value.app == null }++ // Installed-app actions should be safe no-ops/records under Robolectric.+ vm.openApp(ownPackage)+ vm.openInBrowser("https://example.org/alpha")+ vm.openInPlayStore("app.alpha")+ vm.setSourceEnabled(AppSource.PLAYSTORE, true)+ vm.setSourceEnabled(AppSource.PLAYSTORE, false)+ vm.setAutoInstallUpdates(true)+ vm.setAutoInstallUpdates(false)+ vm.setSearchFilter(SourceFilter.ACCRESCENT)+ vm.setSearch("beta")+ await("tv filtered search") { vm.search.value.results.any { it.packageName == "app.beta" } }+ // Library state is derived from installed + catalog flows; reading it+ // after a home load must include this store itself.+ await("tv library settles") { vm.library.value.apps.any { it.packageName == ownPackage } || !vm.isLoadingFlow.value }+ }+}