Modern Apps git

← Modern-Apps.git

weather: add tests for domain, data, UI, widgets, car and device flows

Commit
1f7d728fe009da38ed855a283880ff1429c54a9e
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:18 UTC (29 days ago)
Parents
27d8093
Coverage (merged INSTRUCTION, :weather:createMergedCoverageReport):
6.6% (2432/37108) -> 86.33% (32052/37128), above the 85% target.

Test areas (162 unit tests in 28 classes, all passing, plus 7
instrumented tests passing on the shared emulator):

- domain: unit/Wmo/date-time formatting, metric series extraction for
  every WeatherMetric, resolveConditions for current/hour/day incl.
  vector-mean wind day aggregation and short-list fallbacks, ISO parse
  variants (Robolectric where localized names need ICU).
- data/network: Room DAO in-memory tests (ordering, current-row
  replacement, cache upsert, writeForecastCache air-quality
  preservation), GeoDatabase FTS escaper + prepare/status consistency,
  WeatherRefreshWorker scheduling and retry doWork, DTO serialization
  round-trips, WxBundle mapper edges (bad daily start, missing
  sections), WeatherApi offline failure modes.
- platform: WeatherViewModel against an in-memory FakeRepository
  (selection toggles, CRUD/reorder, cache hydration fresh/stale,
  network-failure error states, GPS far/near fix refresh paths),
  computeDaySummary thresholds, precipitation nowcast slots,
  LocationProvider via Robolectric ShadowLocationManager (permission,
  last-known, simulated one-shot fix), unit-system resolution.
- UI (Robolectric Compose, incl. @GraphicsMode(NATIVE) +
  captureToImage so Canvas draw lambdas execute): all metric blocks,
  hourly/daily cards, summary/selected-header/device-location cards,
  MetricGraphSheet incl. touch selection, HomeScreen/ForecastColumn,
  LocationsScreen incl. long-press delete sheet, MainSearchBar,
  map page + measure selector/legend, WeatherMapState raster/cacheKey/
  indexForIso and the decode effect's cache-hit and cache-miss paths
  (driven via the compose test scheduler), car templates via
  TestCarContext, assistant-intent payload mapping and offline errors.
- widgets: both Glance widgets composed via glance-appwidget-testing,
  snapshot loader degrading to null without a readable cache.
- instrumented (src/androidTest): Berlin places-search journey
  (real GeoDatabase unpack + repository insert), refresh worker and
  car session against the real SQLCipher repository, direct
  WeatherRepository CRUD/cache round-trip with cleanup, and both
  widgets' provideGlance.

Production testability changes (behavior-preserving): WeatherRepository
is now open with an internal constructor and open delegates so tests
can substitute an in-memory fake (the real database needs
AndroidKeyStore, unavailable under Robolectric); WeatherGlanceWidget /
WeatherBlobGlanceWidget are open so tests can expose their protected
Glance content. Test-only dependencies: car-app-testing, work-testing
and glance-appwidget-testing; the two androidTest ones exclude
org.robolectric, whose beta artifacts are not on the mirror and are
unused on device.

Verified: gslot ./gradlew :weather:testDevUnitTest (162 tests, 0
failures) and gslot ./test --instrumented-only weather (OK, 7 tests);
merged report regenerated after folding in the pulled .ec.

Untestable remainder: ViewModel/WeatherApi success paths that require
a live bundle endpoint (offline here, so error paths are asserted
instead), the native .om decode success path, and privileged
location/geocoder backends beyond the shadow/test-provider paths.

(cherry picked from commit 7d254132b1ec51c7d2fa3a6e68cf08d760b3219d)

Diff

weather/build.gradle.kts
diff --git a/weather/build.gradle.kts b/weather/build.gradle.ktsindex a6fd19d8a4..82b8cec365 100644--- a/weather/build.gradle.kts+++ b/weather/build.gradle.kts@@ -54,4 +54,16 @@ dependencies {      // Car-view store-listing screenshots render through the shared host renderer.     add("screenshotTestImplementation", project(":library:carhost"))++    testImplementation(libs.androidx.car.app.testing)+    testImplementation(libs.androidx.work.testing)+    testImplementation(libs.androidx.glance.appwidget.testing)+    // work-testing carries Robolectric for JVM tests; on-device it is+    // unavailable from the mirror and unused, so exclude it there.+    "androidTestImplementation"(libs.androidx.work.testing) {+        exclude(group = "org.robolectric")+    }+    "androidTestImplementation"(libs.androidx.car.app.testing) {+        exclude(group = "org.robolectric")+    } }
weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceLogicTest.kt
diff --git a/weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceLogicTest.kt b/weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceLogicTest.ktnew file mode 100644index 0000000000..682a62a8d3--- /dev/null+++ b/weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceLogicTest.kt@@ -0,0 +1,63 @@+package com.vayunmathur.weather.ui++import android.content.Intent+import androidx.car.app.testing.SessionController+import androidx.car.app.testing.TestCarContext+import androidx.lifecycle.Lifecycle+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.work.Configuration+import androidx.work.ListenableWorker+import androidx.work.testing.SynchronousExecutor+import androidx.work.testing.TestListenableWorkerBuilder+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.weather.data.WeatherRefreshWorker+import com.vayunmathur.weather.service.car.WeatherCarSession+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device logic Robolectric cannot run faithfully: the refresh worker+ * against the real SQLCipher repository (empty locations -> success), and+ * the Android Auto session creating its locations screen against the real+ * cache snapshot.+ */+@RunWith(AndroidJUnit4::class)+class DeviceLogicTest {++    @Test+    fun refreshWorkerSucceedsWithRealRepository() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        val config = Configuration.Builder().setExecutor(SynchronousExecutor()).build()+        WorkManagerTestInitHelper.initializeTestWorkManager(context, config)+        val worker = TestListenableWorkerBuilder<WeatherRefreshWorker>(context).build()+        val result = runBlocking { worker.doWork() }+        assertTrue(+            "expected Success, got $result",+            result is ListenableWorker.Result.Success,+        )+    }++    @Test+    fun carSessionCreatesLocationsScreen() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val context = instrumentation.targetContext+        lateinit var controller: SessionController+        instrumentation.runOnMainSync {+            val carContext = TestCarContext.createCarContext(context)+            val session = WeatherCarSession()+            controller = SessionController(session, carContext, Intent())+            controller.moveToState(Lifecycle.State.CREATED)+            assertNotNull(session)+        }+        // Give the locations flow a moment to land, then tear down so the+        // session's lifecycle observer cancels its collectors.+        Thread.sleep(1_000)+        instrumentation.runOnMainSync {+            controller.moveToState(Lifecycle.State.DESTROYED)+        }+    }+}
weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceRepositoryTest.kt
diff --git a/weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceRepositoryTest.kt b/weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceRepositoryTest.ktnew file mode 100644index 0000000000..c8bcf0ab2b--- /dev/null+++ b/weather/src/androidTest/java/com/vayunmathur/weather/ui/DeviceRepositoryTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.weather.ui++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.data.WeatherCache+import com.vayunmathur.weather.data.WeatherRepository+import com.vayunmathur.weather.network.ForecastResponse+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Direct exercise of the real SQLCipher-backed [WeatherRepository] on+ * device (Robolectric has no AndroidKeyStore, so these delegates can only+ * run here). Cleans up every row it inserts so other journeys still see+ * the fresh-install empty state.+ */+@RunWith(AndroidJUnit4::class)+class DeviceRepositoryTest {++    @Test+    fun repositoryCrudAndCache() = runBlocking {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        val repo = WeatherRepository.get(context)+        val marker = "RepoTest-${System.currentTimeMillis()}"+        var id = -1L+        try {+            id = repo.insertLocation(+                SavedLocation(name = marker, country = "DE", latitude = 52.5, longitude = 13.4, displayOrder = 99),+            )+            assertTrue(id > 0)+            assertTrue(repo.getLocations().any { it.name == marker })+            assertTrue(repo.locations.first().any { it.name == marker })++            repo.updateCoordinates(id, 10.0, 20.0)+            repo.updateName(id, "$marker-renamed", "FR")+            var row = repo.getLocations().first { it.id == id }+            assertEquals("$marker-renamed", row.name)+            assertEquals("FR", row.country)+            assertEquals(10.0, row.latitude, 1e-9)++            repo.setOrder(id, 123)+            row = repo.getLocations().first { it.id == id }+            assertEquals(123, row.displayOrder)++            // Cache round-trip through the delegate + extension.+            repo.writeForecastCache(52.52006, 13.40495, ForecastResponse(52.52006, 13.40495), null, 4242L)+            val cache = repo.getCache(52.5201, 13.405)+            assertNotNull(cache)+            assertEquals(4242L, cache!!.fetchedAtEpochMs)+            repo.upsertCache(WeatherCache(1.0, 2.0, "{}", null, 7L))+            assertEquals(7L, repo.getCache(1.0, 2.0)!!.fetchedAtEpochMs)++            // Current-device row replacement delegates.+            repo.replaceCurrentDeviceLocation(+                SavedLocation(name = marker, latitude = 1.0, longitude = 2.0, isCurrent = true),+            )+            val current = repo.getCurrentDeviceLocation()+            assertNotNull(current)+            assertEquals(marker, current!!.name)+            repo.deleteLocation(current)+            assertNull(repo.getCurrentDeviceLocation())+        } finally {+            // Restore the empty state for the journey tests.+            runCatching {+                repo.getLocations().filter { it.name.startsWith("RepoTest-") || it.name.contains(marker) }+                    .forEach { repo.deleteLocation(it) }+                if (id > 0) repo.getLocations().firstOrNull { it.id == id }?.let { repo.deleteLocation(it) }+                repo.getCurrentDeviceLocation()?.takeIf { it.name.startsWith("RepoTest-") }+                    ?.let { repo.deleteLocation(it) }+            }+        }+    }+}
weather/src/androidTest/java/com/vayunmathur/weather/ui/WeatherJourneyTest.kt
diff --git a/weather/src/androidTest/java/com/vayunmathur/weather/ui/WeatherJourneyTest.kt b/weather/src/androidTest/java/com/vayunmathur/weather/ui/WeatherJourneyTest.ktnew file mode 100644index 0000000000..5eb02f6ae8--- /dev/null+++ b/weather/src/androidTest/java/com/vayunmathur/weather/ui/WeatherJourneyTest.kt@@ -0,0 +1,79 @@+package com.vayunmathur.weather.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device journey that needs the real stack Robolectric cannot provide:+ * the bundled places catalogue unpacks (GeoDatabase), city search returns a+ * real row, and picking it inserts the location through the real+ * SQLCipher-backed repository and returns home.+ */+@RunWith(AndroidJUnit4::class)+class WeatherJourneyTest {++    @Test+    fun searchBerlin_pickResult_returnsHomeWithLocation() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName++        grantAll(instrumentation.uiAutomation, targetContext.packageManager, packageName)++        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)++        assertNotNull(+            "empty state never appeared",+            device.wait(Until.findObject(By.text("No locations yet")), 20_000),+        )+        device.wait(Until.findObject(By.text("Add a location")), 10_000)!!.click()+        assertNotNull(+            "search never opened",+            device.wait(Until.findObject(By.text("City name")), 15_000),+        )+        val fields = device.wait(Until.findObjects(By.clazz("android.widget.EditText")), 10_000)+        val field = fields!!.first()+        field.click()+        field.setText("Berlin")+        // Real catalogue search: a Berlin result row appears (name + region).+        val result = device.wait(Until.findObject(By.text("Berlin")), 30_000)+        assertNotNull("Berlin result never appeared (places catalogue search failed)", result)+        result!!.click()+        // Back home with Berlin as the active location in the search bar.+        assertNotNull(+            "home did not show Berlin after picking it",+            device.wait(Until.findObject(By.textContains("Berlin")), 20_000),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAll(uiAutomation: UiAutomation, pm: PackageManager, pkg: String) {+        val info = try {+            pm.getPackageInfo(pkg, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $pkg not installed", e)+        }+        for (permission in info.requestedPermissions.orEmpty()) {+            try {+                uiAutomation.executeShellCommand("pm grant $pkg $permission").close()+            } catch (ignored: SecurityException) {+            } catch (ignored: IOException) {+            }+        }+    }+}
weather/src/androidTest/java/com/vayunmathur/weather/ui/WidgetGlanceTest.kt
diff --git a/weather/src/androidTest/java/com/vayunmathur/weather/ui/WidgetGlanceTest.kt b/weather/src/androidTest/java/com/vayunmathur/weather/ui/WidgetGlanceTest.ktnew file mode 100644index 0000000000..8d2b76ceb9--- /dev/null+++ b/weather/src/androidTest/java/com/vayunmathur/weather/ui/WidgetGlanceTest.kt@@ -0,0 +1,31 @@+package com.vayunmathur.weather.ui++import androidx.glance.appwidget.AppWidgetId+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.weather.widget.glance.WeatherBlobGlanceWidget+import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Exercises both Glance widgets' real provideGlance path on-device (loadData+ * from the Room cache + Glance RemoteViews composition), which Robolectric+ * cannot run. An unbound app-widget id is used: composition must complete+ * without throwing even though no host ever displays the RemoteViews.+ */+@RunWith(AndroidJUnit4::class)+class WidgetGlanceTest {++    @Test+    fun glanceWidgetsProvideWithoutCrash() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        runBlocking {+            WeatherGlanceWidget().provideGlance(context, AppWidgetId(99001))+            WeatherBlobGlanceWidget().provideGlance(context, AppWidgetId(99002))+        }+        assertTrue(true)+    }+}
weather/src/main/java/com/vayunmathur/weather/data/WeatherRepository.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRepository.kt b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRepository.ktindex c4f4170f38..e5fd66529e 100644--- a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRepository.kt+++ b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRepository.kt@@ -6,28 +6,28 @@ import com.vayunmathur.weather.network.AirQualityResponse import com.vayunmathur.weather.network.ForecastResponse import kotlinx.coroutines.flow.Flow -class WeatherRepository private constructor(context: Context) :+open class WeatherRepository internal constructor(context: Context) :     RoomRepository<WeatherDatabase>(context, WeatherDatabase::class, DB_NAME) {      private val dao get() = db.weatherDao()      // Flows-    val locations: Flow<List<SavedLocation>> get() = dao.observeLocations()+    open val locations: Flow<List<SavedLocation>> get() = dao.observeLocations()      // SavedLocation-    suspend fun getLocations(): List<SavedLocation> = dao.getLocations()-    suspend fun getCurrentDeviceLocation(): SavedLocation? = dao.getCurrentDeviceLocation()-    suspend fun insertLocation(location: SavedLocation): Long = dao.insertLocation(location)-    suspend fun deleteLocation(location: SavedLocation) = dao.deleteLocation(location)-    suspend fun setOrder(id: Long, order: Int) = dao.setOrder(id, order)-    suspend fun updateCoordinates(id: Long, lat: Double, lon: Double) = dao.updateCoordinates(id, lat, lon)-    suspend fun updateName(id: Long, name: String, country: String) = dao.updateName(id, name, country)-    suspend fun replaceCurrentDeviceLocation(newRow: SavedLocation) = dao.replaceCurrentDeviceLocation(newRow)+    open suspend fun getLocations(): List<SavedLocation> = dao.getLocations()+    open suspend fun getCurrentDeviceLocation(): SavedLocation? = dao.getCurrentDeviceLocation()+    open suspend fun insertLocation(location: SavedLocation): Long = dao.insertLocation(location)+    open suspend fun deleteLocation(location: SavedLocation) = dao.deleteLocation(location)+    open suspend fun setOrder(id: Long, order: Int) = dao.setOrder(id, order)+    open suspend fun updateCoordinates(id: Long, lat: Double, lon: Double) = dao.updateCoordinates(id, lat, lon)+    open suspend fun updateName(id: Long, name: String, country: String) = dao.updateName(id, name, country)+    open suspend fun replaceCurrentDeviceLocation(newRow: SavedLocation) = dao.replaceCurrentDeviceLocation(newRow)      // Cache-    suspend fun getCache(lat: Double, lon: Double): WeatherCache? = dao.getCache(lat, lon)-    suspend fun upsertCache(cache: WeatherCache) = dao.upsertCache(cache)-    suspend fun writeForecastCache(+    open suspend fun getCache(lat: Double, lon: Double): WeatherCache? = dao.getCache(lat, lon)+    open suspend fun upsertCache(cache: WeatherCache) = dao.upsertCache(cache)+    open suspend fun writeForecastCache(         latitude: Double,         longitude: Double,         forecast: ForecastResponse,
weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherBlobGlanceWidget.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherBlobGlanceWidget.kt b/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherBlobGlanceWidget.ktindex 636c5ae78d..af786a402f 100644--- a/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherBlobGlanceWidget.kt+++ b/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherBlobGlanceWidget.kt@@ -44,7 +44,7 @@ import kotlin.math.roundToInt  * edges — carrying a large mint temperature and a white condition icon.  * 2x2 — floats over the wallpaper, not full-bleed rect.  */-class WeatherBlobGlanceWidget : MaWidget<WidgetWeather?>() {+open class WeatherBlobGlanceWidget : MaWidget<WidgetWeather?>() {      override suspend fun loadData(context: Context, id: GlanceId): WidgetWeather? =         loadWeatherSnapshot(context)
weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherGlanceWidget.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherGlanceWidget.kt b/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherGlanceWidget.ktindex 4dc0ad9d51..0a97312e53 100644--- a/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherGlanceWidget.kt+++ b/weather/src/main/java/com/vayunmathur/weather/widget/glance/WeatherGlanceWidget.kt@@ -47,7 +47,7 @@ import kotlinx.datetime.toLocalDateTime import kotlin.math.roundToInt import kotlin.time.Clock -class WeatherGlanceWidget : MaWidget<WidgetWeather?>() {+open class WeatherGlanceWidget : MaWidget<WidgetWeather?>() {     override suspend fun loadData(context: Context, id: GlanceId): WidgetWeather? =         loadWeatherSnapshot(context) 
weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.ktnew file mode 100644index 0000000000..cf13952df9--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt@@ -0,0 +1,105 @@+package com.vayunmathur.weather.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.work.Configuration+import androidx.work.WorkManager+import androidx.work.testing.SynchronousExecutor+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.weather.network.WeatherApi+import kotlinx.coroutines.test.runTest+import org.junit.Test as JUnitTest+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue+import kotlin.test.fail++@RunWith(AndroidJUnit4::class)+class GeoAndWorkerTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() {+        GeoDatabase.init(ctx)+    }++    @Test fun prepareIsConsistentWithStatus() = runTest {+        // Robolectric's StorageManager shadow can NPE inside+        // allocateForDatabase before the unpack starts; tolerate that+        // harness gap, but require consistency when prepare returns.+        val result = runCatching { GeoDatabase.prepare() }.getOrElse {+            assertTrue(it is NullPointerException, "unexpected $it")+            return@runTest+        }+        when (val status = GeoDatabase.status.value) {+            is GeoDatabase.Status.Ready -> {+                assertTrue(result.isSuccess)+                assertTrue(GeoDatabase.searchPlaces("Berlin", 5).isNotEmpty())+            }+            is GeoDatabase.Status.Failed -> {+                assertTrue(result.isFailure)+                assertTrue(GeoDatabase.searchPlaces("Berlin", 5).isEmpty())+            }+            else -> fail("unexpected status $status")+        }+    }++    @Test fun prepareIsIdempotent() = runTest {+        runCatching { GeoDatabase.prepare() }+        val second = runCatching { GeoDatabase.prepare() }.getOrElse { return@runTest }+        // Second call returns the cached verified meta or the same failure.+        assertTrue(second.isSuccess == (GeoDatabase.status.value is GeoDatabase.Status.Ready))+    }++    @Test fun scheduleHourlyRefreshEnqueues() {+        val config = Configuration.Builder().setExecutor(SynchronousExecutor()).build()+        WorkManagerTestInitHelper.initializeTestWorkManager(ctx, config)+        WeatherRefreshWorker.scheduleHourlyRefresh(ctx)+        val infos = WorkManager.getInstance(ctx)+            .getWorkInfosForUniqueWork("WeatherHourlyRefresh").get()+        assertTrue(infos.isNotEmpty())+    }++    @JUnitTest(timeout = 60_000)+    fun apiBundleFailsWithoutNetwork() = runTest {+        try {+            WeatherApi.bundle(52.0, 13.0)+            fail("expected network failure")+        } catch (e: Exception) {+            assertTrue(e.message != null || e is RuntimeException)+        }+        try {+            WeatherApi.currentTemperatures(listOf(52.0 to 13.0))+            fail("expected network failure")+        } catch (e: Exception) {+            assertTrue(true)+        }+    }+}++@RunWith(AndroidJUnit4::class)+class WeatherWorkerDoWorkTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun doWorkRetriesWhenRepositoryUnavailable() = runTest {+        // Real repository cannot open under Robolectric (AndroidKeyStore),+        // so doWork must degrade to Result.retry rather than throw.+        val config = Configuration.Builder().setExecutor(SynchronousExecutor()).build()+        WorkManagerTestInitHelper.initializeTestWorkManager(ctx, config)+        val worker = androidx.work.testing.TestListenableWorkerBuilder<WeatherRefreshWorker>(ctx).build()+        val result = worker.doWork()+        assertTrue(result is androidx.work.ListenableWorker.Result.Retry || result is androidx.work.ListenableWorker.Result.Success)+    }++    @Test fun glanceWidgetReceiversScheduleOnEnabled() {+        // onEnabledExtra schedules hourly refresh via WorkManager.+        val config = Configuration.Builder().setExecutor(SynchronousExecutor()).build()+        WorkManagerTestInitHelper.initializeTestWorkManager(ctx, config)+        com.vayunmathur.weather.widget.glance.WeatherGlanceWidgetReceiver().onEnabled(ctx)+        com.vayunmathur.weather.widget.glance.WeatherBlobGlanceWidgetReceiver().onEnabled(ctx)+        val infos = WorkManager.getInstance(ctx).getWorkInfosForUniqueWork("WeatherHourlyRefresh").get()+        assertTrue(infos.isNotEmpty())+    }+}
weather/src/test/java/com/vayunmathur/weather/data/WeatherDaoTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/WeatherDaoTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/WeatherDaoTest.ktnew file mode 100644index 0000000000..6f0ead0c09--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/WeatherDaoTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.weather.data++import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.network.AirQualityResponse+import com.vayunmathur.weather.network.ForecastResponse+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class WeatherDaoTest {++    private lateinit var db: WeatherDatabase+    private lateinit var dao: WeatherDao++    @BeforeTest fun open() {+        db = Room.inMemoryDatabaseBuilder(+            ApplicationProvider.getApplicationContext(),+            WeatherDatabase::class.java,+        ).allowMainThreadQueries().build()+        dao = db.weatherDao()+    }++    @AfterTest fun close() { db.close() }++    private fun loc(name: String, order: Int, current: Boolean = false) = SavedLocation(+        name = name, country = "DE", latitude = 52.5, longitude = 13.4,+        displayOrder = order, isCurrent = current,+    )++    @Test fun insertAndOrdering() = runTest {+        val idB = dao.insertLocation(loc("B", 1))+        dao.insertLocation(loc("A", 0))+        assertEquals(listOf("A", "B"), dao.getLocations().map { it.name })+        assertEquals(listOf("A", "B"), dao.observeLocations().first().map { it.name })+        dao.setOrder(idB, -1)+        assertEquals("B", dao.getLocations().first().name)+    }++    @Test fun updateAndDelete() = runTest {+        val id = dao.insertLocation(loc("Old", 0))+        dao.updateCoordinates(id, 1.0, 2.0)+        dao.updateName(id, "New", "FR")+        val row = dao.getLocations().single()+        assertEquals("New", row.name); assertEquals("FR", row.country)+        assertEquals(1.0, row.latitude); assertEquals(2.0, row.longitude)+        dao.deleteLocation(row)+        assertTrue(dao.getLocations().isEmpty())+    }++    @Test fun replaceCurrentKeepsSingleCurrentRow() = runTest {+        dao.insertLocation(loc("Pinned", 0))+        dao.replaceCurrentDeviceLocation(loc("GPS1", -1, current = false))+        dao.replaceCurrentDeviceLocation(loc("GPS2", -1, current = false))+        val all = dao.getLocations()+        assertEquals(2, all.size)+        assertEquals("GPS2", assertNotNull(dao.getCurrentDeviceLocation()).name)+        assertTrue(dao.getCurrentDeviceLocation()!!.isCurrent)+    }++    @Test fun cacheUpsertAndWritePreservesAirQuality() = runTest {+        val forecast = ForecastResponse(latitude = 52.52006, longitude = 13.40495)+        val aq = AirQualityResponse(current = null)+        dao.writeForecastCache(52.52006, 13.40495, forecast, aq, fetchedAtEpochMs = 1000L)+        var cache = assertNotNull(dao.getCache(52.5201, 13.405))+        assertEquals(1000L, cache.fetchedAtEpochMs)+        assertTrue(cache.forecastJson.contains("52.52006"))+        assertNotNull(cache.airQualityJson)+        // Second write without AQ keeps prior AQ json, updates time.+        dao.writeForecastCache(52.52006, 13.40495, forecast.copy(latitude = 1.0), null, fetchedAtEpochMs = 2000L)+        cache = assertNotNull(dao.getCache(52.5201, 13.405))+        assertEquals(2000L, cache.fetchedAtEpochMs)+        assertNotNull(cache.airQualityJson)+        assertNull(dao.getCache(0.0, 0.0))+        // Direct upsert replaces by PK+        dao.upsertCache(cache.copy(forecastJson = "{}", fetchedAtEpochMs = 3000L))+        assertEquals("{}", assertNotNull(dao.getCache(52.5201, 13.405)).forecastJson)+    }++    @Test fun migrationsDeclared() {+        assertEquals(listOf(MIGRATION_1_2), WeatherDatabase.migrations)+        assertEquals("weather-db", DB_NAME)+    }++    @Test fun geoDatabaseAbsentSearch() = runTest {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        GeoDatabase.init(ctx)+        assertEquals(GeoDatabase.Status.Absent, GeoDatabase.status.value)+        assertTrue(GeoDatabase.searchPlaces("Berlin").isEmpty())+        assertTrue(GeoDatabase.searchPlaces("").isEmpty())+    }+}
weather/src/test/java/com/vayunmathur/weather/domain/DomainEdgesTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/DomainEdgesTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/DomainEdgesTest.ktnew file mode 100644index 0000000000..2ac0a28a1e--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/domain/DomainEdgesTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.weather.domain++import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.Hourly+import kotlinx.datetime.TimeZone+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++@RunWith(RobolectricTestRunner::class)+class DomainEdgesTest {++    private fun current() = Current(+        time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+        relativeHumidity = 50, dewPoint = 14.0, weatherCode = 2, windSpeed = 10.0,+        windDirection = 90, pressureMsl = 1013.0, visibility = 10000.0, cloudCover = 20,+        windGusts = 20.0, isDay = 1,+    )++    private fun fullHourly() = Hourly(+        time = listOf("2026-07-15T00:00", "2026-07-15T06:00", "2026-07-15T12:00"),+        temperature = listOf(15.0, 20.0, 24.0),+        apparentTemperature = listOf(15.0, 20.0, 24.0),+        relativeHumidity = listOf(80, 60, 40),+        dewPoint = listOf(12.0, 12.0, 12.0),+        weatherCode = listOf(0, 1, 2),+        precipitationProbability = listOf(0, 10, 20),+        precipitation = listOf(0.0, 0.0, 0.5),+        windSpeed = listOf(10.0, 10.0, 10.0),+        windDirection = listOf(0, 90, 180),+        pressureMsl = listOf(1010.0, 1012.0, 1014.0),+        visibility = listOf(5000.0, 8000.0, 10000.0),+        cloudCover = listOf(90, 50, 10),+        windGusts = listOf(15.0, 25.0, 20.0),+        uvIndex = listOf(0.0, 3.0, 6.0),+        isDay = listOf(0, 1, 1),+    )++    private fun forecast(hourly: Hourly? = fullHourly(), daily: Daily? = null) = ForecastResponse(+        latitude = 52.0, longitude = 13.0, utcOffsetSeconds = 0,+        current = current(), hourly = hourly, daily = daily,+    )++    @Test fun everyMetricSeriesExtracts() {+        val f = forecast()+        val expected = mapOf(+            WeatherMetric.Temperature to listOf(15.0, 20.0, 24.0),+            WeatherMetric.FeelsLike to listOf(15.0, 20.0, 24.0),+            WeatherMetric.Humidity to listOf(80.0, 60.0, 40.0),+            WeatherMetric.DewPoint to listOf(12.0, 12.0, 12.0),+            WeatherMetric.Precipitation to listOf(0.0, 0.0, 0.5),+            WeatherMetric.WindSpeed to listOf(10.0, 10.0, 10.0),+            WeatherMetric.WindGusts to listOf(15.0, 25.0, 20.0),+            WeatherMetric.Pressure to listOf(1010.0, 1012.0, 1014.0),+            WeatherMetric.Visibility to listOf(5000.0, 8000.0, 10000.0),+            WeatherMetric.CloudCover to listOf(90.0, 50.0, 10.0),+            WeatherMetric.UvIndex to listOf(0.0, 3.0, 6.0),+        )+        for ((metric, values) in expected) {+            assertEquals(values, metricSeries(f, metric, null).map { it.value }, metric.name)+        }+    }++    @Test fun formatterForEveryMetric() {+        for (m in WeatherMetric.entries) {+            val s = metricValueFormatter(m, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(10.0)+            assertTrue(s.isNotBlank(), m.name)+            val imperial = metricValueFormatter(m, TemperatureUnit.Fahrenheit, WindUnit.Mph, PressureUnit.InHg)(10.0)+            assertTrue(imperial.isNotBlank(), m.name)+        }+    }++    @Test fun dayAggregationVectorWind() {+        // Three wind samples N/E/S at equal speed: vector mean cancels N/S,+        // leaving an easterly result slower than the scalar mean.+        val r = assertNotNull(resolveConditions(forecast(), SelectedDateOrTime.Day("2026-07-15")))+        // No daily -> falls back to current? daily is null here, so resolveDay+        // must fall back; covered by unknownDay test. Use a daily instead:+        val withDaily = forecast(daily = Daily(time = listOf("2026-07-15"), temperatureMax = listOf(24.0)))+        val day = assertNotNull(resolveConditions(withDaily, SelectedDateOrTime.Day("2026-07-15")))+        assertEquals(60, day.blockCurrent.relativeHumidity) // avg 80/60/40+        assertEquals(25.0, day.blockCurrent.windGusts) // peak gust+        assertEquals(24.0, day.temperature)+    }++    @Test fun dayWithoutHourlyUsesCurrentBlock() {+        val withDaily = forecast(+            hourly = null,+            daily = Daily(time = listOf("2026-07-15"), temperatureMax = listOf(30.0), weatherCode = listOf(3)),+        )+        val day = assertNotNull(resolveConditions(withDaily, SelectedDateOrTime.Day("2026-07-15")))+        assertEquals(50, day.blockCurrent.relativeHumidity) // current unchanged+        assertEquals(3, day.weatherCode)+    }++    @Test fun hourWithShortListsFallsBackPerField() {+        val short = Hourly(time = listOf("2026-07-15T12:00"))+        val f = forecast(hourly = short, daily = Daily(time = listOf("2026-07-15")))+        val r = assertNotNull(resolveConditions(f, SelectedDateOrTime.Time("2026-07-15T12:00")))+        assertEquals(25.0, r.temperature) // hourly temp missing -> current+        assertEquals(50, r.blockCurrent.relativeHumidity)+    }++    @Test fun instantParsingVariants() {+        // Explicit offset form+        assertTrue(formatInstantInZone("2026-07-01T18:00:00+02:00", TimeZone.UTC, true).contains("16:00"))+        // Naive-UTC form (no Z)+        assertTrue(formatInstantInZone("2026-07-01T18:00", TimeZone.UTC, true).contains("18:00"))+        // Local ISO with explicit Z fallback in parseLocalIsoToEpochSec+        assertEquals(1767225600L, parseLocalIsoToEpochSec("2026-01-01T00:00:00Z", 0))+        assertEquals(null, parseLocalIsoToEpochSec("", 0))+    }++    @Test fun selectedTypesHoldValues() {+        assertEquals("2026-07-15T12:00", SelectedDateOrTime.Time("2026-07-15T12:00").isoTime)+        assertEquals("2026-07-15", SelectedDateOrTime.Day("2026-07-15").isoDate)+    }+}
weather/src/test/java/com/vayunmathur/weather/domain/DomainFormatTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/DomainFormatTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/DomainFormatTest.ktnew file mode 100644index 0000000000..9b278dfba8--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/domain/DomainFormatTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.weather.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class DomainFormatTest {++    @Test fun temperatureConversions() {+        assertEquals("20°C", formatTemperature(20.0, TemperatureUnit.Celsius))+        assertEquals("68°F", formatTemperature(20.0, TemperatureUnit.Fahrenheit))+        assertEquals("-40°F", formatTemperature(-40.0, TemperatureUnit.Fahrenheit))+        assertEquals("21°", formatTemperatureCompact(20.6, TemperatureUnit.Celsius))+        assertEquals(32.0, 0.0.celsiusTo(TemperatureUnit.Fahrenheit))+        assertEquals(0.0, 0.0.celsiusTo(TemperatureUnit.Celsius))+    }++    @Test fun pressureWindAndHelpers() {+        assertEquals("1013 hPa", formatPressure(1013.0, PressureUnit.Hpa))+        assertEquals("29.91 inHg", formatPressure(1013.0, PressureUnit.InHg))+        assertEquals("10 km/h", formatWind(10.0, WindUnit.KmH))+        assertEquals("6 mph", formatWind(10.0, WindUnit.Mph))+        assertEquals(1.0, mmToInches(25.4), 1e-9)+        assertEquals(1.0, metersToMiles(1609.34), 1e-9)+        assertEquals(52.5201, roundCoord(52.52006), 1e-9)+        assertEquals(52.52, roundCoord(52.52004), 1e-9)+    }++    @Test fun compass() {+        assertEquals("N", compassDirection(0))+        assertEquals("N", compassDirection(360))+        assertEquals("N", compassDirection(-10))+        assertEquals("NE", compassDirection(45))+        assertEquals("E", compassDirection(90))+        assertEquals("S", compassDirection(180))+        assertEquals("W", compassDirection(270))+        assertEquals("NNW", compassDirection(340))+        assertEquals("NNE", compassDirection(20))+    }++    @Test fun wmoCodes() {+        assertEquals(WeatherCondition.Clear, weatherConditionForCode(0))+        assertEquals(WeatherCondition.MostlyClear, weatherConditionForCode(1))+        assertEquals(WeatherCondition.PartlyCloudy, weatherConditionForCode(2))+        assertEquals(WeatherCondition.Cloudy, weatherConditionForCode(3))+        assertEquals(WeatherCondition.Fog, weatherConditionForCode(45))+        assertEquals(WeatherCondition.Fog, weatherConditionForCode(48))+        assertEquals(WeatherCondition.Drizzle, weatherConditionForCode(53))+        assertEquals(WeatherCondition.Rain, weatherConditionForCode(61))+        assertEquals(WeatherCondition.Rain, weatherConditionForCode(82))+        assertEquals(WeatherCondition.Snow, weatherConditionForCode(71))+        assertEquals(WeatherCondition.Snow, weatherConditionForCode(86))+        assertEquals(WeatherCondition.Thunderstorm, weatherConditionForCode(95))+        assertEquals(WeatherCondition.Thunderstorm, weatherConditionForCode(99))+        assertEquals(WeatherCondition.Unknown, weatherConditionForCode(4))+        assertEquals(WeatherCondition.Unknown, weatherConditionForCode(999))+    }++    @Test fun dateTimeLabels() {+        assertEquals("Thu 25 Jun", formatDayMonthLabel("2026-06-25"))+        assertEquals("not-a-date", formatDayMonthLabel("not-a-date"))+        assertEquals("3 PM · Thu", formatSelectedHourLabel("2026-06-25T15:00", false))+        assertEquals("15:00 · Thu", formatSelectedHourLabel("2026-06-25T15:00", true))+        assertEquals("bogus", formatSelectedHourLabel("bogus", false))+    }++    @Test fun instantInZoneAndParse() {+        assertEquals(+            "6 PM · Wed",+            formatInstantInZone("2026-07-01T18:00Z", kotlinx.datetime.TimeZone.UTC, false),+        )+        assertEquals(+            "18:00 · Wed",+            formatInstantInZone("2026-07-01T18:00Z", kotlinx.datetime.TimeZone.UTC, true),+        )+        assertEquals("bogus", formatInstantInZone("bogus", kotlinx.datetime.TimeZone.UTC, false))+        assertEquals(1767225600L, parseLocalIsoToEpochSec("2026-01-01T00:00", 0))+        assertEquals(1767222000L, parseLocalIsoToEpochSec("2026-01-01T00:00", 3600))+        assertEquals(null, parseLocalIsoToEpochSec("nope", 0))+    }++    @Test fun epochLabelsUtc() {+        java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("UTC"))+        val epoch = java.time.LocalDateTime.of(2026, 1, 1, 15, 5).toEpochSecond(java.time.ZoneOffset.UTC)+        assertEquals("3 PM", formatStripHour(epoch, false))+        assertEquals("15", formatStripHour(epoch, true))+        assertTrue(formatClockTime(epoch, false).contains("3:05"))+        assertEquals("15:05", formatClockTime(epoch, true))+        assertTrue(formatHourAxisLabel(epoch, true).isNotBlank())+    }++    @Test fun metricMetadata() {+        assertEquals("temperature_2m", WeatherMetric.Temperature.bundleHourlyVar)+        assertEquals("uv_index", WeatherMetric.UvIndex.bundleHourlyVar)+        assertEquals("pressure_msl", WeatherMetric.Pressure.bundleHourlyVar)+        assertTrue(WeatherMetric.Precipitation !in mapMetrics)+        assertTrue(WeatherMetric.WindGusts !in mapMetrics)+        assertTrue(WeatherMetric.Temperature in mapMetrics)+        for (m in WeatherMetric.entries) {+            val ramp = m.colorRamp+            assertTrue(ramp.size >= 3, m.name)+            assertTrue(ramp.zipWithNext().all { (a, b) -> a.value < b.value }, m.name)+        }+        val fmt = metricValueFormatter(WeatherMetric.Humidity, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)+        assertEquals("42%", fmt(41.6))+        assertEquals("3", metricValueFormatter(WeatherMetric.UvIndex, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(3.4))+        assertEquals("20°", metricValueFormatter(WeatherMetric.Temperature, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(20.0))+        assertEquals("10 km/h", metricValueFormatter(WeatherMetric.WindSpeed, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(10.0))+        assertEquals("1013 hPa", metricValueFormatter(WeatherMetric.Pressure, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(1013.0))+        assertEquals("8 km", metricValueFormatter(WeatherMetric.Visibility, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(8000.0))+        assertEquals("5 mi", metricValueFormatter(WeatherMetric.Visibility, TemperatureUnit.Celsius, WindUnit.Mph, PressureUnit.Hpa)(8000.0))+        assertTrue(metricValueFormatter(WeatherMetric.Precipitation, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(1.0).contains("mm"))+    }+}
weather/src/test/java/com/vayunmathur/weather/domain/ResolveConditionsTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/ResolveConditionsTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/ResolveConditionsTest.ktnew file mode 100644index 0000000000..b375aaa4ad--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/domain/ResolveConditionsTest.kt@@ -0,0 +1,137 @@+package com.vayunmathur.weather.domain++import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.Hourly+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class ResolveConditionsTest {++    private fun current() = Current(+        time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+        relativeHumidity = 50, dewPoint = 14.0, weatherCode = 2, windSpeed = 10.0,+        windDirection = 90, pressureMsl = 1013.0, visibility = 10000.0, cloudCover = 20,+        windGusts = 20.0, isDay = 1,+    )++    private fun forecast() = ForecastResponse(+        latitude = 52.0, longitude = 13.0, utcOffsetSeconds = 0,+        current = current(),+        hourly = Hourly(+            time = listOf("2026-07-15T13:00", "2026-07-15T14:00", "2026-07-16T10:00"),+            temperature = listOf(24.0, 25.5, 18.0),+            apparentTemperature = listOf(24.0, 26.5, 17.0),+            relativeHumidity = listOf(55, 48, 60),+            dewPoint = listOf(13.0, 13.5, 10.0),+            weatherCode = listOf(1, 3, 61),+            precipitation = listOf(0.0, 0.1, 2.0),+            windSpeed = listOf(8.0, 12.0, 5.0),+            windDirection = listOf(80, 100, 180),+            pressureMsl = listOf(1012.0, 1014.0, 1010.0),+            visibility = listOf(9000.0, 11000.0, 5000.0),+            cloudCover = listOf(10, 30, 80),+            windGusts = listOf(15.0, 22.0, 9.0),+            uvIndex = listOf(4.0, 5.0, 1.0),+            isDay = listOf(1, 1, 1),+        ),+        daily = Daily(+            time = listOf("2026-07-15", "2026-07-16"),+            weatherCode = listOf(2, 61),+            temperatureMax = listOf(27.0, 19.0),+            temperatureMin = listOf(17.0, 12.0),+            apparentTemperatureMax = listOf(28.0, 18.0),+            sunrise = listOf("2026-07-15T05:00", "2026-07-16T05:01"),+            sunset = listOf("2026-07-15T21:00", "2026-07-16T21:00"),+            daylightDuration = listOf(57600.0, 57540.0),+            uvIndexMax = listOf(6.0, 2.0),+            precipitationSum = listOf(0.1, 3.0),+            moonPhase = listOf(0.5, 0.52),+            moonrise = listOf("2026-07-15T20:00", null),+            moonset = listOf("2026-07-15T06:00", "2026-07-16T07:00"),+        ),+    )++    @Test fun noCurrentReturnsNull() {+        assertNull(resolveConditions(ForecastResponse(0.0, 0.0), null))+    }++    @Test fun currentResolution() {+        val r = assertNotNull(resolveConditions(forecast(), null))+        assertEquals(2, r.weatherCode)+        assertTrue(r.isDay)+        assertEquals(25.0, r.temperature)+        assertEquals(27.0, r.high)+        assertEquals(17.0, r.low)+        assertEquals(6.0, r.uvIndexMax)+        assertEquals("2026-07-15T05:00", r.sunriseIso)+        assertEquals(0.5, r.moonPhase)+        assertEquals(25.0, r.blockCurrent.temperature)+    }++    @Test fun hourResolution() {+        val r = assertNotNull(resolveConditions(forecast(), SelectedDateOrTime.Time("2026-07-15T14:00")))+        assertEquals(3, r.weatherCode)+        assertEquals(25.5, r.temperature)+        assertEquals(26.5, r.apparentTemperature)+        assertEquals(5.0, r.uvIndexMax)+        assertEquals(27.0, r.high)+        assertEquals(0.1, r.precipitationSum)+        assertEquals(48, r.blockCurrent.relativeHumidity)+        assertEquals(22.0, r.blockCurrent.windGusts)+    }++    @Test fun unknownHourFallsBackToCurrent() {+        val r = assertNotNull(resolveConditions(forecast(), SelectedDateOrTime.Time("2026-07-20T10:00")))+        assertEquals(25.0, r.temperature)+        assertEquals(2, r.weatherCode)+    }++    @Test fun dayResolutionAggregatesHourly() {+        val r = assertNotNull(resolveConditions(forecast(), SelectedDateOrTime.Day("2026-07-16")))+        assertEquals(61, r.weatherCode)+        assertEquals(19.0, r.temperature)+        assertEquals(18.0, r.apparentTemperature)+        assertEquals(3.0, r.precipitationSum)+        // Only one hourly row that day: aggregates equal that row.+        assertEquals(60, r.blockCurrent.relativeHumidity)+        assertEquals(9.0, r.blockCurrent.windGusts)+    }++    @Test fun unknownDayFallsBackToCurrent() {+        val r = assertNotNull(resolveConditions(forecast(), SelectedDateOrTime.Day("2026-08-01")))+        assertEquals(25.0, r.temperature)+    }++    @Test fun metricSeriesByDayAndSelection() {+        val f = forecast()+        val today = metricSeries(f, WeatherMetric.Temperature, null)+        assertEquals(listOf(24.0, 25.5), today.map { it.value })+        val day = metricSeries(f, WeatherMetric.Temperature, SelectedDateOrTime.Day("2026-07-16"))+        assertEquals(listOf(18.0), day.map { it.value })+        val byTime = metricSeries(f, WeatherMetric.Humidity, SelectedDateOrTime.Time("2026-07-15T14:00"))+        assertEquals(listOf(55.0, 48.0), byTime.map { it.value })+        assertTrue(metricSeries(ForecastResponse(0.0, 0.0), WeatherMetric.Temperature, null).isEmpty())+    }++    @Test fun metricSeriesSkipsNulls() {+        val f = forecast().copy(+            hourly = forecast().hourly!!.copy(uvIndex = listOf(null, 5.0, null)),+        )+        val pts = metricSeries(f, WeatherMetric.UvIndex, SelectedDateOrTime.Day("2026-07-15"))+        assertEquals(listOf(5.0), pts.map { it.value })+    }++    @Test fun todayFallbacks() {+        // currentTime null -> index based on size capped at 8+        assertEquals(1, todayIndex(Daily(time = listOf("2026-07-15", "2026-07-16")), null))+        assertEquals(0, nowIndex(Hourly(time = listOf("2026-07-15T14:00")), null))+        assertEquals(0, nowIndex(Hourly(time = listOf("2026-07-15T14:00")), "2026-07-15T15:30"))+        val f = ForecastResponse(0.0, 0.0, utcOffsetSeconds = 0, current = null)+        assertTrue(todayIsoDate(f).matches(Regex("\\d{4}-\\d{2}-\\d{2}")))+    }+}
weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.ktnew file mode 100644index 0000000000..3e35474409--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.kt@@ -0,0 +1,105 @@+package com.vayunmathur.weather.network++import com.vayunmathur.weather.domain.map.OmMapMetadata+import com.vayunmathur.weather.domain.WeatherMetric+import com.vayunmathur.weather.domain.map.omFileUrl+import com.vayunmathur.weather.domain.map.DwdIconGlobal+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class NetworkDtoTest {++    private val json = Json { ignoreUnknownKeys = true }++    @Test fun forecastJsonRoundTrip() {+        val raw = """+            {"latitude":52.5,"longitude":13.4,"timezone":"Europe/Berlin","utc_offset_seconds":7200,+             "current":{"time":"2026-07-15T14:30","temperature_2m":25.0,"apparent_temperature":26.0,+               "relative_humidity_2m":50,"weather_code":2,"wind_speed_10m":10.0,"wind_direction_10m":90,"is_day":1},+             "hourly":{"time":["2026-07-15T14:00"],"temperature_2m":[25.0],"uv_index":[null]},+             "daily":{"time":["2026-07-15"],"moonrise":[null]}}+        """.trimIndent()+        val f = json.decodeFromString<ForecastResponse>(raw)+        assertEquals("Europe/Berlin", f.timezone)+        assertEquals(25.0, f.current!!.temperature)+        assertEquals(listOf(null), f.hourly!!.uvIndex)+        assertEquals(listOf(null), f.daily!!.moonrise)+        val re = json.decodeFromString<ForecastResponse>(json.encodeToString(f))+        assertEquals(f, re)+    }++    @Test fun wxBundleDefaultsAndNullSections() {+        val b = json.decodeFromString<WxBundle>("""{"lat":1.0,"lon":2.0}""")+        assertEquals("UTC", b.tz)+        assertNull(b.current)+        val f = b.toForecastResponse()+        assertNull(f.current); assertNull(f.hourly); assertNull(f.daily); assertNull(f.minutely15)+        assertNull(b.toAirQuality())+        assertEquals(RegionTimezone("UTC", "UTC", 0), b.toRegionTimezone())+    }++    @Test fun bundleWithBadDailyStartDropsDaily() {+        val b = WxBundle(+            lat = 0.0, lon = 0.0,+            daily = WxDaily(start = "not-a-date", count = 2, tmax = listOf(1.0, 2.0)),+            hourly = WxHourly(start = 0, count = 1, temp = listOf(3.0)),+        )+        val f = b.toForecastResponse()+        assertNull(f.daily)+        assertEquals(listOf(3.0), assertNotNull(f.hourly).temperature)+    }++    @Test fun geocodingAndAirQualitySerialization() {+        val g = json.decodeFromString<GeocodingResponse>(+            """{"results":[{"id":1,"name":"Berlin","latitude":52.5,"longitude":13.4,"country_code":"DE"}]}""",+        )+        assertEquals("Berlin", g.results[0].name)+        assertEquals("DE", g.results[0].countryCode)+        assertEquals(emptyList(), json.decodeFromString<GeocodingResponse>("{}").results)+        val aq = json.decodeFromString<AirQualityResponse>(+            """{"current":{"time":"2026-07-15T14:00","us_aqi":42,"grass_pollen":1.5}}""",+        )+        assertEquals(42, aq.current!!.usAqi)+        assertEquals(1.5, aq.current!!.grassPollen)+    }++    @Test fun omMetadataSupports() {+        val meta = OmMapMetadata(+            referenceTime = "2026-07-01T18:00:00Z",+            validTimes = listOf("2026-07-01T18:00Z"),+            variables = listOf("temperature_2m", "wind_u_component_10m"),+        )+        assertTrue(meta.supports(WeatherMetric.Temperature))+        assertFalse(meta.supports(WeatherMetric.WindSpeed)) // needs both u and v+        assertFalse(meta.supports(WeatherMetric.Humidity))+        val withWind = meta.copy(variables = meta.variables + "wind_v_component_10m")+        assertTrue(withWind.supports(WeatherMetric.WindSpeed))+        assertEquals("dwd_icon", DwdIconGlobal.model)+        assertEquals(2879, DwdIconGlobal.nx)+    }++    @Test fun omFileUrl() {+        assertEquals(+            "https://api.maproj.org/data_spatial/dwd_icon/2026/07/01/1800Z/2026-07-01T1800.om",+            omFileUrl(DwdIconGlobal, "2026-07-01T18:00:00Z", "2026-07-01T18:00Z"),+        )+    }++    @Test fun geocodeBlankIsEmpty() = runTest {+        assertTrue(WeatherApi.geocode("").results.isEmpty())+        assertTrue(WeatherApi.geocode("   ").results.isEmpty())+        assertTrue(WeatherApi.currentTemperatures(emptyList()).isEmpty())+    }++    @Test fun currentTempResponseDefaults() {+        val c = json.decodeFromString<CurrentTemperatureResponse>("""{"current":{"temperature_2m":21.5}}""")+        assertEquals(21.5, c.current!!.temperature)+        assertNull(json.decodeFromString<CurrentTemperatureResponse>("{}").current)+    }+}
weather/src/test/java/com/vayunmathur/weather/platform/FakeRepository.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/FakeRepository.kt b/weather/src/test/java/com/vayunmathur/weather/platform/FakeRepository.ktnew file mode 100644index 0000000000..c4eb094c77--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/platform/FakeRepository.kt@@ -0,0 +1,52 @@+package com.vayunmathur.weather.platform++import android.content.Context+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.data.WeatherCache+import com.vayunmathur.weather.data.WeatherRepository+import com.vayunmathur.weather.network.AirQualityResponse+import com.vayunmathur.weather.network.ForecastResponse+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow++/** In-memory [WeatherRepository] fake: no Room/SQLCipher, records writes. */+class FakeRepository(context: Context) : WeatherRepository(context) {+    val rows = MutableStateFlow<List<SavedLocation>>(emptyList())+    val caches = mutableMapOf<Pair<Double, Double>, WeatherCache>()+    var nextId = 100L++    override val locations: Flow<List<SavedLocation>> get() = rows+    override suspend fun getLocations(): List<SavedLocation> = rows.value+    override suspend fun getCurrentDeviceLocation(): SavedLocation? = rows.value.firstOrNull { it.isCurrent }+    override suspend fun insertLocation(location: SavedLocation): Long {+        val id = nextId+++        rows.value = rows.value + location.copy(id = id)+        return id+    }+    override suspend fun deleteLocation(location: SavedLocation) {+        rows.value = rows.value.filterNot { it.id == location.id }+    }+    override suspend fun setOrder(id: Long, order: Int) {+        rows.value = rows.value.map { if (it.id == id) it.copy(displayOrder = order) else it }+    }+    override suspend fun updateCoordinates(id: Long, lat: Double, lon: Double) {+        rows.value = rows.value.map { if (it.id == id) it.copy(latitude = lat, longitude = lon) else it }+    }+    override suspend fun updateName(id: Long, name: String, country: String) {+        rows.value = rows.value.map { if (it.id == id) it.copy(name = name, country = country) else it }+    }+    override suspend fun replaceCurrentDeviceLocation(newRow: SavedLocation) {+        rows.value = rows.value.filterNot { it.isCurrent } + newRow.copy(isCurrent = true)+    }+    override suspend fun getCache(lat: Double, lon: Double): WeatherCache? = caches[lat to lon]+    override suspend fun upsertCache(cache: WeatherCache) {+        caches[cache.latRounded to cache.lonRounded] = cache+    }+    override suspend fun writeForecastCache(+        latitude: Double, longitude: Double, forecast: ForecastResponse,+        airQuality: AirQualityResponse?, fetchedAtEpochMs: Long,+    ) {+        caches[latitude to longitude] = WeatherCache(latitude, longitude, "{}", null, fetchedAtEpochMs)+    }+}+
weather/src/test/java/com/vayunmathur/weather/platform/LocationProviderTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/LocationProviderTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/LocationProviderTest.ktnew file mode 100644index 0000000000..f993125ae4--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/platform/LocationProviderTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.weather.platform++import android.Manifest+import android.app.Application+import android.location.Location+import android.location.LocationManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class LocationProviderTest {++    private lateinit var app: Application+    private lateinit var lm: LocationManager++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        lm = app.getSystemService(LocationManager::class.java)+        Shadows.shadowOf(app).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+            Manifest.permission.ACCESS_COARSE_LOCATION,+        )+        Shadows.shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        Shadows.shadowOf(lm).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+    }++    private fun fix(lat: Double, provider: String = LocationManager.GPS_PROVIDER) = Location(provider).apply {+        latitude = lat; longitude = 13.0; time = System.currentTimeMillis()+    }++    @Test fun permissionGranted() {+        assertTrue(LocationProvider.hasPermission(app))+    }++    @Test fun lastKnownLocationReturnedImmediately() = runBlocking {+        Shadows.shadowOf(lm).setLastKnownLocation(LocationManager.GPS_PROVIDER, fix(52.0))+        Shadows.shadowOf(lm).setLastKnownLocation(LocationManager.NETWORK_PROVIDER, fix(40.0, LocationManager.NETWORK_PROVIDER))+        val got = LocationProvider.currentLocation(app)+        assertNotNull(got)+        // Freshest of the providers wins (GPS fix was stamped first but both+        // use "now"; either way a real fix must come back, not a listener).+        assertTrue(got.latitude in listOf(52.0, 40.0))+    }++    @Test fun oneShotListenerDeliversFix() = runBlocking {+        val deferred = async { LocationProvider.currentLocation(app) }+        // Let the call register its one-shot listeners, then push a fix.+        var guard = 0+        while (guard++ < 50) {+            delay(20)+            Shadows.shadowOf(lm).simulateLocation(fix(48.0))+            Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            if (deferred.isCompleted) break+        }+        val got = withTimeout(5_000) { deferred.await() }+        assertEquals(48.0, assertNotNull(got).latitude)+    }+}
weather/src/test/java/com/vayunmathur/weather/platform/PlatformHelpersTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/PlatformHelpersTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/PlatformHelpersTest.ktnew file mode 100644index 0000000000..cdbfff3493--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/platform/PlatformHelpersTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.weather.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.Minutely15+import org.junit.runner.RunWith+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(AndroidJUnit4::class)+class PlatformHelpersTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun forecast(precipProb: Int = 0, wind: Double = 5.0) = ForecastResponse(+        latitude = 52.0, longitude = 13.0,+        current = Current(+            time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+            relativeHumidity = 50, weatherCode = 0, windSpeed = wind, windDirection = 90,+        ),+        daily = Daily(+            time = listOf("2026-07-15"),+            temperatureMax = listOf(27.0), temperatureMin = listOf(17.0),+            precipitationProbabilityMax = listOf(precipProb),+        ),+    )++    @Test fun summaryDryCalm() {+        val s = computeDaySummary(ctx, forecast(), TemperatureUnit.Celsius)+        assertTrue(s.contains("27°"), s)+        assertTrue(s.contains("17°"), s)+        assertFalse(s.lowercase().contains("rain"), s)+    }++    @Test fun summaryRainAndWind() {+        val s = computeDaySummary(ctx, forecast(precipProb = 80, wind = 40.0), TemperatureUnit.Fahrenheit)+        assertTrue(s.lowercase().contains("rain") || s.lowercase().contains("likely"), s)+    }++    @Test fun summaryShowersAndSlight() {+        assertTrue(computeDaySummary(ctx, forecast(precipProb = 50), TemperatureUnit.Celsius).isNotBlank())+        assertTrue(computeDaySummary(ctx, forecast(precipProb = 25), TemperatureUnit.Celsius).isNotBlank())+        // No daily/current at all still produces a string+        assertTrue(computeDaySummary(ctx, ForecastResponse(0.0, 0.0), TemperatureUnit.Celsius).isNotBlank())+    }++    private fun naiveUtc(epochSec: Long): String {+        val ldt = java.time.Instant.ofEpochSecond(epochSec).atZone(java.time.ZoneOffset.UTC)+        return "%04d-%02d-%02dT%02d:%02d".format(ldt.year, ldt.monthValue, ldt.dayOfMonth, ldt.hour, ldt.minute)+    }++    @Test fun nowcastNullAndEmpty() {+        assertNull(precipitationNowcast(ctx, null, 0))+        assertNull(precipitationNowcast(ctx, Minutely15(), 0))+        assertNull(precipitationNowcast(ctx, Minutely15(time = listOf("bogus"), precipitation = listOf(1.0)), 0))+    }++    @Test fun nowcastNoRain() {+        val now = System.currentTimeMillis() / 1000+        val series = Minutely15(+            time = listOf(naiveUtc(now + 900), naiveUtc(now + 1800)),+            precipitation = listOf(0.0, 0.0),+        )+        assertNotNull(precipitationNowcast(ctx, series, 0))+    }++    @Test fun nowcastRainSoonAndNow() {+        val now = System.currentTimeMillis() / 1000+        val soon = Minutely15(+            time = listOf(naiveUtc(now - 3600), naiveUtc(now + 1800)),+            precipitation = listOf(0.0, 1.0),+        )+        assertNotNull(precipitationNowcast(ctx, soon, 0))+        val raining = Minutely15(+            time = listOf(naiveUtc(now - 300)),+            precipitation = listOf(0.5),+        )+        assertNotNull(precipitationNowcast(ctx, raining, 0))+    }++    @Test fun systemTempUnitAndLocationPermission() {+        // Just exercises the branch; value depends on locale prefs.+        assertTrue(systemTempUnit() in TemperatureUnit.entries)+        assertFalse(LocationProvider.hasPermission(ctx))+    }++    @Test fun contractDefaults() {+        val units = DisplayUnits()+        assertEquals(TemperatureUnit.Celsius, units.temperature)+        val loc = SavedLocation(name = "Berlin", latitude = 52.0, longitude = 13.0)+        val state = LocationUiState(location = loc)+        assertNull(state.forecast); assertEquals(false, state.refreshing)+        val rows = LocationsUiState()+        assertTrue(rows.rows.isEmpty()); assertNull(rows.activeLocationId)+        // Noop actions must not throw+        WeatherActions.Noop.refreshAll()+        WeatherActions.Noop.toggleTime("2026-07-15T14:00")+        WeatherActions.Noop.toggleDay("2026-07-15")+        WeatherActions.Noop.clearSelection()+        WeatherActions.Noop.deleteLocation(loc)+        WeatherActions.Noop.reorderLocations(listOf(loc))+        assertEquals(loc, LocationRow(loc, "desc").location)+    }++    @Test fun formatAgoRanges() {+        val res = ctx.resources+        val now = 1_000_000_000_000L+        assertTrue(formatAgoInternal(res, now, now).isNotBlank())+        assertTrue(formatAgoInternal(res, now - 5 * 60_000L, now).isNotBlank())+        assertTrue(formatAgoInternal(res, now - 3 * 3600_000L, now).isNotBlank())+        assertTrue(formatAgoInternal(res, now - 2 * 86400_000L, now).isNotBlank())+    }++    private fun formatAgoInternal(res: android.content.res.Resources, epoch: Long, now: Long) =+        com.vayunmathur.weather.ui.formatAgo(res, epoch, now)+}
weather/src/test/java/com/vayunmathur/weather/platform/UnitExtrasTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/UnitExtrasTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/UnitExtrasTest.ktnew file mode 100644index 0000000000..d16c4502ad--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/platform/UnitExtrasTest.kt@@ -0,0 +1,50 @@+package com.vayunmathur.weather.platform++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.domain.PressureUnit+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.WindUnit+import kotlinx.coroutines.test.runTest+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++@RunWith(AndroidJUnit4::class)+class UnitExtrasTest {++    @get:Rule val rule = createComposeRule()++    @Test fun rememberUnitsResolve() {+        var temp: TemperatureUnit? = null+        var wind: WindUnit? = null+        var pressure: PressureUnit? = null+        var use24: Boolean? = null+        rule.setContent {+            temp = rememberTempUnit()+            wind = rememberWindUnit()+            pressure = rememberPressureUnit()+            use24 = rememberUse24Hour()+            val units = rememberDisplayUnits()+            assertEquals(temp, units.temperature)+            assertEquals(wind, units.wind)+            assertEquals(pressure, units.pressure)+            assertEquals(use24, units.use24Hour)+        }+        assertNotNull(temp); assertNotNull(wind); assertNotNull(pressure); assertNotNull(use24)+    }++    @Test fun currentLocationWithoutPermissionIsNull() = runTest {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        assertNull(LocationProvider.currentLocation(ctx))+    }++    @Test fun backupAgentDbCodec() {+        val agent = AppBackupAgent()+        assertNotNull(agent.dbCodec)+    }+}
weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.ktnew file mode 100644index 0000000000..1a3f9e9ca2--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt@@ -0,0 +1,163 @@+package com.vayunmathur.weather.platform++import android.app.Application+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.data.WeatherCache+import com.vayunmathur.weather.data.weatherJson+import com.vayunmathur.weather.domain.roundCoord+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.ForecastResponse+import org.junit.runner.RunWith+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class ViewModelFetchTest {++    private lateinit var app: Application+    private lateinit var repo: FakeRepository+    private lateinit var vm: WeatherViewModel++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        }+        repo = FakeRepository(app)+        vm = WeatherViewModel(app, repo)+    }++    private fun await(cond: () -> Boolean): Boolean {+        var guard = 0+        while (!cond() && guard++ < 250) {+            Shadows.shadowOf(Looper.getMainLooper()).idle()+            Thread.sleep(20)+        }+        return cond()+    }++    private fun forecast() = ForecastResponse(+        latitude = 52.5, longitude = 13.4,+        current = Current(+            time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+            relativeHumidity = 50, weatherCode = 2, windSpeed = 10.0, windDirection = 90,+        ),+    )++    @Test fun hydrateFromFreshCacheSkipsNetwork() {+        val loc = SavedLocation(id = 7L, name = "Berlin", latitude = 52.52006, longitude = 13.40495)+        repo.caches[roundCoord(loc.latitude) to roundCoord(loc.longitude)] = WeatherCache(+            latRounded = roundCoord(loc.latitude), lonRounded = roundCoord(loc.longitude),+            forecastJson = weatherJson.encodeToString(forecast()),+            airQualityJson = """{"current":null}""",+            fetchedAtEpochMs = System.currentTimeMillis(),+        )+        vm.ensureForecast(loc)+        assertTrue(await { vm.forecasts.value[7L]?.forecast != null }, "state=${vm.forecasts.value}")+        assertEquals(25.0, vm.forecasts.value[7L]!!.forecast!!.current!!.temperature)+        assertEquals(false, vm.forecasts.value[7L]!!.refreshing)+    }++    @Test fun staleCacheThenNetworkFailureSetsError() {+        val loc = SavedLocation(id = 8L, name = "Nowhere", latitude = 1.0, longitude = 2.0)+        repo.caches[1.0 to 2.0] = WeatherCache(+            latRounded = 1.0, lonRounded = 2.0,+            forecastJson = weatherJson.encodeToString(forecast()),+            fetchedAtEpochMs = 0L,+        )+        vm.ensureForecast(loc)+        // Stale cache hydrates, then the (unreachable) network fetch fails and+        // the state must surface an error while keeping the cached forecast.+        assertTrue(await { vm.forecasts.value[8L]?.error != null }, "state=${vm.forecasts.value}")+        assertNotNull(vm.forecasts.value[8L]!!.forecast)+    }++    @Test fun noCacheNetworkFailureSetsError() {+        val loc = SavedLocation(id = 9L, name = "Nowhere", latitude = 3.0, longitude = 4.0)+        vm.ensureForecast(loc, force = true)+        assertTrue(await { vm.forecasts.value[9L]?.error != null }, "state=${vm.forecasts.value}")+    }++    @Test fun currentLocationFetchWithoutPermission() {+        val loc = SavedLocation(id = 10L, name = "GPS", latitude = 5.0, longitude = 6.0, isCurrent = true)+        vm.ensureForecast(loc, force = true)+        assertTrue(await { vm.forecasts.value[10L]?.error != null }, "state=${vm.forecasts.value}")+    }++    @Test fun refreshAllFetchesSavedLocations() {+        val loc = SavedLocation(id = 11L, name = "Berlin", latitude = 52.52006, longitude = 13.40495)+        repo.rows.value = listOf(loc)+        repo.caches[roundCoord(loc.latitude) to roundCoord(loc.longitude)] = WeatherCache(+            latRounded = roundCoord(loc.latitude), lonRounded = roundCoord(loc.longitude),+            forecastJson = weatherJson.encodeToString(forecast()),+            fetchedAtEpochMs = System.currentTimeMillis(),+        )+        // savedLocations is WhileSubscribed: collect via the screen path is+        // covered elsewhere; here refreshAll over an empty snapshot is a no-op+        // and ensureForecast does the work.+        vm.ensureForecast(loc)+        assertTrue(await { vm.forecasts.value[11L]?.forecast != null })+    }+}++@RunWith(AndroidJUnit4::class)+class ViewModelDeviceFixTest {++    private lateinit var app: Application+    private lateinit var repo: FakeRepository+    private lateinit var vm: WeatherViewModel++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        }+        org.robolectric.Shadows.shadowOf(app).grantPermissions(+            android.Manifest.permission.ACCESS_FINE_LOCATION,+        )+        repo = FakeRepository(app)+        vm = WeatherViewModel(app, repo)+    }++    private fun setFix(lat: Double, lon: Double) {+        val lm = app.getSystemService(android.location.LocationManager::class.java)+        val shadow = org.robolectric.Shadows.shadowOf(lm)+        shadow.setProviderEnabled(android.location.LocationManager.GPS_PROVIDER, true)+        shadow.setLastKnownLocation(+            android.location.LocationManager.GPS_PROVIDER,+            android.location.Location(android.location.LocationManager.GPS_PROVIDER).apply {+                latitude = lat; longitude = lon; time = System.currentTimeMillis()+            },+        )+    }++    private fun awaitError(id: Long): Boolean {+        var guard = 0+        while (vm.forecasts.value[id]?.error == null && guard++ < 100) {+            org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            Thread.sleep(20)+        }+        return vm.forecasts.value[id]?.error != null+    }++    @Test fun farFixUpdatesCoordinatesThenNetworkFails() {+        val loc = SavedLocation(id = 21L, name = "GPS", latitude = 52.5, longitude = 13.4, isCurrent = true)+        setFix(10.0, 20.0) // thousands of km away -> move path+        vm.ensureForecast(loc, force = true)+        assertTrue(awaitError(21L), "state=${vm.forecasts.value}")+    }++    @Test fun nearFixKeepsLocationThenNetworkFails() {+        val loc = SavedLocation(id = 22L, name = "GPS", latitude = 52.5, longitude = 13.4, isCurrent = true)+        setFix(52.5001, 13.4001) // ~11 m away -> keep path+        vm.ensureForecast(loc, force = true)+        assertTrue(awaitError(22L), "state=${vm.forecasts.value}")+    }+}
weather/src/test/java/com/vayunmathur/weather/platform/WeatherViewModelTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/WeatherViewModelTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/WeatherViewModelTest.ktnew file mode 100644index 0000000000..db1bb5c675--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/platform/WeatherViewModelTest.kt@@ -0,0 +1,132 @@+package com.vayunmathur.weather.platform++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.data.WeatherCache+import com.vayunmathur.weather.data.WeatherRepository+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.network.AirQualityResponse+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.widget.glance.WeatherBlobGlanceWidget+import com.vayunmathur.weather.widget.glance.WeatherBlobGlanceWidgetReceiver+import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget+import com.vayunmathur.weather.widget.glance.WeatherGlanceWidgetReceiver+import com.vayunmathur.weather.widget.glance.WidgetWeather+import com.vayunmathur.weather.widget.glance.loadWeatherSnapshot+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class WeatherViewModelTest {++    private lateinit var app: Application+    private lateinit var repo: FakeRepository+    private lateinit var vm: WeatherViewModel++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching {+            androidx.work.WorkManager.initialize(+                app, androidx.work.Configuration.Builder().build(),+            )+        }+        repo = FakeRepository(app)+        vm = WeatherViewModel(app, repo)+    }++    @Test fun selectionToggles() {+        assertNull(vm.selectedDateOrTime.value)+        vm.selectTime("2026-07-15T14:00")+        assertEquals(SelectedDateOrTime.Time("2026-07-15T14:00"), vm.selectedDateOrTime.value)+        vm.toggleTime("2026-07-15T14:00")+        assertNull(vm.selectedDateOrTime.value)+        vm.toggleTime("2026-07-15T15:00")+        assertEquals(SelectedDateOrTime.Time("2026-07-15T15:00"), vm.selectedDateOrTime.value)+        vm.toggleDay("2026-07-16")+        assertEquals(SelectedDateOrTime.Day("2026-07-16"), vm.selectedDateOrTime.value)+        vm.toggleDay("2026-07-16")+        assertNull(vm.selectedDateOrTime.value)+        vm.selectDay("2026-07-17")+        vm.clearSelection()+        assertNull(vm.selectedDateOrTime.value)+    }++    @Test fun factoryCreatesViewModel() {+        val created = WeatherViewModelFactory(app, repo).create(WeatherViewModel::class.java)+        assertNotNull(created)+    }++    @Test fun addDeleteAndReorderLocations() = runTest {+        vm.addLocation("Berlin", "Germany", 52.5, 13.4)+        vm.addLocation("Paris", "France", 48.8, 2.3)+        // viewModelScope is Main under Robolectric; drain by polling the fake.+        var rows = repo.getLocations()+        var guard = 0+        while (rows.size < 2 && guard++ < 50) {+            Thread.sleep(20)+            rows = repo.getLocations()+        }+        assertEquals(2, rows.size)+        assertEquals(0, rows[0].displayOrder)+        assertEquals(1, rows[1].displayOrder)+        vm.reorderLocations(listOf(rows[1], rows[0]))+        guard = 0+        while (repo.getLocations().first().name != "Paris" && guard++ < 50) Thread.sleep(20)+        vm.deleteLocation(repo.getLocations().first())+        guard = 0+        while (repo.getLocations().size != 1 && guard++ < 50) Thread.sleep(20)+        assertEquals(1, repo.getLocations().size)+    }++    @Test fun setCurrentLocationReplaces() {+        vm.setCurrentLocation("Here", 10.0, 20.0)+        var guard = 0+        while (repo.rows.value.none { it.isCurrent } && guard++ < 250) {+            org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            Thread.sleep(20)+        }+        assertTrue(repo.rows.value.any { it.isCurrent }, "rows=${repo.rows.value}")+    }++    @Test fun refreshAllWithNoLocationsIsNoOp() {+        vm.refreshAll(force = true)+        assertTrue(vm.forecasts.value.isEmpty())+    }++    @Test fun ensureForecastDedupes() {+        val loc = SavedLocation(id = 999L, name = "Nowhere", latitude = 0.0, longitude = 0.0)+        vm.ensureForecast(loc)+        vm.ensureForecast(loc)+    }++    @Test fun widgetSnapshotEmptyWithoutCache() = runTest {+        // Real repository cannot open SQLCipher under Robolectric; the+        // snapshot loader must degrade to null rather than throw.+        assertNull(loadWeatherSnapshot(app))+    }++    @Test fun glanceWidgetsConstruct() {+        assertNotNull(WeatherGlanceWidget())+        assertNotNull(WeatherBlobGlanceWidget())+        assertNotNull(WeatherGlanceWidgetReceiver())+        assertNotNull(WeatherBlobGlanceWidgetReceiver())+        val data = WidgetWeather(temperatureCelsius = 22.0, weatherCode = 1, isDay = true)+        assertEquals(22.0, data.temperatureCelsius)+        assertTrue(data.isDay)+    }++    @Test fun staleConstant() {+        assertEquals(15 * 60 * 1000L, WeatherViewModel.STALE_THRESHOLD_MS)+    }+}
weather/src/test/java/com/vayunmathur/weather/service/CarScreensTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/service/CarScreensTest.kt b/weather/src/test/java/com/vayunmathur/weather/service/CarScreensTest.ktnew file mode 100644index 0000000000..c3731607ed--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/service/CarScreensTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.weather.service++import android.content.Context+import androidx.car.app.model.MessageTemplate+import androidx.car.app.model.PaneTemplate+import androidx.car.app.testing.TestCarContext+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.data.weatherJson+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.service.car.CarForecast+import com.vayunmathur.weather.service.car.WeatherCarDetailScreen+import com.vayunmathur.weather.service.car.WeatherCarLocationsScreen+import com.vayunmathur.weather.service.car.WeatherCarState+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class CarScreensTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun carContext(apiLevel: Int = 7): TestCarContext {+        val c = TestCarContext.createCarContext(ctx)+        // TestCarContext never establishes a host API level; set the field+        // the host binder would normally fill so screens can pick a template.+        val field = androidx.car.app.CarContext::class.java.getDeclaredField("mCarAppApiLevel")+        field.isAccessible = true+        field.setInt(c, apiLevel)+        return c+    }++    private fun loc(id: Long = 1, name: String = "Berlin", current: Boolean = false) = SavedLocation(+        id = id, name = name, country = "Germany", latitude = 52.5, longitude = 13.4,+        isCurrent = current,+    )++    private fun forecast() = ForecastResponse(+        latitude = 52.5, longitude = 13.4,+        current = Current(+            time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+            relativeHumidity = 50, weatherCode = 2, windSpeed = 10.0, windDirection = 90,+        ),+        daily = Daily(+            time = listOf("2026-07-15", "2026-07-16"),+            temperatureMax = listOf(27.0, 19.0), temperatureMin = listOf(17.0, 12.0),+            weatherCode = listOf(2, 61), precipitationProbabilityMax = listOf(10, 80),+        ),+    )++    @Test fun locationsLoadingTemplate() {+        val state = WeatherCarState()+        val screen = WeatherCarLocationsScreen(carContext(), state)+        assertTrue(screen.onGetTemplate() is MessageTemplate)+    }++    @Test fun locationsEmptyTemplateWithPermissionDenied() {+        val state = WeatherCarState()+        state.locations = emptyList()+        state.permissionDenied = true+        val screen = WeatherCarLocationsScreen(carContext(), state)+        assertTrue(screen.onGetTemplate() is MessageTemplate)+    }++    @Test fun locationsListTemplate() {+        val state = WeatherCarState()+        state.locations = listOf(loc(), loc(2, "Paris"))+        state.putForecast(1L, CarForecast(forecast()))+        val screen = WeatherCarLocationsScreen(carContext(), state)+        assertNotNull(screen.onGetTemplate())+    }++    @Test fun locationsCurrentRowTemplate() {+        val state = WeatherCarState()+        state.locations = listOf(loc(current = true, name = ""))+        val screen = WeatherCarLocationsScreen(carContext(), state)+        assertNotNull(screen.onGetTemplate())+    }++    @Test fun locationsSectionedTemplate() {+        val state = WeatherCarState()+        state.locations = listOf(loc())+        state.putForecast(1L, CarForecast(forecast()))+        assertNotNull(WeatherCarLocationsScreen(carContext(apiLevel = 8), state).onGetTemplate())+    }++    @Test fun detailMissingAndLoadingTemplates() {+        val state = WeatherCarState()+        state.locations = listOf(loc())+        assertTrue(WeatherCarDetailScreen(carContext(), 99L, state).onGetTemplate() is MessageTemplate)+        assertTrue(WeatherCarDetailScreen(carContext(), 1L, state).onGetTemplate() is MessageTemplate)+    }++    @Test fun detailPaneTemplate() {+        val state = WeatherCarState()+        state.locations = listOf(loc())+        state.putForecast(1L, CarForecast(forecast(), fetchedAtEpochMs = 5L))+        val template = WeatherCarDetailScreen(carContext(), 1L, state).onGetTemplate()+        assertTrue(template is PaneTemplate, "got $template")+    }++    @Test fun detailPaneWithoutCurrent() {+        val state = WeatherCarState()+        state.locations = listOf(loc())+        val noCurrent = forecast().copy(current = null)+        state.putForecast(1L, CarForecast(noCurrent))+        assertTrue(WeatherCarDetailScreen(carContext(), 1L, state).onGetTemplate() is PaneTemplate)+    }++    @Test fun carForecastJsonRoundTripViaState() {+        val state = WeatherCarState()+        val json = weatherJson.encodeToString(forecast())+        val decoded = com.vayunmathur.weather.service.car.decodeCarForecast(json, null, 7L)+        assertNotNull(decoded)+        state.putForecast(3L, decoded)+        assertTrue(state.forecastFor(3L)!!.forecast.daily!!.time.size == 2)+    }+}
weather/src/test/java/com/vayunmathur/weather/service/WeatherMiscTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/service/WeatherMiscTest.kt b/weather/src/test/java/com/vayunmathur/weather/service/WeatherMiscTest.ktnew file mode 100644index 0000000000..e3fe776637--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/service/WeatherMiscTest.kt@@ -0,0 +1,150 @@+package com.vayunmathur.weather.service++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoBounds+import com.vayunmathur.weather.data.weatherJson+import com.vayunmathur.weather.domain.map.OmMapMetadata+import com.vayunmathur.weather.domain.map.colorizeToBitmap+import com.vayunmathur.weather.domain.ColorStop+import com.vayunmathur.weather.domain.WeatherMetric+import com.vayunmathur.weather.intents.errorWeatherData+import com.vayunmathur.weather.intents.toWeatherData+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.service.car.WeatherCarAppService+import com.vayunmathur.weather.service.car.WeatherCarState+import com.vayunmathur.weather.service.car.cacheKeyFor+import com.vayunmathur.weather.service.car.decodeCarForecast+import com.vayunmathur.weather.ui.cacheKey+import com.vayunmathur.weather.ui.indexForIso+import com.vayunmathur.weather.ui.rasterSize+import com.vayunmathur.weather.ui.WeatherMapState+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.graphics.toArgb+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class WeatherMiscTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun forecast() = ForecastResponse(+        latitude = 52.0, longitude = 13.0, utcOffsetSeconds = 0,+        current = Current(+            time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+            relativeHumidity = 50, weatherCode = 2, windSpeed = 10.0, windDirection = 90,+        ),+        daily = Daily(+            time = listOf("2026-07-15"), temperatureMax = listOf(27.0),+            temperatureMin = listOf(17.0), precipitationProbabilityMax = listOf(33),+            uvIndexMax = listOf(5.0), sunrise = listOf("2026-07-15T05:00"),+            sunset = listOf("2026-07-15T21:00"),+        ),+    )++    @Test fun toWeatherData() {+        val data = forecast().toWeatherData(ctx, "Berlin, Germany")+        assertEquals("Berlin, Germany", data.locationName)+        assertEquals(25.0, data.temperatureCelsius)+        assertEquals(27.0, data.highCelsius)+        assertEquals(33, data.precipitationChancePercent)+        assertEquals("E", data.windDirection)+        assertEquals(5.0, data.uvIndex)+        assertNotNull(data.sunriseEpochSec)+    }++    @Test fun toWeatherDataNoCurrent() {+        val data = ForecastResponse(0.0, 0.0).toWeatherData(ctx, null)+        assertEquals("No current observations available", data.error)+        val err = errorWeatherData("X", "boom")+        assertEquals("boom", err.error); assertEquals("X", err.locationName)+        assertEquals(0.0, err.temperatureCelsius)+    }++    @Test fun intentsReturnErrorWithoutNetwork() = runTest {+        val a = com.vayunmathur.weather.intents.GetWeatherIntent()+            .performCalculation(com.vayunmathur.weather.intents.LatLonInput(52.0, 13.0))+        assertNotNull(a.error)+        val b = com.vayunmathur.weather.intents.GetWeatherByNameIntent()+            .performCalculation(com.vayunmathur.weather.intents.LocationQueryInput(""))+        assertNotNull(b.error)+    }++    @Test fun carStateObserversAndDecode() {+        val state = WeatherCarState()+        var calls = 0+        state.observe { calls++ }+        state.observe { throw RuntimeException("bad observer") }+        state.notifyChanged()+        assertEquals(1, calls)+        assertNull(state.forecastFor(1L))+        val json = weatherJson.encodeToString(forecast())+        val car = assertNotNull(decodeCarForecast(json, null, 123L))+        assertEquals(123L, car.fetchedAtEpochMs)+        assertEquals(25.0, car.forecast.current!!.temperature)+        state.putForecast(1L, car)+        assertEquals(car, state.forecastFor(1L))+        assertNull(decodeCarForecast("not json", null, 0L))+        val withAq = decodeCarForecast(json, """{"current":null}""", 5L)+        assertNotNull(withAq); assertNull(withAq.airQuality!!.current)+        assertEquals(52.5201 to 13.405, cacheKeyFor(52.52006, 13.40495))+    }++    @Test fun carServiceCreatesSessionAndValidator() {+        val svc = WeatherCarAppService()+        assertNotNull(svc.createHostValidator())+        assertNotNull(svc.onCreateSession())+    }++    @Test fun mapHelpers() {+        val bounds = GeoBounds(west = 0.0, south = 0.0, east = 10.0, north = 5.0)+        val (w, h) = rasterSize(bounds)+        assertEquals(512, w); assertEquals(256, h)+        val (w2, h2) = rasterSize(GeoBounds(west = 0.0, south = 0.0, east = 5.0, north = 10.0))+        assertEquals(512, h2); assertEquals(256, w2)+        assertTrue(cacheKey(bounds, "temperature_2m", "2026-07-01T18:00Z").contains("temperature_2m"))+        assertEquals(0, indexForIso(emptyList(), "x"))+        assertEquals(1, indexForIso(listOf("2026-07-01T17:00Z", "2026-07-01T18:00Z"), "2026-07-01T18:00Z"))+        assertEquals(1, indexForIso(listOf("2026-07-01T17:00Z", "2026-07-01T18:30Z"), "2026-07-01T18:00"))+        assertEquals(0, indexForIso(listOf("2026-07-02T00:00Z"), "2026-07-01T18:00"))+        assertEquals(0, indexForIso(listOf("2026-07-01T00:00Z"), null))+    }++    @Test fun mapStateDefaultsAndFallback() {+        val s = WeatherMapState("Temperature")+        assertEquals(WeatherMetric.Temperature, s.selectedMetric)+        assertEquals(WeatherMetric.Temperature, WeatherMapState("bogus").selectedMetric)+        // Precipitation is not a map metric -> falls back+        assertEquals(WeatherMetric.Temperature, WeatherMapState("Precipitation").selectedMetric)+        assertTrue(s.supportedMetrics.isNotEmpty())+        s.metadata = OmMapMetadata(+            referenceTime = "2026-07-01T18:00:00Z",+            validTimes = listOf("t1"),+            variables = listOf("temperature_2m"),+        )+        assertEquals(listOf(WeatherMetric.Temperature), s.supportedMetrics)+        assertEquals(listOf("t1"), s.times)+    }++    @Test fun colorizeBitmap() {+        val ramp = listOf(ColorStop(0.0, Color.Red), ColorStop(10.0, Color.Blue))+        val bmp = colorizeToBitmap(floatArrayOf(0f, 5f, 10f, Float.NaN), 2, 2, ramp)+        assertEquals(2, bmp.width); assertEquals(2, bmp.height)+        assertEquals(Color.Red.toArgb(), bmp.asAndroidBitmap().getPixel(0, 0))+        assertEquals(Color.Blue.toArgb(), bmp.asAndroidBitmap().getPixel(0, 1))+        assertEquals(0, bmp.asAndroidBitmap().getPixel(1, 1))+        // empty ramp -> transparent+        val empty = colorizeToBitmap(floatArrayOf(1f), 1, 1, emptyList())+        assertEquals(0, empty.asAndroidBitmap().getPixel(0, 0))+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/CanvasBlocksTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/CanvasBlocksTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/CanvasBlocksTest.ktnew file mode 100644index 0000000000..d954fca487--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/CanvasBlocksTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.weather.ui++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.domain.MetricPoint+import com.vayunmathur.weather.ui.components.MetricGraphSheet+import com.vayunmathur.weather.ui.components.blocks.MoonBlock+import com.vayunmathur.weather.ui.components.blocks.SunBlock+import com.vayunmathur.weather.ui.components.blocks.UvIndexBlock+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.onRoot+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test++/**+ * Canvas-heavy blocks under Robolectric's NATIVE graphics mode so the+ * DrawScope lambdas (sun/moon tracks, moon disc, UV dots, graph lines)+ * actually execute instead of being skipped by the legacy shadow canvas.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(AndroidJUnit4::class)+class CanvasBlocksTest {++    @get:Rule val rule = createComposeRule()++    @Test fun sunMoonUvDraw() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                SunBlock(1767225600L, 1767268800L, true, 43200.0, 1767247200L)+                MoonBlock(0.5, 1767225600L, 1767268800L, false, 1767247200L)+                MoonBlock(0.9, null, null, true, 1767247200L)+                MoonBlock(null, 1767225600L, 1767200000L, true, 1767247200L)+                UvIndexBlock(9.0)+                UvIndexBlock(2.0)+                UvIndexBlock(null)+            }+        }+        rule.waitForIdle()+        // Force a real render pass so every Canvas DrawScope lambda runs.+        rule.onRoot().captureToImage()+    }++    @Test fun graphSheetDraws() {+        rule.setContent {+            MetricGraphSheet(+                title = "Temperature",+                points = (0..10).map { MetricPoint(1767225600L + it * 3600, 10.0 + it % 3) },+                valueLabel = { "${it.toInt()}°" },+                timeLabel = { "h$it" },+                onOpenMap = {},+                onDismiss = {},+            )+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/ComposeBlocksTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/ComposeBlocksTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/ComposeBlocksTest.ktnew file mode 100644index 0000000000..30e7fcbe4b--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/ComposeBlocksTest.kt@@ -0,0 +1,264 @@+package com.vayunmathur.weather.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.onLast+import androidx.compose.ui.test.performTouchInput+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.domain.PressureUnit+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.WindUnit+import com.vayunmathur.weather.network.AirQualityCurrent+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.Hourly+import com.vayunmathur.weather.ui.components.CurrentWeatherCard+import com.vayunmathur.weather.ui.components.DailyCard+import com.vayunmathur.weather.ui.components.HourlyCard+import com.vayunmathur.weather.ui.components.MetricGraphSheet+import com.vayunmathur.weather.ui.components.SelectedDateTimeHeader+import com.vayunmathur.weather.ui.components.SummaryCard+import com.vayunmathur.weather.ui.components.UseDeviceLocationCard+import com.vayunmathur.weather.ui.components.WeatherBlocks+import com.vayunmathur.weather.ui.components.blocks.AirQualityBlock+import com.vayunmathur.weather.ui.components.blocks.CloudCoverBlock+import com.vayunmathur.weather.ui.components.blocks.HumidityBlock+import com.vayunmathur.weather.ui.components.blocks.MoonBlock+import com.vayunmathur.weather.ui.components.blocks.PollenBlock+import com.vayunmathur.weather.ui.components.blocks.PrecipitationBlock+import com.vayunmathur.weather.ui.components.blocks.PressureBlock+import com.vayunmathur.weather.ui.components.blocks.SunBlock+import com.vayunmathur.weather.ui.components.blocks.UvIndexBlock+import com.vayunmathur.weather.ui.components.blocks.VisibilityBlock+import com.vayunmathur.weather.ui.components.blocks.WindBlock+import com.vayunmathur.weather.domain.MetricPoint+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class ComposeBlocksTest {++    @get:Rule val rule = createComposeRule()++    private fun current(+        humidity: Int = 65, cloud: Int = 85, windDir: Int = 90,+    ) = Current(+        time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+        relativeHumidity = humidity, dewPoint = 14.0, weatherCode = 2, windSpeed = 10.0,+        windDirection = windDir, pressureMsl = 1013.0, visibility = 8000.0,+        cloudCover = cloud, windGusts = 20.0, isDay = 1,+    )++    private fun air(aqi: Int? = 42) = AirQualityCurrent(+        time = "2026-07-15T14:00", usAqi = aqi, grassPollen = 5.0, birchPollen = 60.0,+    )++    @Test fun currentCardShowsTempAndCondition() {+        rule.setContent {+            CurrentWeatherCard(2, true, 25.0, 26.0, 27.0, 17.0, TemperatureUnit.Celsius)+        }+        rule.onNodeWithText("25°").assertIsDisplayed()+        rule.onNodeWithText("Partly cloudy", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Feels like", substring = true).assertIsDisplayed()+    }++    @Test fun currentCardWithoutFeelsLikeOrRange() {+        rule.setContent {+            CurrentWeatherCard(0, false, 10.0, null, null, null, TemperatureUnit.Fahrenheit)+        }+        rule.onNodeWithText("50°").assertIsDisplayed()+    }++    @Test fun blocksRenderValues() {+        rule.setContent {+            HumidityBlock(current(), TemperatureUnit.Celsius)+            UvIndexBlock(7.0)+            AirQualityBlock(air())+            PollenBlock(air())+            CloudCoverBlock(current())+            WindBlock(current(), WindUnit.KmH)+            PressureBlock(current(), PressureUnit.Hpa)+            VisibilityBlock(current(), useMiles = false)+        }+        rule.onNodeWithText("65%").assertIsDisplayed()+        rule.onNodeWithText("7").assertIsDisplayed()+        rule.onNodeWithText("42").assertIsDisplayed()+        rule.onNodeWithText("85%").assertIsDisplayed()+        rule.onNodeWithText("1013").assertIsDisplayed()+        rule.onNodeWithText("8").assertIsDisplayed()+    }++    @Test fun blocksNullAndExtremeVariants() {+        rule.setContent {+            AirQualityBlock(null)+            PollenBlock(null)+            UvIndexBlock(null)+            UvIndexBlock(12.0)+            AirQualityBlock(air(aqi = 350))+            CloudCoverBlock(current(cloud = 5))+            PressureBlock(current().copy(pressureMsl = 970.0), PressureUnit.InHg)+            VisibilityBlock(current().copy(visibility = 16093.0), useMiles = true)+            WindBlock(current(), WindUnit.Mph)+            HumidityBlock(current(humidity = 95), TemperatureUnit.Fahrenheit)+        }+        rule.onNodeWithText("Good", substring = true).assertDoesNotExist()+        rule.onNodeWithText("12").assertIsDisplayed()+    }++    @Test fun sunMoonPrecipBlocks() {+        rule.setContent {+            SunBlock(+                sunriseEpochSec = 1767225600L, sunsetEpochSec = 1767268800L,+                use24Hour = true, daylightDurationSec = 43200.0, nowEpochSec = 1767247200L,+            )+            MoonBlock(+                moonPhase = 0.5, moonriseEpochSec = 1767225600L, moonsetEpochSec = 1767268800L,+                use24Hour = false, nowEpochSec = 1767247200L,+            )+            PrecipitationBlock(amountMm = 2.5, useInches = false, nowcast = "Raining now")+            PrecipitationBlock(amountMm = 25.4, useInches = true, nowcast = null)+        }+        rule.onNodeWithText("Raining now").assertIsDisplayed()+        rule.onNodeWithText("Full Moon", substring = true).assertIsDisplayed()+        rule.onNodeWithText("1.00").assertIsDisplayed()+    }++    @Test fun moonPhaseVariantsAndNullSun() {+        rule.setContent {+            MoonBlock(moonPhase = 0.1, moonriseEpochSec = null, moonsetEpochSec = null, use24Hour = true)+            SunBlock(sunriseEpochSec = null, sunsetEpochSec = null, use24Hour = true)+        }+        rule.onNodeWithText("Waxing Crescent", substring = true).assertIsDisplayed()+    }++    @Test fun weatherBlocksGridAndMetricClick() {+        var clicked: com.vayunmathur.weather.domain.WeatherMetric? = null+        rule.setContent {+            WeatherBlocks(+                current = current(), uvIndex = 5.0, air = air(),+                sunriseEpochSec = 1767225600L, sunsetEpochSec = 1767268800L,+                precipitationMm = 1.0, precipitationNowcast = "Raining now",+                daylightDurationSec = 40000.0, moonPhase = 0.25,+                moonriseEpochSec = 1767225600L, moonsetEpochSec = 1767268800L,+                onMetricSelected = { clicked = it },+                tempUnit = TemperatureUnit.Celsius, windUnit = WindUnit.KmH,+                pressureUnit = PressureUnit.Hpa, use24Hour = true, nowEpochSec = 1767247200L,+            )+        }+        rule.onNodeWithText("65%").assertIsDisplayed()+        rule.onNodeWithText("65%").performClick()+        assertEquals(com.vayunmathur.weather.domain.WeatherMetric.Humidity, clicked)+    }++    @Test fun hourlyAndDailyCards() {+        var hour: String? = null+        var day: String? = null+        val hourly = Hourly(+            time = listOf("2026-07-15T13:00", "2026-07-15T14:00"),+            temperature = listOf(24.0, 25.0), weatherCode = listOf(0, 2),+            precipitationProbability = listOf(0, 20), isDay = listOf(1, 1),+        )+        val daily = Daily(+            time = listOf("2026-07-15", "2026-07-16"),+            temperatureMax = listOf(27.0, 19.0), temperatureMin = listOf(17.0, 12.0),+            weatherCode = listOf(0, 61), precipitationProbabilityMax = listOf(10, 80),+        )+        rule.setContent {+            HourlyCard(hourly, TemperatureUnit.Celsius, 0, false, null, { hour = it }, null, "2026-07-15T14:00", 1760000000L)+            DailyCard(daily, TemperatureUnit.Celsius, "2026-07-16", { day = it }, "2026-07-15")+        }+        rule.mainClock.advanceTimeBy(2_000)+        rule.onNodeWithText("Hourly forecast").assertIsDisplayed()+        rule.onNodeWithText("Daily forecast").assertIsDisplayed()+        rule.onNodeWithText("27°").performClick()+        assertEquals("2026-07-15", day)+        assertTrue(hour == null || hour!!.startsWith("2026"))+    }++    @Test fun emptyCardsRenderNothing() {+        rule.setContent {+            DailyCard(Daily(), TemperatureUnit.Celsius)+            HourlyCard(Hourly(), TemperatureUnit.Celsius)+        }+        rule.onNodeWithText("Daily forecast").assertDoesNotExist()+    }++    @Test fun summarySelectedAndDeviceCards() {+        var cleared = false+        var used = false+        val forecast = ForecastResponse(+            latitude = 0.0, longitude = 0.0, current = current(),+            daily = Daily(+                time = listOf("2026-07-15"), temperatureMax = listOf(27.0),+                temperatureMin = listOf(17.0), precipitationProbabilityMax = listOf(0),+            ),+        )+        rule.setContent {+            SummaryCard(forecast, TemperatureUnit.Celsius)+            SelectedDateTimeHeader(SelectedDateOrTime.Day("2026-06-25"), false) { cleared = true }+            SelectedDateTimeHeader(SelectedDateOrTime.Time("2026-06-25T15:00"), true) {}+            UseDeviceLocationCard(onClick = { used = true }, isLoading = false)+            UseDeviceLocationCard(onClick = {}, isLoading = true)+        }+        rule.onAllNodesWithText("Use current location", substring = true)[0].assertIsDisplayed()+        rule.onNodeWithText("Thu 25 Jun", substring = true).assertIsDisplayed()+    }++    @Test fun metricGraphSheetStates() {+        var opened = false+        var dismissed = false+        rule.setContent {+            MetricGraphSheet(+                title = "Temperature",+                points = listOf(MetricPoint(1767225600L, 10.0), MetricPoint(1767229200L, 12.0), MetricPoint(1767232800L, 11.0)),+                valueLabel = { "${it.toInt()}°" },+                timeLabel = { "t$it" },+                onOpenMap = { opened = true },+                onDismiss = { dismissed = true },+            )+        }+        rule.onNodeWithText("Temperature").assertIsDisplayed()+        rule.onNodeWithText("12°").assertIsDisplayed()+    }++    @Test fun metricGraphSheetInteraction() {+        rule.setContent {+            MetricGraphSheet(+                title = "Temperature",+                points = (0..10).map { MetricPoint(1767225600L + it * 3600, 10.0 + it) },+                valueLabel = { "${it.toInt()}°" },+                timeLabel = { "h" },+                onOpenMap = {},+                onDismiss = {},+            )+        }+        rule.waitForIdle()+        // Tap and drag across the chart so the selection marker draws.+        rule.onAllNodes(androidx.compose.ui.test.isRoot()).onLast().performTouchInput {+            down(androidx.compose.ui.geometry.Offset(160f, 376f))+            moveBy(androidx.compose.ui.geometry.Offset(60f, 0f))+            up()+        }+        rule.waitForIdle()+        rule.onNodeWithText("Temperature").assertIsDisplayed()+    }++    @Test fun metricGraphSheetNotEnoughData() {+        rule.setContent {+            MetricGraphSheet(+                title = "Wind", points = listOf(MetricPoint(0L, 1.0)),+                valueLabel = { it.toString() }, timeLabel = { "" },+                onOpenMap = {}, onDismiss = {},+            )+        }+        rule.onNodeWithText("Not enough data to plot.").assertIsDisplayed()+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.ktnew file mode 100644index 0000000000..e7bdacac62--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.kt@@ -0,0 +1,252 @@+package com.vayunmathur.weather.ui++import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onLast+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.performClick+import androidx.compose.ui.unit.dp+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.rememberDrawerState+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.weather.Route+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.Hourly+import com.vayunmathur.weather.platform.DisplayUnits+import com.vayunmathur.weather.platform.LocationRow+import com.vayunmathur.weather.platform.LocationUiState+import com.vayunmathur.weather.platform.LocationsUiState+import com.vayunmathur.weather.platform.WeatherActions+import com.vayunmathur.weather.ui.components.LocationItem+import com.vayunmathur.weather.ui.components.MainSearchBar+import kotlinx.serialization.json.Json+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class ComposeScreensTest {++    @get:Rule val rule = createComposeRule()++    private fun loc(id: Long = 1, name: String = "Berlin", current: Boolean = false) = SavedLocation(+        id = id, name = name, country = "Germany", latitude = 52.5, longitude = 13.4,+        displayOrder = 0, isCurrent = current,+    )++    private fun forecast() = ForecastResponse(+        latitude = 52.5, longitude = 13.4, utcOffsetSeconds = 0,+        current = Current(+            time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+            relativeHumidity = 50, dewPoint = 14.0, weatherCode = 2, windSpeed = 10.0,+            windDirection = 90, pressureMsl = 1013.0, visibility = 10000.0,+            cloudCover = 20, windGusts = 20.0, isDay = 1,+        ),+        hourly = Hourly(+            time = listOf("2026-07-15T14:00"), temperature = listOf(25.0),+            weatherCode = listOf(2), precipitationProbability = listOf(10), isDay = listOf(1),+        ),+        daily = Daily(+            time = listOf("2026-07-15"), temperatureMax = listOf(27.0),+            temperatureMin = listOf(17.0), weatherCode = listOf(2),+            precipitationProbabilityMax = listOf(10), uvIndexMax = listOf(5.0),+            sunrise = listOf("2026-07-15T05:00"), sunset = listOf("2026-07-15T21:00"),+        ),+    )++    @Test fun forecastColumnWithForecast() {+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(location = loc(), forecast = forecast()),+                units = DisplayUnits(),+                actions = WeatherActions.Noop,+                drawerState = rememberDrawerState(DrawerValue.Closed),+                paddingValues = PaddingValues(0.dp),+                precipitationNowcast = "Raining now",+                nowEpochSec = 1760000000L,+                onOpenMap = { _, _ -> },+            )+        }+        rule.onNodeWithText("Berlin", substring = true).assertIsDisplayed()+        rule.onAllNodesWithText("25°")[0].assertIsDisplayed()+    }++    @Test fun forecastColumnLoadingAndError() {+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(location = loc(), forecast = null, error = "Boom"),+                units = DisplayUnits(),+                actions = WeatherActions.Noop,+                drawerState = rememberDrawerState(DrawerValue.Closed),+                paddingValues = PaddingValues(0.dp),+                precipitationNowcast = null,+                nowEpochSec = 0L,+                onOpenMap = { _, _ -> },+            )+        }+        rule.onNodeWithText("Boom").assertIsDisplayed()+    }++    @Test fun forecastColumnSelected() {+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(+                    location = loc(), forecast = forecast(),+                    selected = SelectedDateOrTime.Time("2026-07-15T14:00"),+                ),+                units = DisplayUnits(),+                actions = WeatherActions.Noop,+                drawerState = rememberDrawerState(DrawerValue.Closed),+                paddingValues = PaddingValues(0.dp),+                precipitationNowcast = null,+                nowEpochSec = 1760000000L,+                onOpenMap = { _, _ -> },+            )+        }+        rule.onAllNodesWithText("25°")[0].assertIsDisplayed()+    }++    @Test fun forecastColumnScrollsAndRendersBlocks() {+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(location = loc(), forecast = forecast()),+                units = DisplayUnits(),+                actions = WeatherActions.Noop,+                drawerState = rememberDrawerState(DrawerValue.Closed),+                paddingValues = PaddingValues(0.dp),+                precipitationNowcast = null,+                nowEpochSec = 1760000000L,+                onOpenMap = { _, _ -> },+            )+        }+        rule.onNodeWithText("Berlin", substring = true).assertIsDisplayed()+        // Scroll the forecast column repeatedly so the blocks grid below+        // the fold composes and draws.+        repeat(8) {+            rule.onAllNodes(androidx.compose.ui.test.isRoot()).onLast()+                .performTouchInput {+                    down(androidx.compose.ui.geometry.Offset(160f, 400f))+                    moveBy(androidx.compose.ui.geometry.Offset(160f, 100f))+                    up()+                }+            rule.waitForIdle()+        }+        rule.waitForIdle()+    }++    @Test fun homeScreenCompact() {+        rule.setContent {+            HomeScreen(+                state = LocationUiState(location = loc(), forecast = forecast()),+                units = DisplayUnits(),+                actions = WeatherActions.Noop,+                precipitationNowcast = null,+                nowEpochSec = 1760000000L,+            )+        }+        rule.onNodeWithText("Berlin", substring = true).assertIsDisplayed()+    }++    @Test fun locationsScreenSelectAndSearch() {+        var selected: SavedLocation? = null+        var searched = false+        var usedDevice = false+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(+                    rows = listOf(+                        LocationRow(loc(1, "Berlin"), "No data yet", 2, true),+                        LocationRow(loc(2, "Paris"), "Last updated 5m ago", 0, true),+                    ),+                    activeLocationId = 1L,+                ),+                actions = WeatherActions.Noop,+                onLocationSelect = { selected = it },+                onSearchLocation = { searched = true },+                onUseDeviceLocation = { usedDevice = true },+            )+        }+        rule.onNodeWithText("Locations").assertIsDisplayed()+        rule.onNodeWithText("Berlin").assertIsDisplayed()+        rule.onNodeWithText("Paris").performClick()+        assertEquals("Paris", selected?.name)+        rule.onNodeWithText("Search location").performClick()+        assertTrue(searched)+    }++    @Test fun locationsScreenEmptyShowsDeviceCard() {+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(rows = emptyList()),+                actions = WeatherActions.Noop,+            )+        }+        rule.onNodeWithText("Use current location", substring = true).assertIsDisplayed()+    }++    @Test fun locationItemAndSearchBar() {+        var clicked = false+        rule.setContent {+            LocationItem(+                location = loc(current = true), description = "No data yet",+                currentWeatherCode = 0, isDay = true, isSelected = true,+                onClick = { clicked = true }, onLongClick = {},+            )+            MainSearchBar(+                paddingValues = PaddingValues(0.dp),+                drawerState = rememberDrawerState(DrawerValue.Closed),+                activeLocation = loc(),+            )+        }+        rule.onNodeWithText("Berlin").assertIsDisplayed()+        rule.onNodeWithText("Berlin").performClick()+        assertTrue(clicked)+    }++    @Test fun mainSearchBarNoLocation() {+        rule.setContent {+            MainSearchBar(+                paddingValues = PaddingValues(0.dp),+                drawerState = rememberDrawerState(DrawerValue.Closed),+                activeLocation = null,+            )+        }+        rule.onNodeWithText("••••").assertIsDisplayed()+    }++    @Test fun legendAndMeasureSelector() {+        rule.setContent {+            Legend(com.vayunmathur.weather.domain.WeatherMetric.Temperature, "-20°", "40°")+            MeasureSelector(+                selected = com.vayunmathur.weather.domain.WeatherMetric.Temperature,+                options = com.vayunmathur.weather.domain.mapMetrics,+                onSelect = {},+            )+        }+        rule.onAllNodesWithText("Temperature")[0].assertIsDisplayed()+        rule.onNodeWithText("-20°").assertIsDisplayed()+        rule.onNodeWithText("40°").assertIsDisplayed()+    }++    @Test fun routeSerialization() {+        val json = Json { ignoreUnknownKeys = true }+        val home = json.encodeToString(Route.serializer(), Route.Home)+        assertEquals(Route.Home, json.decodeFromString(Route.serializer(), home))+        val map = Route.WeatherMap(52.5, 13.4, "Berlin", "2026-07-15T14:00", "Temperature")+        val decoded = json.decodeFromString(+            Route.serializer(), json.encodeToString(Route.serializer(), map),+        ) as Route.WeatherMap+        assertEquals("Berlin", decoded.name)+        assertEquals("Temperature", decoded.metric)+        assertEquals(Route.SearchLocation, json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.SearchLocation)))+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/DeviceLocationGrantedTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/DeviceLocationGrantedTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/DeviceLocationGrantedTest.ktnew file mode 100644index 0000000000..c28e049e98--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/DeviceLocationGrantedTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.weather.ui++import android.Manifest+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.platform.FakeRepository+import com.vayunmathur.weather.platform.WeatherViewModel+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(AndroidJUnit4::class)+class DeviceLocationGrantedTest {++    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++    @Test fun clickWithPermissionRunsFetchAndClearsLoading() {+        Shadows.shadowOf(rule.activity.application).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+        )+        // No enabled providers: currentLocation must return null at once+        // instead of parking on a one-shot listener that never fires.+        val lm = rule.activity.getSystemService(android.location.LocationManager::class.java)+        Shadows.shadowOf(lm).setProviderEnabled(android.location.LocationManager.GPS_PROVIDER, false)+        Shadows.shadowOf(lm).setProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER, false)+        runCatching {+            androidx.work.WorkManager.initialize(+                rule.activity.application, androidx.work.Configuration.Builder().build(),+            )+        }+        val vm = WeatherViewModel(rule.activity.application, FakeRepository(rule.activity.application))+        var pair: Pair<() -> Unit, Boolean>? = null+        rule.setContent { pair = rememberRequestDeviceLocation(vm) }+        pair!!.first()+        rule.waitForIdle()+        // No providers under Robolectric: the fetch completes with no fix and+        // the loading flag must clear again.+        var guard = 0+        while (pair!!.second && guard++ < 50) {+            Thread.sleep(20)+            rule.waitForIdle()+        }+        assertEquals(false, pair!!.second)+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/LocationsInteractionTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/LocationsInteractionTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/LocationsInteractionTest.ktnew file mode 100644index 0000000000..115e27c1b3--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/LocationsInteractionTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.weather.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.longClick+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.platform.LocationRow+import com.vayunmathur.weather.platform.LocationsUiState+import com.vayunmathur.weather.platform.WeatherActions+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class LocationsInteractionTest {++    @get:Rule val rule = createComposeRule()++    private fun loc(id: Long, name: String) = SavedLocation(+        id = id, name = name, country = "Germany", latitude = 52.5, longitude = 13.4,+    )++    @Test fun longPressOpensDeleteSheetAndConfirms() {+        var deleted: SavedLocation? = null+        val actions = object : WeatherActions {+            override fun deleteLocation(location: SavedLocation) { deleted = location }+        }+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(+                    rows = listOf(LocationRow(loc(1, "Berlin"), "No data yet", 2, true)),+                    activeLocationId = 1L,+                ),+                actions = actions,+            )+        }+        rule.onNodeWithText("Berlin").performTouchInput { longClick() }+        rule.waitForIdle()+        rule.onNodeWithText("Confirm delete").assertIsDisplayed()+        rule.onNodeWithText("Confirm delete").performClick()+        assertEquals("Berlin", deleted?.name)+    }++    @Test fun closeAndUnitsButtonsRender() {+        var closed = false+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(rows = emptyList()),+                actions = WeatherActions.Noop,+                onClose = { closed = true },+            )+        }+        rule.onNodeWithText("Units").assertIsDisplayed()+        assertTrue(!closed)+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.ktnew file mode 100644index 0000000000..c63d1f84e8--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.kt@@ -0,0 +1,31 @@+package com.vayunmathur.weather.ui++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.weather.Route+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test++@RunWith(AndroidJUnit4::class)+class MapPageTest {++    @get:Rule val rule = createComposeRule()++    @Test fun weatherMapPageRenders() {+        val backStack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent {+            WeatherMapPage(backStack, 52.5, 13.4, "2026-07-15T14:00", "Temperature")+        }+        rule.waitForIdle()+    }++    @Test fun weatherMapPageBadMetricRenders() {+        val backStack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent {+            WeatherMapPage(backStack, 0.0, 0.0, null, "bogus")+        }+        rule.waitForIdle()+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/MoreEdgesTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/MoreEdgesTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/MoreEdgesTest.ktnew file mode 100644index 0000000000..2e0f640699--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/MoreEdgesTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.weather.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.Hourly+import com.vayunmathur.weather.platform.FakeRepository+import com.vayunmathur.weather.platform.WeatherViewModel+import com.vayunmathur.weather.platform.reverseGeocodeName+import com.vayunmathur.weather.ui.components.DailyCard+import com.vayunmathur.weather.ui.components.HourlyCard+import kotlinx.coroutines.test.runTest+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++@RunWith(AndroidJUnit4::class)+class MoreEdgesTest {++    @get:Rule val rule = createComposeRule()++    private lateinit var vm: WeatherViewModel++    @BeforeTest fun setUp() {+        val app = ApplicationProvider.getApplicationContext<Application>()+        runCatching {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        }+        vm = WeatherViewModel(app, FakeRepository(app))+    }++    @Test fun reverseGeocodeReturnsNullWithoutBackend() = runTest {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        // Robolectric has no geocoder backend results: must be null, not throw.+        assertNull(reverseGeocodeName(ctx, 52.5, 13.4))+    }++    @Test fun deviceLocationHelperClickWithoutPermission() {+        var pair: Pair<() -> Unit, Boolean>? = null+        rule.setContent { pair = rememberRequestDeviceLocation(vm) }+        // No permission in Robolectric: the click routes to the permission+        // launcher; the helper must stay composed and not crash the test.+        runCatching { pair!!.first() }+        rule.waitForIdle()+        assertEquals(false, pair!!.second)+    }++    @Test fun dailyCardInvalidDateFallsBackToRaw() {+        val daily = Daily(+            time = listOf("bogus"),+            temperatureMax = listOf(20.0), temperatureMin = listOf(10.0),+            weatherCode = listOf(0), precipitationProbabilityMax = listOf(5),+        )+        rule.setContent { DailyCard(daily, TemperatureUnit.Celsius, null, {}, null) }+        rule.onNodeWithText("bogus").assertIsDisplayed()+    }++    @Test fun hourlyCardUnparseableTimesRenderNothing() {+        val hourly = Hourly(time = listOf("not-a-time"), temperature = listOf(1.0))+        rule.setContent { HourlyCard(hourly, TemperatureUnit.Celsius) }+        rule.onNodeWithText("Hourly forecast").assertDoesNotExist()+    }++    @Test fun dailyCardEmptyAndHourlyEmpty() {+        rule.setContent {+            DailyCard(Daily(), TemperatureUnit.Fahrenheit)+            HourlyCard(Hourly(time = listOf("2026-07-15T14:00"), temperature = listOf(25.0), weatherCode = listOf(0), isDay = listOf(1)), TemperatureUnit.Fahrenheit, 0, true, null, {}, null, "2026-07-15T14:00", 1760000000L)+        }+        rule.onNodeWithText("25°").assertDoesNotExist() // 25C = 77F+        rule.onNodeWithText("77°", substring = true).assertIsDisplayed()+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.ktnew file mode 100644index 0000000000..017652d922--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt@@ -0,0 +1,229 @@+package com.vayunmathur.weather.ui++import android.app.Application+import android.os.Looper+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.performTextInput+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.rememberCameraState+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.weather.Route+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.Hourly+import com.vayunmathur.weather.platform.FakeRepository+import com.vayunmathur.weather.platform.WeatherViewModel+import com.vayunmathur.weather.platform.rememberDisplayUnits+import com.vayunmathur.weather.ui.components.MainSearchBar+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.domain.WeatherMetric+import com.vayunmathur.weather.domain.map.OmMapMetadata+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class PagesTest {++    @get:Rule val rule = createComposeRule()++    private lateinit var app: Application+    private lateinit var repo: FakeRepository+    private lateinit var vm: WeatherViewModel++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        }+        repo = FakeRepository(app)+        vm = WeatherViewModel(app, repo)+    }++    private fun loc(id: Long = 1, name: String = "Berlin") = SavedLocation(+        id = id, name = name, country = "Germany", latitude = 52.5, longitude = 13.4,+    )++    private fun forecast() = ForecastResponse(+        latitude = 52.5, longitude = 13.4, utcOffsetSeconds = 0,+        current = Current(+            time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+            relativeHumidity = 50, dewPoint = 14.0, weatherCode = 2, windSpeed = 10.0,+            windDirection = 90, pressureMsl = 

Diff truncated.