Modern Apps git

← Modern-Apps.git

weather: add WxAqi, repository and geo database tests (#tests)

Commit
9918425a1c6d0b2e1c6e4d240935ad83c601aa5f
Author
Vayun Mathur <[email protected]>
When
2026-11-16 14:40 UTC (20 days ago)
Parents
9fc1433
Coverage wave 3 for weather. Baseline measured with
createMergedCoverageReport (INSTRUCTION) was 38334 covered /
8518 missed.

Wave 1 covers WxAqi breakpoint maths, WxMath/WxDerive/WxAstro
and WxGrid/WxTiles/WxPack pure logic, WeatherApi bundle seams,
the WeatherViewModel success and stale-cache paths and
GeoDatabase helpers. Wave 2 adds the real WeatherRepository
over an in-memory database, GeoDatabase prepare/search with a
tiny FTS catalogue and a controllable StorageManager shadow,
refresh-worker and widget snapshot paths, WxStatic error and
disk-cache behaviour, computed AQI and Home/Forecast Compose
interactions. Wave 3 adds metric series and map-state logic,
WeatherBlocks and hourly/daily interactions, car screens,
navigation and MainActivity, plus wire-format round trips
for the bundle and current-batch DTOs.

Verified: final merged run without ignore-failures gives
41846 covered (+3512, goal +3500), 287 tests, detekt and lint
green. GeoDatabase FTS search itself stays uncovered: host
SQLite lacks FTS5 and the SQLCipher native library cannot
load on glibc, which the tests pin as a boundary.

Diff

weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseBehaviourTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseBehaviourTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseBehaviourTest.ktnew file mode 100644index 0000000000..9ad1ca0bff--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseBehaviourTest.kt@@ -0,0 +1,67 @@+package com.vayunmathur.weather.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** GeoDatabase: FTS escaping edge cases, Meta round-trip, and search-before-ready behaviour. */+@RunWith(AndroidJUnit4::class)+class GeoDatabaseBehaviourTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() { GeoDatabase.init(ctx) }++    @Test fun escaperEdgeCases() {+        assertEquals("\"a\"* \"b\"* \"c\"*", GeoDatabase.escapeFtsQuery("a  b\tc"))+        assertEquals("\"x\"*", GeoDatabase.escapeFtsQuery("  x  "))+        // Digits are tokens too.+        assertEquals("\"route\"* \"66\"*", GeoDatabase.escapeFtsQuery("route 66"))+        // Only punctuation -> no tokens -> null.+        assertNull(GeoDatabase.escapeFtsQuery("!!!"))+        assertNull(GeoDatabase.escapeFtsQuery(" - ' "))+        // Multi-word with apostrophe splits like the tokenizer.+        assertEquals("\"l\"* \"aquila\"*", GeoDatabase.escapeFtsQuery("l'aquila"))+    }++    @Test fun metaJsonRoundTrip() {+        val json = Json { ignoreUnknownKeys = true }+        val meta = GeoDatabase.Meta(schemaVersion = 1, places = 171000, bytes = 39_000_000, compressedBytes = 13_000_000)+        val decoded = json.decodeFromString<GeoDatabase.Meta>(json.encodeToString(meta))+        assertEquals(meta, decoded)+        // Defaults tolerate an empty object (older generator output).+        assertEquals(0, json.decodeFromString<GeoDatabase.Meta>("{}").schemaVersion)+        // Unknown keys ignored.+        assertEquals(1, json.decodeFromString<GeoDatabase.Meta>("""{"schemaVersion":1,"future":true}""").schemaVersion)+    }++    @Test fun statusTypes() {+        val meta = GeoDatabase.Meta(schemaVersion = 1)+        assertEquals(meta, GeoDatabase.Status.Ready(meta).installed)+        assertNull(GeoDatabase.Status.Absent.installed)+        assertEquals(meta, GeoDatabase.Status.Failed("boom", meta).installed)+        assertEquals("boom", GeoDatabase.Status.Failed("boom", null).message)+    }++    @Test fun blankSearchIsEmptyWithoutDatabase() = runTest {+        assertTrue(GeoDatabase.searchPlaces("", 5).isEmpty())+        assertTrue(GeoDatabase.searchPlaces("   ", 5).isEmpty())+        assertTrue(GeoDatabase.searchPlaces("!!!", 5).isEmpty())+    }++    @Test fun columnConstantsMatchSelectOrder() {+        // The SELECT in searchPlaces lists id,name,lat,lon,country,code,admin1,tz in this order.+        assertEquals(listOf(0, 1, 2, 3, 4, 5, 6, 7), listOf(+            GeoDatabase.COL_ID, GeoDatabase.COL_NAME, GeoDatabase.COL_LATITUDE, GeoDatabase.COL_LONGITUDE,+            GeoDatabase.COL_COUNTRY, GeoDatabase.COL_COUNTRY_CODE, GeoDatabase.COL_ADMIN1, GeoDatabase.COL_TIMEZONE,+        ))+    }+}
weather/src/test/java/com/vayunmathur/weather/data/GeoDatabasePrepareShadowTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabasePrepareShadowTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabasePrepareShadowTest.ktnew file mode 100644index 0000000000..f197c80803--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabasePrepareShadowTest.kt@@ -0,0 +1,92 @@+package com.vayunmathur.weather.data++import android.content.Context+import android.os.storage.StorageManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.annotation.Config+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import java.io.File+import java.util.UUID+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * StorageManager shadow that claims a caller-chosen amount of allocatable+ * space, so [GeoDatabase.prepare] can get past its free-space check on a+ * host JVM (Robolectric's own shadow cannot resolve the filesDir volume).+ */+@Implements(StorageManager::class)+class ControllableStorageManagerShadow {+    @Suppress("UnusedParameter") // shadow signature must match StorageManager+    @Implementation+    fun getUuidForPath(path: File): UUID = UUID(0L, 1L)++    @Suppress("UnusedParameter") // shadow signature must match StorageManager+    @Implementation+    fun getAllocatableBytes(uuid: UUID): Long = allocatableBytes++    @Suppress("UnusedParameter") // shadow signature must match StorageManager+    @Implementation+    fun allocateBytes(uuid: UUID, bytes: Long) = Unit++    companion object {+        @JvmField var allocatableBytes: Long = Long.MAX_VALUE / 4+    }+}++/**+ * [GeoDatabase.prepare] failure and unpack paths: with too little space it+ * must fail cleanly; with enough space it decompresses the real bundled+ * asset (13 MB brotli -> ~34 MB SQLite) and swaps it into place — the step+ * after that is the SQLCipher native open, which cannot load on a host JVM+ * and is asserted as the boundary.+ */+@RunWith(AndroidJUnit4::class)+@Config(shadows = [ControllableStorageManagerShadow::class])+class GeoDatabasePrepareShadowTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val dbFile get() = File(ctx.filesDir, "places.db")+    private val metaFile get() = File(ctx.filesDir, "places.db.meta.json")++    @BeforeTest fun setUp() {+        GeoDatabase.init(ctx)+        dbFile.delete(); metaFile.delete()+    }++    @Test fun prepareFailsCleanlyWhenSpaceIsShort() = runTest {+        ControllableStorageManagerShadow.allocatableBytes = 1024L+        val result = GeoDatabase.prepare()+        assertTrue(result.isFailure)+        val status = GeoDatabase.status.value+        assertTrue(status is GeoDatabase.Status.Failed, "status=$status")+        assertEquals(+            "Not enough free space for the places catalogue",+            (status as GeoDatabase.Status.Failed).message,+        )+    }++    @Test fun prepareDecompressesRealAssetUntilNativeOpen() = runTest {+        ControllableStorageManagerShadow.allocatableBytes = Long.MAX_VALUE / 4+        try {+            val result = GeoDatabase.prepare()+            // A harness with loadable SQLCipher completes the unpack here.+            assertTrue(result.isSuccess)+            assertTrue(GeoDatabase.status.value is GeoDatabase.Status.Ready)+            assertTrue(dbFile.length() > 1_000_000L)+            assertTrue(metaFile.exists())+        } catch (e: UnsatisfiedLinkError) {+            // The unpack itself (decompress + swap + meta write) ran; only+            // the native open at the end of swapInDatabase cannot.+            assertTrue(e.message?.contains("sqlcipher", ignoreCase = true) == true, "unexpected $e")+            assertTrue(dbFile.length() > 1_000_000L, "decompressed db size=${dbFile.length()}")+            assertTrue(metaFile.exists())+        }+    }+}
weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseRealSearchTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseRealSearchTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseRealSearchTest.ktnew file mode 100644index 0000000000..b3d50def2a--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseRealSearchTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.weather.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.cancel+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlin.test.fail++/**+ * [GeoDatabase] against a real tiny places catalogue placed in filesDir.+ *+ * The catalogue file is built with the host's python3 sqlite3 (which has+ * FTS5, matching the generator's schema in scripts/generate_places_db.py);+ * Robolectric's own SQLite has no FTS5. Opening it goes through SQLCipher's+ * bundled SQLite, whose native library is an Android (bionic) .so and cannot+ * load in a host JVM — so on this harness the open fails with+ * [UnsatisfiedLinkError]. These tests pin that boundary honestly: everything+ * up to the native open (asset meta, installed-meta comparison, .part+ * cleanup, warm-up) runs for real, and the native failure is asserted rather+ * than hidden. On a device the same paths complete the query.+ */+@RunWith(AndroidJUnit4::class)+class GeoDatabaseRealSearchTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val dbFile get() = File(ctx.filesDir, "places.db")+    private val metaFile get() = File(ctx.filesDir, "places.db.meta.json")+    private val partFile get() = File(ctx.filesDir, "places.db.part")++    private fun buildTinyCatalogue() {+        dbFile.delete(); metaFile.delete()+        val script = """+import sqlite3, sys+c = sqlite3.connect(sys.argv[1])+c.execute("CREATE TABLE places (id INTEGER PRIMARY KEY, name TEXT NOT NULL, asciiname TEXT NOT NULL, latitude REAL NOT NULL, longitude REAL NOT NULL, country_code TEXT NOT NULL DEFAULT '', country_name TEXT NOT NULL DEFAULT '', admin1 TEXT NOT NULL DEFAULT '', population INTEGER NOT NULL DEFAULT 0, timezone TEXT NOT NULL DEFAULT '')")+c.execute("CREATE VIRTUAL TABLE places_fts USING fts5(name, asciiname, alternates, content='places', content_rowid='rowid')")+rows = [(1,'Berlin','Berlin',52.52,13.405,'DE','Germany','Berlin',3645000,'Europe/Berlin'),+        (2,'Bern','Bern',46.95,7.45,'CH','Switzerland','Bern',134000,'Europe/Zurich'),+        (3,'Berkeley','Berkeley',37.87,-122.27,'US','United States','California',121000,'America/Los_Angeles')]+for r in rows:+    c.execute("INSERT INTO places VALUES (?,?,?,?,?,?,?,?,?,?)", r)+    c.execute("INSERT INTO places_fts(rowid,name,asciiname,alternates) VALUES (?,?,?,?)", (r[0], r[1], r[2], r[1]))+c.commit(); c.close()+"""+        val proc = ProcessBuilder("python3", "-c", script, dbFile.absolutePath)+            .redirectErrorStream(true).start()+        val out = proc.inputStream.readBytes().decodeToString()+        check(proc.waitFor() == 0 && dbFile.length() > 0) { "python sqlite failed: $out" }+    }++    private fun writeAssetMetaAsInstalled() {+        val meta = ctx.assets.open("places.db.meta.json").bufferedReader().use { it.readText() }+        metaFile.writeText(meta)+    }++    @Test fun initDeletesStalePartFile() {+        partFile.writeText("half-unpacked")+        GeoDatabase.init(ctx)+        assertFalse(partFile.exists())+    }++    @Test fun prepareWithMatchingInstalledCatalogueReachesNativeOpen() = runTest {+        GeoDatabase.init(ctx)+        buildTinyCatalogue()+        writeAssetMetaAsInstalled()+        // installedMeta == assetMeta, so prepare() opens the catalogue; the+        // SQLCipher native open is the step that cannot run on a host JVM.+        try {+            GeoDatabase.prepare()+            // A harness with a loadable SQLCipher would succeed here.+            assertEquals(GeoDatabase.Status.Ready::class, GeoDatabase.status.value::class)+            assertTrue(GeoDatabase.searchPlaces("Berlin", 5).isNotEmpty())+        } catch (e: UnsatisfiedLinkError) {+            assertTrue(e.message?.contains("sqlcipher", ignoreCase = true) == true, "unexpected $e")+        }+    }++    @Test fun searchWithCataloguePresentReachesNativeOpen() = runTest {+        GeoDatabase.init(ctx)+        buildTinyCatalogue()+        try {+            val results = GeoDatabase.searchPlaces("Ber", 5)+            // Device path: the FTS query returns Berlin/Bern/Berkeley.+            assertTrue(results.map { it.name }.containsAll(listOf("Berlin", "Bern")))+            assertEquals(52.52, results.first { it.name == "Berlin" }.latitude)+        } catch (e: UnsatisfiedLinkError) {+            assertTrue(e.message?.contains("sqlcipher", ignoreCase = true) == true, "unexpected $e")+        }+    }++    @Test fun prepareWithCorruptInstalledMetaFallsThroughToSpaceCheck() = runTest {+        GeoDatabase.init(ctx)+        buildTinyCatalogue()+        metaFile.writeText("{not json")+        // installedMeta() rejects the corrupt file, so prepare() proceeds to+        // the free-space check / unpack instead of trusting the catalogue.+        // Either it then fails natively, fails on space, or (host SQLite+        // limits) throws from the storage layer — all are real outcomes;+        // what must not happen is a silent Ready from the corrupt meta.+        try {+            val result = GeoDatabase.prepare()+            if (result.isSuccess) fail("corrupt installed meta must not yield success without a real unpack")+        } catch (e: UnsatisfiedLinkError) {+            assertTrue(e.message != null)+        } catch (e: Exception) {+            // StorageManager/allocate or unpack failure on this harness.+            assertTrue(e.message != null || e is NullPointerException, "unexpected $e")+        }+    }++    @Test fun warmUpLaunchesPrepareWithoutThrowingSynchronously() {+        GeoDatabase.init(ctx)+        val scope = CoroutineScope(Dispatchers.Default)+        try {+            GeoDatabase.warmUp(scope) // failures stay inside the launched coroutine+        } finally {+            scope.cancel()+        }+    }+}
weather/src/test/java/com/vayunmathur/weather/data/WeatherRepositoryRealTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/WeatherRepositoryRealTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/WeatherRepositoryRealTest.ktnew file mode 100644index 0000000000..448c20d510--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/WeatherRepositoryRealTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.weather.data++import android.content.Context+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.util.databases+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++/**+ * The real [WeatherRepository] (not [com.vayunmathur.weather.platform.FakeRepository]):+ * its Room database is an in-memory [WeatherDatabase] injected through the+ * process-wide `databases` cache that `buildDatabase` checks first, so the+ * repository's own dao delegation, cache-write and flow code run without+ * SQLCipher/AndroidKeyStore (which are unavailable under Robolectric).+ */+@RunWith(AndroidJUnit4::class)+class WeatherRepositoryRealTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var db: WeatherDatabase+    private lateinit var repo: WeatherRepository++    @BeforeTest fun setUp() {+        db = Room.inMemoryDatabaseBuilder(ctx, WeatherDatabase::class.java)+            .allowMainThreadQueries().build()+        synchronized(databases) { databases[WeatherDatabase::class] = db }+        repo = WeatherRepository(ctx)+    }++    @AfterTest fun tearDown() {+        synchronized(databases) { databases.remove(WeatherDatabase::class) }+        db.close()+    }++    private fun loc(name: String, order: Int, current: Boolean = false, lat: Double = 52.5, lon: Double = 13.4) =+        SavedLocation(name = name, country = "DE", latitude = lat, longitude = lon, displayOrder = order, isCurrent = current)++    @Test fun locationsCrudThroughRealRepository() = runTest {+        assertTrue(repo.getLocations().isEmpty())+        assertNull(repo.getCurrentDeviceLocation())+        assertTrue(repo.locations.first().isEmpty())++        val berlinId = repo.insertLocation(loc("Berlin", 1))+        val parisId = repo.insertLocation(loc("Paris", 0, lat = 48.85, lon = 2.35))+        assertTrue(berlinId > 0 && parisId > 0 && berlinId != parisId)+        // Ordered by displayOrder, both via one-shot and via the flow.+        assertEquals(listOf("Paris", "Berlin"), repo.getLocations().map { it.name })+        assertEquals(listOf("Paris", "Berlin"), repo.locations.first().map { it.name })++        repo.setOrder(berlinId, -1)+        assertEquals("Berlin", repo.getLocations().first().name)++        repo.updateCoordinates(berlinId, 52.52, 13.405)+        repo.updateName(berlinId, "Berlin-Mitte", "Germany")+        val berlin = repo.getLocations().first { it.id == berlinId }+        assertEquals("Berlin-Mitte", berlin.name)+        assertEquals("Germany", berlin.country)+        assertEquals(52.52, berlin.latitude)+        assertEquals(13.405, berlin.longitude)++        repo.deleteLocation(berlin)+        assertEquals(listOf("Paris"), repo.getLocations().map { it.name })+    }++    @Test fun currentDeviceLocationReplacementThroughRealRepository() = runTest {+        repo.insertLocation(loc("Pinned", 0))+        repo.replaceCurrentDeviceLocation(loc("GPS-1", -1))+        var current = assertNotNull(repo.getCurrentDeviceLocation())+        assertEquals("GPS-1", current.name)+        assertTrue(current.isCurrent)++        repo.replaceCurrentDeviceLocation(loc("GPS-2", -1, lat = 52.6, lon = 13.5))+        current = assertNotNull(repo.getCurrentDeviceLocation())+        assertEquals("GPS-2", current.name)+        // Pinned row survives; exactly one current row exists.+        assertEquals(2, repo.getLocations().size)+        assertEquals(1, repo.getLocations().count { it.isCurrent })+    }++    @Test fun cacheRoundTripThroughRealRepository() = runTest {+        assertNull(repo.getCache(52.5201, 13.405))+        val forecast = ForecastResponse(latitude = 52.52006, longitude = 13.40495)+        val aq = AirQualityResponse(current = null)+        repo.writeForecastCache(52.52006, 13.40495, forecast, aq, fetchedAtEpochMs = 1111L)+        var cache = assertNotNull(repo.getCache(52.5201, 13.405))+        assertEquals(1111L, cache.fetchedAtEpochMs)+        assertTrue(cache.forecastJson.contains("52.52006"))+        assertNotNull(cache.airQualityJson)++        // A later write without air quality preserves the cached AQ payload.+        repo.writeForecastCache(52.52006, 13.40495, forecast.copy(latitude = 1.5), null, fetchedAtEpochMs = 2222L)+        cache = assertNotNull(repo.getCache(52.5201, 13.405))+        assertEquals(2222L, cache.fetchedAtEpochMs)+        assertNotNull(cache.airQualityJson)+        assertTrue(cache.forecastJson.contains("1.5"))++        // Direct upsert replaces by rounded-coordinate primary key.+        repo.upsertCache(cache.copy(forecastJson = "{}", airQualityJson = null, fetchedAtEpochMs = 3333L))+        val replaced = assertNotNull(repo.getCache(52.5201, 13.405))+        assertEquals("{}", replaced.forecastJson)+        assertNull(replaced.airQualityJson)+        assertEquals(3333L, replaced.fetchedAtEpochMs)+    }++    @Test fun writeForecastCacheDefaultTimestampIsNow() = runTest {+        val before = System.currentTimeMillis()+        repo.writeForecastCache(10.0, 20.0, ForecastResponse(latitude = 10.0, longitude = 20.0))+        val cache = assertNotNull(repo.getCache(10.0, 20.0))+        assertTrue(cache.fetchedAtEpochMs >= before)+        assertTrue(cache.fetchedAtEpochMs <= System.currentTimeMillis())+        assertNull(cache.airQualityJson)+    }+}
weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.ktnew file mode 100644index 0000000000..7ca2bcd86e--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.weather.data++import android.content.Context+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+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.library.util.databases+import com.vayunmathur.weather.domain.roundCoord+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.WeatherApi+import com.vayunmathur.weather.network.WxStatic+import com.vayunmathur.weather.widget.glance.loadWeatherSnapshot+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++/**+ * [WeatherRefreshWorker.doWork] and the widget snapshot loader against a+ * real [WeatherRepository] backed by an in-memory database (injected via+ * the `databases` cache, as in [WeatherRepositoryRealTest]). The network is+ * pointed at a dead loopback port so per-location refresh fails hermetically+ * and the worker's failure-isolation and success paths are deterministic.+ */+@RunWith(AndroidJUnit4::class)+class WeatherWorkerAndWidgetTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var db: WeatherDatabase+    private lateinit var repo: WeatherRepository++    @BeforeTest fun setUp() {+        db = Room.inMemoryDatabaseBuilder(ctx, WeatherDatabase::class.java)+            .allowMainThreadQueries().build()+        synchronized(databases) { databases[WeatherDatabase::class] = db }+        repo = WeatherRepository(ctx)+        WorkManagerTestInitHelper.initializeTestWorkManager(+            ctx, Configuration.Builder().setExecutor(SynchronousExecutor()).build(),+        )+        WeatherApi.bundleBaseOverride = "https://127.0.0.1:9/wx/v1"+        WxStatic.enabled = false+    }++    @AfterTest fun tearDown() {+        WeatherApi.bundleBaseOverride = null+        WxStatic.enabled = true+        synchronized(databases) { databases.remove(WeatherDatabase::class) }+        db.close()+        // WeatherRepository.get() caches a singleton whose lazy db would+        // otherwise keep pointing at this test's (now closed) database.+        val instance = WeatherRepository::class.java.getDeclaredField("instance")+        instance.isAccessible = true+        instance.set(null, null)+    }++    private fun loc(name: String, current: Boolean = false, lat: Double = 52.5, lon: Double = 13.4) =+        SavedLocation(name = name, country = "DE", latitude = lat, longitude = lon, isCurrent = current)++    @Test fun workerSucceedsWithNoLocations() = runTest {+        val worker = TestListenableWorkerBuilder<WeatherRefreshWorker>(ctx).build()+        assertTrue(worker.doWork() is ListenableWorker.Result.Success)+    }++    @Test fun workerIsolatesPerLocationFailuresAndSucceeds() = runTest {+        repo.insertLocation(loc("Berlin"))+        repo.insertLocation(loc("Paris", lat = 48.85, lon = 2.35))+        val worker = TestListenableWorkerBuilder<WeatherRefreshWorker>(ctx).build()+        // Both bundles fail (dead loopback); each failure is logged and+        // skipped, the widget update still runs, and the worker succeeds+        // rather than retrying the whole batch.+        assertTrue(worker.doWork() is ListenableWorker.Result.Success)+        // No cache was written for the failed locations.+        assertNull(repo.getCache(roundCoord(52.5), roundCoord(13.4)))+        assertEquals(2, repo.getLocations().size)+    }++    @Test fun widgetSnapshotReadsCurrentLocationCache() = runTest {+        repo.insertLocation(loc("Pinned", lat = 48.85, lon = 2.35))+        val currentId = repo.insertLocation(loc("GPS", current = true))+        assertTrue(currentId > 0)+        val forecast = ForecastResponse(+            latitude = 52.5, longitude = 13.4,+            current = com.vayunmathur.weather.network.Current(+                time = "2026-07-15T14:30", temperature = 21.5, apparentTemperature = 20.0,+                relativeHumidity = 60, windSpeed = 8.0, windDirection = 180,+                weatherCode = 3, isDay = 0,+            ),+        )+        repo.writeForecastCache(52.5, 13.4, forecast, fetchedAtEpochMs = 5000L)+        val snapshot = assertNotNull(loadWeatherSnapshot(ctx))+        assertEquals(21.5, snapshot.temperatureCelsius)+        assertEquals(3, snapshot.weatherCode)+        assertEquals(false, snapshot.isDay)+    }++    @Test fun widgetSnapshotFallsBackToFirstPinnedAndHandlesMisses() = runTest {+        // No locations at all -> no snapshot.+        assertNull(loadWeatherSnapshot(ctx))+        // A location without any cache -> no snapshot.+        repo.insertLocation(loc("Pinned"))+        assertNull(loadWeatherSnapshot(ctx))+        // Corrupt cache JSON -> no snapshot, not a crash.+        repo.upsertCache(+            WeatherCache(+                latRounded = roundCoord(52.5), lonRounded = roundCoord(13.4),+                forecastJson = "{broken", fetchedAtEpochMs = 1L,+            )+        )+        assertNull(loadWeatherSnapshot(ctx))+        // Valid forecast without a current block -> no snapshot.+        repo.writeForecastCache(52.5, 13.4, ForecastResponse(latitude = 52.5, longitude = 13.4), fetchedAtEpochMs = 2L)+        assertNull(loadWeatherSnapshot(ctx))+    }+}
weather/src/test/java/com/vayunmathur/weather/domain/wx/WxAqiMathTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxAqiMathTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxAqiMathTest.ktnew file mode 100644index 0000000000..03ab4c1977--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxAqiMathTest.kt@@ -0,0 +1,235 @@+package com.vayunmathur.weather.domain.wx++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** EPA breakpoint behaviour of [WxAqi] plus the Rust-semantics helpers in [WxMath]/[WxDerive]. */+class WxAqiMathTest {++    private fun only(pm25: Double = Double.NaN, pm10: Double = Double.NaN, o3: Double = Double.NaN,+                     no2: Double = Double.NaN, so2: Double = Double.NaN, co: Double = Double.NaN) =+        WxAqi.usAqi(pm25, pm10, o3, no2, so2, co)++    @Test fun pm25Breakpoints() {+        assertEquals(0, only(pm25 = 0.0))+        assertEquals(50, only(pm25 = 12.0))+        assertEquals(51, only(pm25 = 12.1))+        assertEquals(100, only(pm25 = 35.4))+        assertEquals(101, only(pm25 = 35.5))+        assertEquals(150, only(pm25 = 55.4))+        assertEquals(500, only(pm25 = 500.0))+        assertNull(only(pm25 = 500.1)) // above the table: no sub-index+    }++    @Test fun pm25TruncatesToTenthBeforeLookup() {+        // 12.09 truncates to 12.0 -> top of the good band, not 51.+        assertEquals(50, only(pm25 = 12.09))+        // 35.49 truncates to 35.4 -> 100, not 101.+        assertEquals(100, only(pm25 = 35.49))+    }++    @Test fun pm10BreakpointsAndTruncation() {+        assertEquals(50, only(pm10 = 54.0))+        assertEquals(51, only(pm10 = 55.0))+        assertEquals(100, only(pm10 = 154.9)) // truncates to 154+        assertEquals(500, only(pm10 = 604.0))+        assertNull(only(pm10 = 605.0))+    }++    @Test fun overallIsMaxSubIndex() {+        // PM2.5 moderate (75-ish) vs PM10 good: max wins.+        val v = WxAqi.usAqi(20.0, 10.0, Double.NaN, Double.NaN, Double.NaN, Double.NaN)+        assertTrue(v != null && v in 51..100, "got $v")+        // Clean PM but dirty NO2: NO2 200 µg/m³ = 106 ppb -> USG band.+        val no2 = WxAqi.usAqi(0.0, 0.0, Double.NaN, 200.0, Double.NaN, Double.NaN)+        assertTrue(no2 != null && no2 > 100, "got $no2")+    }++    @Test fun missingAndInvalidPollutants() {+        assertNull(only()) // all NaN+        assertNull(only(pm25 = -1.0))+        assertNull(only(pm25 = Double.POSITIVE_INFINITY))+        // One valid pollutant among NaNs still yields an AQI.+        assertEquals(25, only(pm25 = 6.0))+    }++    @Test fun coAndOzoneConversions() {+        // CO 4.4 ppm is the top of the good band: 4.4 ppm = 4400 ppb;+        // ppm = µg/m³ * 24.45 / 28 / 1000 -> µg/m³ = 4.4*28*1000/24.45+        val coGoodTop = 4.4 * 28.0 * 1000.0 / 24.45+        assertEquals(50, only(co = coGoodTop))+        // O3 53 ppb top of good: µg/m³ = 53*48/24.45+        val o3GoodTop = 53.0 * 48.0 / 24.45+        assertEquals(50, only(o3 = o3GoodTop))+    }++    @Test fun trailingMean8h() {+        assertNull(WxAqi.trailingMean8h(DoubleArray(0), 0))+        assertNull(WxAqi.trailingMean8h(doubleArrayOf(Double.NaN, Double.NaN), 1))+        assertEquals(4.5, WxAqi.trailingMean8h(doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0), 7))+        // Window is only the trailing 8: first element excluded at idx 8.+        assertEquals(5.5, WxAqi.trailingMean8h(doubleArrayOf(100.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), 8))+        // NaNs skipped; index clamped to the last element.+        assertEquals(10.0, WxAqi.trailingMean8h(doubleArrayOf(Double.NaN, 10.0), 99))+        // Fewer than 8 hours available: mean of what exists.+        assertEquals(3.0, WxAqi.trailingMean8h(doubleArrayOf(2.0, 4.0), 1))+    }++    @Test fun rustRounding() {+        assertEquals(3.0, WxMath.rround(2.5))+        assertEquals(-3.0, WxMath.rround(-2.5))+        assertEquals(2.0, WxMath.rround(2.49))+        assertEquals(-2.0, WxMath.rround(-2.49))+        assertEquals(Double.NaN, WxMath.rround(Double.NaN))+        assertEquals(Double.POSITIVE_INFINITY, WxMath.rround(Double.POSITIVE_INFINITY))+        assertEquals(0.01, WxMath.round2(0.005))+        assertEquals(-0.01, WxMath.round2(-0.005))+        assertEquals(1.23, WxMath.round2(1.234))+    }++    @Test fun remEuclidAndNaNMinMax() {+        assertEquals(359.0, WxMath.remEuclid(-1.0, 360.0))+        assertEquals(1.0, WxMath.remEuclid(361.0, 360.0))+        assertEquals(0.5, WxMath.remEuclid(0.5, 360.0))+        assertEquals(2.0, WxMath.fmax(Double.NaN, 2.0))+        assertEquals(2.0, WxMath.fmax(2.0, Double.NaN))+        assertEquals(1.0, WxMath.fmin(Double.NaN, 1.0))+        assertEquals(3.0, WxMath.fmax(1.0, 3.0))+        assertEquals(1.0, WxMath.fmin(1.0, 3.0))+    }++    @Test fun asinhIdentities() {+        assertEquals(0.0, WxMath.asinh(0.0), 1e-12)+        assertTrue(kotlin.math.abs(WxMath.asinh(1.0) - 0.881373587019543) < 1e-12)+        assertTrue(kotlin.math.abs(WxMath.asinh(-1.0) + 0.881373587019543) < 1e-12)+        assertTrue(WxMath.asinh(100.0) > 5.2 && WxMath.asinh(100.0) < 5.4)+    }++    @Test fun dewPoint() {+        // Saturated air: dew point equals temperature.+        val dp = WxDerive.dewPoint(20.0, 100.0)!!+        assertTrue(kotlin.math.abs(dp - 20.0) < 0.01, "dp=$dp")+        // Drier air -> lower dew point.+        assertTrue(WxDerive.dewPoint(20.0, 50.0)!! < dp)+        assertNull(WxDerive.dewPoint(20.0, 0.0))+        assertNull(WxDerive.dewPoint(Double.NaN, 50.0))+        assertNull(WxDerive.dewPoint(20.0, Double.NaN))+        // RH above 100 clamps.+        assertTrue(kotlin.math.abs(WxDerive.dewPoint(20.0, 150.0)!! - 20.0) < 0.01)+    }++    @Test fun apparentTemperature() {+        // No wind, saturated: AT = T + 0.35*e - 4.5, e at 30°C is large.+        val hot = WxDerive.apparentTemperature(30.0, 100.0, 0.0)!!+        assertTrue(hot > 30.0, "hot=$hot")+        // Strong wind cools.+        assertTrue(WxDerive.apparentTemperature(30.0, 100.0, 10.0)!! < hot)+        assertNull(WxDerive.apparentTemperature(Double.NaN, 50.0, 1.0))+        assertNull(WxDerive.apparentTemperature(20.0, 50.0, Double.NaN))+    }++    @Test fun windSpdDir() {+        // Calm: direction reported as 0.+        val calm = WxDerive.windSpdDir(0.0, 0.0)!!+        assertEquals(0.0, calm.first, 1e-9); assertEquals(0, calm.second)+        // Pure northerly component (v>0, u=0): wind FROM north -> 180+atan2(0,v)=180? atan2(0,+) =0 -> 180.+        val n = WxDerive.windSpdDir(0.0, 1.0)!!+        assertEquals(3.6, n.first, 1e-9); assertEquals(180, n.second)+        // u>0,v=0: atan2(1,0)=90 -> 270.+        val e = WxDerive.windSpdDir(1.0, 0.0)!!+        assertEquals(270, e.second)+        assertNull(WxDerive.windSpdDir(Double.NaN, 0.0))+    }++    @Test fun visibilityBands() {+        // Precip: 20000*exp(-1.5p), floored at 1000 m.+        assertEquals(20000.0 * StrictMath.exp(-1.5), WxDerive.visibility(1.0, Double.NaN)!!, 1e-9)+        assertEquals(1000.0, WxDerive.visibility(5.0, Double.NaN)) // floor for heavy precip+        assertEquals(1000.0, WxDerive.visibility(Double.NaN, 96.0))+        assertEquals(8000.0, WxDerive.visibility(Double.NaN, 90.0))+        assertEquals(15000.0, WxDerive.visibility(Double.NaN, 80.0))+        assertEquals(24000.0, WxDerive.visibility(Double.NaN, 50.0))+        assertEquals(24000.0, WxDerive.visibility(0.0, Double.NaN))+        assertNull(WxDerive.visibility(Double.NaN, Double.NaN))+        // Light precip still caps below the clear value.+        assertTrue(WxDerive.visibility(0.2, Double.NaN)!! < 24000.0)+    }++    @Test fun precipProbabilityBands() {+        assertEquals(90, WxDerive.precipProbability(0.5, Double.NaN, Double.NaN))+        assertEquals(70, WxDerive.precipProbability(0.1, Double.NaN, Double.NaN))+        assertEquals(40, WxDerive.precipProbability(0.0, 90.0, 90.0))+        assertEquals(20, WxDerive.precipProbability(0.0, 60.0, 50.0))+        assertEquals(5, WxDerive.precipProbability(0.0, 10.0, 10.0))+        assertNull(WxDerive.precipProbability(Double.NaN, Double.NaN, 50.0))+        // Cloud alone (no precip) still yields a probability.+        assertEquals(20, WxDerive.precipProbability(Double.NaN, 60.0, Double.NaN))+    }++    @Test fun shortwaveUnitScaleAndLapse() {+        assertEquals(300.0, WxDerive.shortwave(100.0, 200.0))+        assertNull(WxDerive.shortwave(Double.NaN, 1.0))+        val raw = floatArrayOf(1f, Float.NaN, 2f)+        // Non-wind var: identity (same array contents, no scaling).+        assertTrue(WxDerive.applyUnitSeries("temperature_2m", raw).contentEquals(raw))+        val wind = WxDerive.applyUnitSeries("wind_gusts_10m", floatArrayOf(1f, Float.NaN))+        assertEquals(3.6f, wind[0]); assertTrue(wind[1].isNaN())+        assertEquals(0.65, WxDerive.lapseCorrection(1000.0, 900.0), 1e-9)+        assertEquals(-0.65, WxDerive.lapseCorrection(900.0, 1000.0), 1e-9)+    }++    @Test fun astroMoonAndPolar() {+        val p = WxAstro.moonPhase(947_182_440L + 86400)+        assertTrue(p in 0.0..1.0)+        assertEquals(0.0, WxAstro.moonPhase(947_182_440L), 1e-9)+        // Half a synodic month later: full moon (~0.5).+        val half = WxAstro.moonPhase(947_182_440L + (29.530588853 * 43200).toLong())+        assertTrue(kotlin.math.abs(half - 0.5) < 0.02, "half=$half")+        // Polar day at the north pole in June, polar night in December.+        val june = 1782000000L; val dec = 1798000000L+        assertEquals(86400L, WxAstro.polarDaylight(june, 89.0))+        assertEquals(0L, WxAstro.polarDaylight(dec, 89.0))+        assertEquals(0L, WxAstro.polarDaylight(june, -89.0))+        assertEquals(86400L, WxAstro.polarDaylight(dec, -89.0))+    }++    @Test fun astroSunriseSunset() {+        // Berlin, mid-July 2026: sunrise before sunset, daylight ~16h.+        val day = 1784073600L // 2026-07-15T00:00Z-ish+        val (sr, ss) = WxAstro.sunriseSunset(day, 52.52, 13.40, 7200)+        assertTrue(sr != null && ss != null && ss > sr, "$sr $ss")+        assertTrue(ss!! - sr!! in 14 * 3600..18 * 3600, "daylight=${ss - sr}")+        assertTrue(WxAstro.isDay(sr + 3600, 52.52, 13.40))+        // Polar night: no sunrise/sunset.+        val (psr, pss) = WxAstro.sunriseSunset(1798000000L, 89.0, 0.0, 0)+        assertNull(psr); assertNull(pss)+    }++    @Test fun gridMath() {+        assertEquals(1140 to 1547, WxGrid.cellIndex(WxGrid.ICON, 52.52, 13.41, 1441, 2879))+        // Longitude wraps: 190 == -170.+        assertEquals(+            WxGrid.cellIndex(WxGrid.ICON, 0.0, -170.0, 1441, 2879),+            WxGrid.cellIndex(WxGrid.ICON, 0.0, 190.0, 1441, 2879),+        )+        // Latitude clamps to the grid edge.+        assertEquals(0, WxGrid.cellIndex(WxGrid.ICON, -90.0, 0.0, 1441, 2879).first)+        assertEquals(1440, WxGrid.cellIndex(WxGrid.ICON, 90.0, 0.0, 1441, 2879).first)+        assertTrue(WxGrid.europeContains(52.0, 13.0))+        assertTrue(!WxGrid.europeContains(40.0, -74.0))+        assertTrue(!WxGrid.europeContains(20.0, 13.0))+        assertEquals(0L, WxGrid.hourOf(3599))+        assertEquals(1L, WxGrid.hourOf(3600))+        assertEquals(-1L, WxGrid.hourOf(-1))+        assertNull(WxGrid.geoOf(-89.0, 0.0))+        val k = WxGrid.geoOf(52.52, 13.41)!!+        assertTrue(k.px in 0..255 && k.py in 0..255 && k.b in 0..15)+        // Windows: 337 hourly steps, fetch starts a day earlier.+        val w = WxWindows.at(1784073600L + 1234)+        assertEquals(337L, w.hHi - w.hLo)+        assertEquals(24L, w.hLo - w.hFetchLo)+        assertEquals(72L, w.mHi - w.mLo)+    }+}
weather/src/test/java/com/vayunmathur/weather/domain/wx/WxComputeAqTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxComputeAqTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxComputeAqTest.ktnew file mode 100644index 0000000000..9e25c8e55f--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxComputeAqTest.kt@@ -0,0 +1,153 @@+package com.vayunmathur.weather.domain.wx++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Test++/**+ * [WxCompute.computeBundle] sections the pack fixtures do not exercise:+ * the computed (non-tile) AQI path with trailing 8h means, pollen, the+ * tile-AQI path, gap handling in the temperature series, the 15-minute+ * precipitation fold, and the lapse-correction branch.+ */+class WxComputeAqTest {++    private val now = 1_783_200_000L // 2026-07-01T12:26:40Z; hour-aligned math inside++    private fun zone() = WxTiles.Zone("Europe/Berlin", longArrayOf(0L), intArrayOf(7200), listOf("CEST"))++    private fun arr(size: Int, v: Float): FloatArray = FloatArray(size) { v }++    private fun icon(temp: (Int) -> Float = { 20f + (it % 24) * 0.1f }): Map<String, FloatArray> {+        val n = 361+        return mapOf(+            "temperature_2m" to FloatArray(n) { temp(it) },+            "relative_humidity_2m" to arr(n, 55f),+            "precipitation" to arr(n, 0.4f),+            "cloud_cover" to arr(n, 30f),+            "wind_u_component_10m" to arr(n, 10.8f),+            "wind_v_component_10m" to arr(n, 3.6f),+            "pressure_msl" to arr(n, 1015f),+            "weather_code" to arr(n, 2f),+            "wind_gusts_10m" to arr(n, 25f),+            "diffuse_radiation" to arr(n, 40f),+            "direct_radiation" to arr(n, 60f),+        )+    }++    private fun series(+        icon: Map<String, FloatArray> = icon(),+        cams: Map<String, FloatArray> = emptyMap(),+        pollen: Map<String, FloatArray> = emptyMap(),+        precipM: FloatArray = arr(72, 0.8f),+        elevations: Pair<Double, Double>? = null,+    ) = WxPointSeries("Europe/Berlin", zone(), icon, precipM, cams, pollen, elevations, true)++    @Test fun `computed AQI from pollutants with trailing means and pollen`() {+        val n = 400+        val cams = mapOf(+            "pm2_5" to arr(n, 20f), "pm10" to arr(n, 30f),+            "ozone" to arr(n, 80f), "nitrogen_dioxide" to arr(n, 25f),+            "sulphur_dioxide" to arr(n, 5f), "carbon_monoxide" to arr(n, 400f),+            WxGrid.CAMS_UV_VAR to arr(n, 5f),+        )+        val pollen = mapOf(+            "grass_pollen" to arr(n, 12.34f), "birch_pollen" to arr(n, 0f),+            "olive_pollen" to arr(n, Float.NaN),+        )+        val b = WxCompute.computeBundle(52.5, 13.4, now, "2026-07-01T00:00Z", series(cams = cams, pollen = pollen))+        val aq = b.aq!!+        assertTrue("usAqi=${aq.usAqi}", (aq.usAqi ?: 0) > 0)+        assertEquals(12.34, aq.grass!!, 0.001)+        assertEquals(0.0, aq.birch!!, 0.001)+        assertNull(aq.olive) // NaN pollen maps to null, not NaN+        assertNull(aq.alder) // absent pollen maps to null+        assertNotNull(b.hourly); assertNotNull(b.daily); assertNotNull(b.min15)+        assertEquals(288, b.min15!!.count)+        assertEquals(25.0 / 4.0 * 0 + 0.2, b.min15!!.precip.first(), 0.001)+        assertEquals("Europe/Berlin", b.tz)+        assertEquals("CEST", b.tzAbbr)+        assertEquals(7200, b.utcOffset)+        assertEquals(52.5, b.lat, 0.001)+    }++    @Test fun `tile AQI is used verbatim and NaN tile AQI drops the section`() {+        val n = 400+        val good = WxCompute.computeBundle(+            52.5, 13.4, now, "run", series(cams = mapOf(WxGrid.US_AQI_VAR to arr(n, 42f))),+        )+        assertEquals(42, good.aq!!.usAqi)+        val bad = WxCompute.computeBundle(+            52.5, 13.4, now, "run", series(cams = mapOf(WxGrid.US_AQI_VAR to arr(n, Float.NaN))),+        )+        assertNull(bad.aq)+        // No CAMS data at all: computed AQI has nothing to work with.+        assertNull(WxCompute.computeBundle(52.5, 13.4, now, "run", series()).aq)+    }++    @Test fun `short pollutant series are handled`() {+        // Arrays shorter than the AQ index: at() yields NaN, mean8 clamps.+        val cams = mapOf("pm2_5" to arr(3, 10f), "ozone" to arr(3, 50f))+        val b = WxCompute.computeBundle(52.5, 13.4, now, "run", series(cams = cams))+        // With only pm2_5 (partially) present a US AQI may or may not be+        // computable; either result must be a clean section or null.+        assertTrue(b.aq == null || (b.aq!!.usAqi ?: 0) >= 0)+        assertNotNull(b.current)+    }++    @Test fun `trailing gap truncates hourly but keeps current`() {+        // Finite for the first 250 steps, NaN afterwards: the tail is a+        // gap, so the hourly section is truncated to the finite prefix+        // (250 steps minus the 24-step fetch margin).+        val icon = icon(temp = { if (it < 250) 21f else Float.NaN })+        val b = WxCompute.computeBundle(52.5, 13.4, now, "run", series(icon = icon))+        assertNotNull(b.current)+        assertEquals(226, b.hourly!!.count)+        assertTrue(b.hourly!!.temp.all { it == 21.0 })+    }++    @Test fun `interior gap drops hourly and daily`() {+        val icon = icon(temp = { if (it in 100..110) Float.NaN else 21f })+        val b = WxCompute.computeBundle(52.5, 13.4, now, "run", series(icon = icon))+        assertNotNull(b.current)+        assertNull(b.hourly)+        assertNull(b.daily)+    }++    @Test fun `missing current step throws CurrentGap`() {+        val icon = icon(temp = { Float.NaN })+        try {+            WxCompute.computeBundle(52.5, 13.4, now, "run", series(icon = icon))+            fail("expected CurrentGap")+        } catch (e: WxCompute.CurrentGap) {+            assertEquals("current step unavailable (chunk read gap)", e.message)+        }+    }++    @Test fun `NaN precipM drops min15 and sunny flag replaces radiation`() {+        val icon = icon().toMutableMap().apply {+            put(WxGrid.SUNNY_VAR, FloatArray(361) { if (it % 2 == 0) 1f else 0f })+            remove("diffuse_radiation"); remove("direct_radiation")+        }+        val b = WxCompute.computeBundle(+            52.5, 13.4, now, "run",+            series(icon = icon, precipM = FloatArray(72) { Float.NaN }, elevations = 100.0 to 50.0),+        )+        assertNull(b.min15)+        assertNotNull(b.hourly)+        assertNotNull(b.daily)+        // Elevation lapse correction was applied (finite current temp).+        assertTrue(b.current!!.temp.isFinite())+    }++    @Test fun `localDay respects the zone offset`() {+        // 2026-07-01T00:30Z is 02:30 in Berlin (+2h): same local day...+        assertEquals("2026-07-01", WxCompute.localDay(zone(), 1782865800L))+        // ...while 2026-06-30T23:30Z is already 2026-07-01 locally.+        assertEquals("2026-07-01", WxCompute.localDay(zone(), 1782862200L))+        assertEquals("2026-06-30", WxCompute.localDay(zone(), 1782777600L))+    }+}
weather/src/test/java/com/vayunmathur/weather/domain/wx/WxTilesPackTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxTilesPackTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxTilesPackTest.ktnew file mode 100644index 0000000000..911d088dd7--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxTilesPackTest.kt@@ -0,0 +1,168 @@+package com.vayunmathur.weather.domain.wx++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Behaviour of the tile/pack value types (no brotli fixtures needed). */+class WxTilesPackTest {++    private fun zone() = WxTiles.Zone(+        "Europe/Berlin",+        longArrayOf(0L, 1000L, 2000L),+        intArrayOf(3600, 7200, 3600),+        listOf("CET", "CEST", "CET"),+    )++    @Test fun zoneOffsetBinarySearch() {+        val z = zone()+        assertEquals(3600, z.offsetAt(-5)) // before the first interval: first entry+        assertEquals(3600, z.offsetAt(0))+        assertEquals(3600, z.offsetAt(999))+        assertEquals(7200, z.offsetAt(1000))+        assertEquals(7200, z.offsetAt(1999))+        assertEquals(3600, z.offsetAt(2000))+        assertEquals(3600, z.offsetAt(Long.MAX_VALUE / 2))+        assertEquals("CEST", z.abbrAt(1500))+        assertEquals("CET", z.abbrAt(2500))+        assertEquals("CET", z.abbrAt(-100))+    }++    @Test fun localDayUsesZoneOffset() {+        val z = zone()+        // Epoch 0 at +1h is 1970-01-01 01:00 local.+        assertEquals("1970-01-01", WxCompute.localDay(z, 0L))+        // UTC zone: epoch -1 is still 1969-12-31.+        val utc = WxTiles.Zone("UTC", longArrayOf(0L), intArrayOf(0), listOf("UTC"))+        assertEquals("1969-12-31", WxCompute.localDay(utc, -1L))+        assertEquals("1970-01-01", WxCompute.localDay(utc, 0L))+    }++    @Test fun varBlockWindowPadsNaN() {+        val vb = WxTiles.VarBlock("temperature_2m", h0 = 100L, nt = 3, values = floatArrayOf(1f, 2f, 3f, 4f, 5f, 6f))+        // Cell 1 over [99, 103): one NaN pad, then 4,5, then NaN.+        val w = vb.window(1, 99L, 103L)+        assertEquals(4, w.size)+        assertTrue(w[0].isNaN()); assertEquals(4f, w[1]); assertEquals(5f, w[2]); assertEquals(6f, w[3])+        // Empty/inverted window.+        assertEquals(0, vb.window(0, 100L, 100L).size)+        assertEquals(0, vb.window(0, 102L, 100L).size)+        // Fully inside.+        assertTrue(vb.window(0, 100L, 103L).contentEquals(floatArrayOf(1f, 2f, 3f)))+    }++    @Test fun sectionCellWrapsLongitude() {+        val sec = WxTiles.Section(+            model = 0, ny = 10, nx = 360, j0 = 2, i0 = 350, nj = 4, ni = 20, vars = emptyList(),+        )+        assertEquals(0, sec.cell(2, 350))+        assertEquals(19, sec.cell(2, 369))+        assertEquals(0, sec.cell(2, 710)) // wraps past nx+        assertNull(sec.cell(1, 350)) // above j0+        assertNull(sec.cell(6, 350)) // below j0+nj+        assertNull(sec.variable("nope"))+    }++    @Test fun cellMeansBounds() {+        val cm = WxTiles.CellMeans(100L, 200L, 2, 3, doubleArrayOf(1.0, 2.0, Double.NaN, 4.0, 5.0, 6.0))+        assertEquals(1.0, cm.get(100L, 200L))+        assertEquals(6.0, cm.get(101L, 202L))+        assertNull(cm.get(100L, 202L)) // NaN stored -> null+        assertNull(cm.get(99L, 200L))+        assertNull(cm.get(100L, 203L))+        assertNull(cm.get(102L, 200L))+    }++    @Test fun geoBlockElevationAndZone() {+        // Elevation int encodes (m + offset): stored = (elev*256 + 8388608) accumulated.+        // GeoBlock stores cumulative ints; elevation(px,py) = (c - 8388608)/256 floored at -500.+        val elev = IntArray(64 * 64) { 8_388_608 + 256 * 10 } // 10 m everywhere+        val gb = WxTiles.GeoBlock(1, 2, 3, listOf("UTC", "Europe/Berlin"), ByteArray(256) { 1 }, elev)+        assertEquals(10.0, gb.elevation(0, 0))+        assertEquals(10.0, gb.elevation(63, 63))+        assertNull(WxTiles.GeoBlock(0, 0, 0, listOf("UTC"), ByteArray(256), null).elevation(0, 0))+        assertEquals("Europe/Berlin", gb.zone(0, 0))+        assertEquals("Europe/Berlin", gb.zone(63, 63))+        assertNull(WxTiles.GeoBlock(0, 0, 0, listOf("UTC"), ByteArray(256), null).zone(0, 0).let {+            // tz index 0 -> "UTC" exists, so not null; use an out-of-range index instead+            WxTiles.GeoBlock(0, 0, 0, listOf("UTC"), ByteArray(256) { 5 }, null).zone(0, 0)+        })+        // Below-sea-level floor: stored 0 -> (0-8388608)/256 is very negative -> -500.+        val deep = WxTiles.GeoBlock(0, 0, 0, listOf("UTC"), ByteArray(256), IntArray(64 * 64) { 0 })+        assertEquals(-500.0, deep.elevation(5, 5))+    }++    @Test fun spanPacking() {+        // Span packs offset in the high bits, length in the low 24.+        val s = WxPack.span((12345L shl 24) or 678L)+        assertEquals(12345L, s.off); assertEquals(678, s.len)+        assertTrue(!s.isEmpty)+        assertEquals("bytes=12345-13022", s.range())+        assertTrue(WxPack.span(0L).isEmpty)+        assertEquals(64L, WxPack.runEntryOffset(0, 0))+        assertEquals(64L, WxPack.histEntryOffset(0, 0)) // 8-byte spans start right after the header+        assertEquals(64L + 8L, WxPack.histEntryOffset(0, 1))+        assertTrue(WxPack.runEntryOffset(1, 0) > WxPack.runEntryOffset(0, 359))+    }++    @Test fun runEntryDecodeAndHistSpan() {+        val b = ByteArray(WxPack.RUN_ENTRY_LEN)+        fun put64(off: Int, v: Long) { for (k in 0..7) b[off + k] = (v shr (8 * k)).toByte() }+        fun put32(off: Int, v: Int) { for (k in 0..3) b[off + k] = (v shr (8 * k)).toByte() }+        fun put16(off: Int, v: Int) { for (k in 0..1) b[off + k] = (v shr (8 * k)).toByte() }+        put64(0, 42L); put64(8, 999L); put32(16, 100); put32(20, 103); put16(24, 7); put16(26, 9)+        put64(32, (5000L shl 24) or 120L)+        put64(40, (6000L shl 24) or 50L) // hist day 100+        // day 101 left empty+        put64(56, (7000L shl 24) or 60L) // hist day 102+        val e = WxPack.decodeRunEntry(b)+        assertEquals(42L, e.gen); assertEquals(999L, e.nextCheck)+        assertEquals(7, e.ty); assertEquals(9, e.tx)+        assertEquals(5000L, e.tile.off); assertEquals(120, e.tile.len)+        assertEquals(6000L, e.histSpan(100L)!!.off)+        assertNull(e.histSpan(101L)) // empty span+        assertEquals(7000L, e.histSpan(102L)!!.off)+        assertNull(e.histSpan(99L)) // before range+        assertNull(e.histSpan(103L)) // at histToDay (exclusive)+        assertFailsWith<IllegalArgumentException> { WxPack.decodeRunEntry(ByteArray(10)) }+    }++    @Test fun headerEntryOffset() {+        val h = WxPack.Header(kind = 3, entryLen = 8, ky0 = 10, kx0 = 20, nky = 2, nkx = 3)+        assertEquals(64L, h.entryOffset(10, 20))+        assertEquals(64L + 8L, h.entryOffset(10, 21))+        assertEquals(64L + 3 * 8L, h.entryOffset(11, 20))+        assertNull(h.entryOffset(9, 20))+        assertNull(h.entryOffset(12, 20))+        assertNull(h.entryOffset(10, 23))+    }++    @Test fun decodeHeaderRejectsBadPacks() {+        assertFailsWith<IllegalArgumentException> { WxPack.decodeHeader(ByteArray(64)) }+        val b = ByteArray(64)+        "WXP1".toByteArray().copyInto(b)+        b[4] = 9 // bad version+        assertFailsWith<IllegalArgumentException> { WxPack.decodeHeader(b) }+        b[4] = 1; b[5] = WxPack.KIND_GEO.toByte()+        val h = WxPack.decodeHeader(b)+        assertEquals(WxPack.KIND_GEO, h.kind)+    }++    @Test fun tileDecodersRejectGarbage() {+        assertFailsWith<WxTiles.FormatException> { WxTiles.decodeTile(byteArrayOf(1, 2, 3)) }+        assertFailsWith<WxTiles.FormatException> { WxTiles.decodeGeo(byteArrayOf(1, 2, 3)) }+        // Right magic, wrong version.+        val bad = "WXT1".toByteArray() + byteArrayOf(9, 0) + ByteArray(20)+        assertFailsWith<WxTiles.FormatException> { WxTiles.decodeTile(bad) }+    }++    @Test fun histDaysNeededRange() {+        // now is in window terms; runH0 at day boundary.+        val now = 20770L * 86400 + 3600+        val days = WxGrid.histDaysNeeded(now, 20770L * 24)+        assertTrue(days.first <= days.last)+        assertTrue(days.all { it < 20770L })+    }+}
weather/src/test/java/com/vayunmathur/weather/intents/WeatherByNameIntentTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/intents/WeatherByNameIntentTest.kt b/weather/src/test/java/com/vayunmathur/weather/intents/WeatherByNameIntentTest.ktnew file mode 100644index 0000000000..7f9c655a5e--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/intents/WeatherByNameIntentTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.weather.intents++import com.vayunmathur.weather.network.GeocodingResult+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.data.GeoDatabase+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** GetWeatherByNameIntent no-match path and GeocodingResult construction. */+@RunWith(AndroidJUnit4::class)+class WeatherByNameIntentTest {++    @BeforeTest fun setUp() {+        GeoDatabase.init(ApplicationProvider.getApplicationContext())+    }++    @Test fun noMatchReturnsNamedError() = runTest {+        // No places catalogue is unpacked in this sandbox, so any name+        // resolves to zero matches and the intent must say so, not throw.+        val data = GetWeatherByNameIntent().performCalculation(LocationQueryInput("Atlantis"))+        assertEquals("No location matched 'Atlantis'", data.error)+        assertEquals("Atlantis", data.locationName)+        assertEquals(0.0, data.temperatureCelsius)+    }++    @Test fun blankNameReturnsError() = runTest {+        val data = GetWeatherByNameIntent().performCalculation(LocationQueryInput(""))+        assertNotNull(data.error)+    }++    @Test fun geocodingResultConstructionAndSerialization() {+        val full = GeocodingResult(+            id = 7L, name = "Berlin", latitude = 52.52, longitude = 13.405,+            country = "Germany", countryCode = "DE", admin1 = "Berlin", timezone = "Europe/Berlin",+        )+        assertEquals(7L, full.id)+        assertEquals("DE", full.countryCode)+        val copy = full.copy(name = "Berlin-Mitte")+        assertEquals("Berlin-Mitte", copy.name)+        assertEquals(full.latitude, copy.latitude)+        assertTrue(full.toString().contains("Berlin"))+        assertEquals(full.hashCode(), full.copy().hashCode())++        val minimal = GeocodingResult(id = 1L, name = "X", latitude = 0.0, longitude = 0.0)+        assertNull(minimal.country)+        assertNull(minimal.countryCode)+        assertNull(minimal.admin1)+        assertNull(minimal.timezone)++        val json = Json { ignoreUnknownKeys = true }+        val decoded = json.decodeFromString<GeocodingResult>(json.encodeToString(GeocodingResult.serializer(), full))+        assertEquals(full, decoded)+        // Serialized names follow the API (country_code), and missing+        // optional fields decode as null.+        val fromApi = json.decodeFromString<GeocodingResult>(+            """{"id":3,"name":"Bern","latitude":46.95,"longitude":7.45,"country_code":"CH"}"""+        )+        assertEquals("CH", fromApi.countryCode)+        assertNull(fromApi.country)+    }+}
weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.ktnew file mode 100644index 0000000000..e72141145e--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.weather.network++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.weather.data.GeoDatabase+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.assertFailsWith+import kotlin.test.assertTrue++/** WeatherApi behaviour that does not need the live network: blank/short-circuit paths and the dead-server fallback. */+@RunWith(AndroidJUnit4::class)+class WeatherApiBehaviourTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() {+        GeoDatabase.init(ctx)+        WeatherApi.bundleBaseOverride = "https://127.0.0.1:9/wx/v1"+    }++    @AfterTest fun tearDown() {+        WeatherApi.bundleBaseOverride = null+    }++    @Test fun geocodeBlankShortCircuits() = runTest {+        assertTrue(WeatherApi.geocode("").results.isEmpty())+        assertTrue(WeatherApi.geocode("   ").results.isEmpty())+    }++    @Test fun geocodeUnknownPlaceIsEmptyNotFailure() = runTest {+        // Catalogue may not be unpacked under Robolectric; either way an+        // unknown nonsense query must return empty, never throw.+        val r = WeatherApi.geocode("zzzzqqqq-no-such-place-12345", limit = 5)+        assertTrue(r.results.isEmpty())+    }++    @Test fun emptyBatchTemperaturesNeedsNoNetwork() = runTest {+        assertEquals(emptyMap(), WeatherApi.currentTemperatures(emptyList()))+    }++    @Test fun bundleDerivedCallsFailAgainstDeadServer() = runTest {+        assertFailsWith<Exception> { WeatherApi.forecast(52.0, 13.0) }+        assertFailsWith<Exception> { WeatherApi.airQuality(52.0, 13.0) }+        assertFailsWith<Exception> { WeatherApi.timezoneAt(52.0, 13.0) }+        assertFailsWith<Exception> { WeatherApi.currentTemperature(52.0, 13.0) }+        assertFailsWith<Exception> { WeatherApi.currentTemperatures(listOf(52.0 to 13.0)) }+    }++    @Test fun dtoDefaultsAndJsonRoundTrip() {+        val bundle = WxBundle(lat = 1.5, lon = 2.5)+        assertEquals("UTC", bundle.tz)+        assertEquals(null, bundle.current)+        assertEquals(null, bundle.aq)+        val aq = WxAq(time = 100L, usAqi = 42)+        val mapped = WxBundle(lat = 0.0, lon = 0.0, utcOffset = 3600, aq = aq).toAirQuality()+        assertEquals(42, mapped!!.current!!.usAqi)+        // 100s after epoch + 1h offset = 01:01 local.+        assertEquals("1970-01-01T01:01", mapped.current!!.time)+        assertEquals(null, WxBundle(lat = 0.0, lon = 0.0).toAirQuality())+        val tz = WxBundle(lat = 0.0, lon = 0.0, tz = "Europe/Berlin", tzAbbr = "CEST", utcOffset = 7200).toRegionTimezone()+        assertEquals("Europe/Berlin", tz.timezone)+        assertEquals(7200, tz.utcOffsetSeconds)+        // Forecast mapping with no sections: envelope only.+        val f = WxBundle(lat = 3.0, lon = 4.0).toForecastResponse()+        assertEquals(3.0, f.latitude); assertEquals(null, f.current); assertEquals(null, f.hourly); assertEquals(null, f.daily)+    }++    @Test fun forecastMappingExpandsSeries() {+        val bundle = WxBundle(+            lat = 52.0, lon = 13.0, utcOffset = 0,+            current = WxCurrent(time = 3600, temp = 20.0, feels = 21.0, rh = 50, dew = 9.0, code = 1,+                windSpd = 10.0, windDir = 90, pres = 1013.0, vis = 10000.0, cloud = 20, gust = 15.0, day = 1),+            hourly = WxHourly(start = 0, step = 3600, count = 2, temp = listOf(10.0, 11.0),+                feels = listOf(10.0, 11.0), rh = listOf(40, 41), dew = listOf(1.0, 2.0), code = listOf(0, 1),+                pprob = listOf(0, 10), precip = listOf(0.0, 0.1), windSpd = listOf(5.0, 6.0),+                windDir = listOf(0, 90), pres = listOf(1000.0, 1001.0), vis = listOf(9000.0, 9500.0),+                uv = listOf(1.0, null), cloud = listOf(0, 50), gust = listOf(7.0, 8.0), day = listOf(0, 1)),+            daily = WxDaily(start = "2026-07-15", count = 2, code = listOf(1, 61),+                tmax = listOf(25.0, 20.0), tmin = listOf(15.0, 11.0),+                feelsMax = listOf(26.0, 20.0), feelsMin = listOf(15.0, 11.0),+                sunrise = listOf(18000, 104400), sunset = listOf(72000, 158400),+                daylight = listOf(54000, 54000), sunshine = listOf(3600, 0),+                uvMax = listOf(5.0, null), pprobMax = listOf(10, 80), precipSum = listOf(0.0, 2.5),+                moonPhase = listOf(0.1, 0.2), moonrise = listOf(1000L, null), moonset = listOf(2000L, 3000L)),+            min15 = WxMin15(start = 0, step = 900, count = 2, precip = listOf(0.0, 0.4)),+        )+        val f = bundle.toForecastResponse()+        assertEquals("1970-01-01T01:00", f.current!!.time)+        assertEquals(listOf("1970-01-01T00:00", "1970-01-01T01:00"), f.hourly!!.time)+        assertEquals(listOf("2026-07-15", "2026-07-16"), f.daily!!.time)+        assertEquals(80, f.daily!!.precipitationProbabilityMax[1])+        assertEquals(null, f.daily!!.moonrise[1])+        assertEquals("1970-01-01T00:15", f.minutely15!!.time[1])+    }+}
weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.ktnew file mode 100644index 0000000000..661ec6c90e--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.weather.network++import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Wire-format round trips for the bundle/batch DTOs: serial names, defaults, nullability. */+class WxDtoWireTest {+    private val json = Json { ignoreUnknownKeys = true }++    @Test+    fun currentBatchDecodesPointsAndDefaultsVersion() {+        val batch = json.decodeFromString<WxCurrentBatch>(+            """{"points":[{"lat":51.5,"lon":-0.12,"temp":9.5,"code":3,"day":1},{"lat":40.7,"lon":-74.0,"temp":21.25,"code":0,"day":0}]}""",+        )+        assertEquals(1, batch.v)+        assertEquals(2, batch.points.size)+        assertEquals(WxCurrentPoint(51.5, -0.12, 9.5, 3, 1), batch.points[0])+        assertEquals(0, batch.points[1].day)+        assertEquals("""{"v":2}""", json.encodeToString(WxCurrentBatch.serializer(), WxCurrentBatch(v = 2))) // default empty points omitted+        assertEquals(WxCurrentBatch(), json.decodeFromString<WxCurrentBatch>("""{}"""))+        // copy/component semantics carry the point values, not defaults+        val moved = batch.points[1].copy(temp = -3.0, code = 61)+        assertEquals(-3.0, moved.temp); assertEquals(61, moved.code); assertEquals(40.7, moved.lat)+    }++    @Test+    fun min15AndCurrentSerialNames() {+        val min15 = json.decodeFromString<WxMin15>("""{"start":1700000000,"precip":[0.0,0.2,1.4]}""")+        assertEquals(900L, min15.step); assertEquals(0, min15.count); assertEquals(listOf(0.0, 0.2, 1.4), min15.precip)+        val encodedMin = json.encodeToString(WxMin15.serializer(), WxMin15(start = 5, step = 900, count = 2, precip = listOf(0.5)))+        assertTrue(encodedMin.contains("\"start\":5")); assertTrue(encodedMin.contains("\"precip\":[0.5]"))+        val current = json.decodeFromString<WxCurrent>(+            """{"time":1700000000,"temp":4.0,"feels":1.5,"rh":81,"dew":1.0,"code":45,"wind_spd":12.5,"wind_dir":270,"pres":1013.0,"vis":4000.0,"cloud":90,"gust":30.0,"day":1}""",+        )+        assertEquals(12.5, current.windSpd); assertEquals(270, current.windDir); assertEquals(45, current.code)+        assertTrue(json.encodeToString(WxCurrent.serializer(), current).contains("\"wind_spd\":12.5"))+    }++    @Test+    fun regionTimezoneAndCurrentTemperatureDefaults() {+        val tz = json.decodeFromString<RegionTimezone>("""{"timezone":"Europe/London","timezone_abbreviation":"GMT","utc_offset_seconds":0}""")+        assertEquals("Europe/London", tz.timezone); assertEquals("GMT", tz.abbreviation); assertEquals(0, tz.utcOffsetSeconds)+        val empty = json.decodeFromString<RegionTimezone>("""{}""")+        assertNull(empty.timezone); assertNull(empty.abbreviation)+        val temp = json.decodeFromString<CurrentTemperatureResponse>("""{"current":{"temperature_2m":18.25}}""")+        assertEquals(18.25, temp.current!!.temperature)+        assertNull(json.decodeFromString<CurrentTemperatureResponse>("""{}""").current)+        assertTrue(json.encodeToString(CurrentTemperature.serializer(), CurrentTemperature(7.5)).contains("\"temperature_2m\":7.5"))+    }++    @Test+    fun bundleDefaultsAndNullableSections() {+        val bundle = json.decodeFromString<WxBundle>("""{"lat":1.0,"lon":2.0}""")+        assertEquals("UTC", bundle.tz); assertNull(bundle.current); assertNull(bundle.min15); assertNull(bundle.aq)+        val aq = json.decodeFromString<WxAq>("""{"time":9,"us_aqi":42,"grass":1.5}""")+        assertEquals(42, aq.usAqi); assertEquals(1.5, aq.grass); assertNull(aq.birch)+        assertTrue(json.encodeToString(WxAq.serializer(), aq).contains("\"us_aqi\":42"))+    }+}
weather/src/test/java/com/vayunmathur/weather/network/WxStaticDiskCacheTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WxStaticDiskCacheTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticDiskCacheTest.ktnew file mode 100644index 0000000000..0f3cdcdd0a--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticDiskCacheTest.kt@@ -0,0 +1,114 @@+package com.vayunmathur.weather.network++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.long+import org.junit.runner.RunWith+import java.io.File+import java.util.zip.GZIPInputStream+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * [WxStatic] with a real on-disk cache directory (Robolectric cacheDir):+ * the first bundle writes the entry/tile/history/geo files, and after the+ * in-memory caches are reset a second bundle is served entirely from disk+ * (loadEntry, runTile, history and geo file reads) with zero fetches.+ */+@RunWith(AndroidJUnit4::class)+class WxStaticDiskCacheTest {++    private val json = Json { ignoreUnknownKeys = true }+    private val requests = mutableListOf<String>()+    private val objects = HashMap<String, Pair<ByteArray, String>>()+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun res(path: String): ByteArray? =+        javaClass.classLoader!!.getResourceAsStream("wx/$path")?.use { it.readBytes() }+    private fun gz(path: String): ByteArray = GZIPInputStream(res(path)!!.inputStream()).use { it.readBytes() }++    private val case = json.parseToJsonElement(res("cases.json")!!.decodeToString()).jsonArray[0].jsonObject+    private val lat = case["lat"]!!.jsonPrimitive.content.toDouble()+    private val lon = case["lon"]!!.jsonPrimitive.content.toDouble()+    private val now = case["now"]!!.jsonPrimitive.long++    @BeforeTest fun setUp() {+        WxStatic.resetForTest()+        WxStatic.enabled = true+        WxStatic.baseOverride = "https://r2.test/wx/v1/"+        // Start from an empty wx-static cache dir.+        File(ctx.cacheDir, "wx-static").deleteRecursively()+        WxStatic.init(ctx)+        objects["run.wxp"] = gz("run.wxp.gz") to "\"run1\""+        objects["geo.wxp"] = gz("geo.wxp.gz") to "\"geo\""+        for (d in 20762..20769) objects["hist/$d.wxp"] = gz("hist/$d.wxp.gz") to "\"h$d\""+        WxStatic.fetcher = { url, headers ->+            val key = url.removePrefix("https://r2.test/wx/v1/")+            val obj = objects[key]+            val (a, b) = headers.getValue("Range").removePrefix("bytes=").split('-').map { it.toLong() }+            requests += "$key@$a"+            when {+                obj == null -> WxStatic.Resp(404, emptyMap(), ByteArray(0))+                headers["If-Match"]?.let { it != obj.second } == true -> WxStatic.Resp(412, emptyMap(), ByteArray(0))+                else -> WxStatic.Resp(206, mapOf("etag" to obj.second), obj.first.copyOfRange(a.toInt(), b.toInt() + 1))+            }+        }+    }++    @AfterTest fun tearDown() {+        WxStatic.resetForTest()+        WxStatic.baseOverride = null+        WxStatic.enabled = true+    }++    @Test fun secondBundleIsServedEntirelyFromDiskCache() = runBlocking {+        val first = WxStatic.bundle(lat, lon, now)+        assertNotNull(first.current)+        assertTrue(requests.isNotEmpty())+        val dir = File(ctx.cacheDir, "wx-static")+        // Entry, tile, history and geo files were written atomically.+        assertTrue(File(dir, "e").listFiles()?.isNotEmpty() == true, "entry files: ${dir.walkTopDown().map { it.name }.toList()}")+        assertTrue(File(dir, "t").listFiles()?.isNotEmpty() == true)+        assertTrue(File(dir, "h").listFiles()?.isNotEmpty() == true)+        assertTrue(File(dir, "g").listFiles()?.isNotEmpty() == true)+        assertTrue(File(dir, "g/header").exists())++        // Drop all in-memory state (as a process restart would), keep disk.+        WxStatic.resetForTest()+        WxStatic.baseOverride = "https://r2.test/wx/v1/"+        WxStatic.init(ctx)+        WxStatic.fetcher = { _, _ -> throw AssertionError("network must not be touched on a warm disk cache") }+        requests.clear()+        val second = WxStatic.bundle(lat, lon, now + 3600)+        assertNotNull(second.current)+        // Recomputed locally for the new hour from the disk-cached tile:+        // the current timestamp advances by exactly the elapsed hour.+        assertEquals(first.current!!.time + 3600, second.current!!.time)+        assertTrue(requests.isEmpty())+    }++    @Test fun corruptEntryFileIsIgnoredAndRefetched() = runBlocking {+        WxStatic.bundle(lat, lon, now)+        val entryFile = File(ctx.cacheDir, "wx-static/e").listFiles()!!.first()+        entryFile.writeBytes(ByteArray(4) { 0x7f }) // too short to decode+        WxStatic.resetForTest()+        WxStatic.baseOverride = "https://r2.test/wx/v1/"+        WxStatic.init(ctx)+        // Fetcher is still the fixture fetcher from setUp? No: resetForTest+        // does not touch fetcher, so ranged GETs work again.+        val before = requests.size+        val bundle = WxStatic.bundle(lat, lon, now + 3600)+        assertNotNull(bundle.current)+        assertTrue(requests.size > before, "corrupt entry must trigger a refetch")+    }+}
weather/src/test/java/com/vayunmathur/weather/network/WxStaticErrorPathsTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WxStaticErrorPathsTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticErrorPathsTest.ktnew file mode 100644index 0000000000..26c66c2478--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticErrorPathsTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.weather.network++import com.vayunmathur.weather.domain.wx.WxGrid+import com.vayunmathur.weather.domain.wx.WxPack+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.long+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Before+import org.junit.Test+import java.io.IOException+import java.util.zip.GZIPInputStream++/**+ * [WxStatic] failure and cache-policy branches the happy-path fixture test+ * does not reach: disabled, HTTP error mapping, short bodies, layout+ * changes, off-grid points, missing history, and entry re-check timing.+ */+class WxStaticErrorPathsTest {+    private val json = Json { ignoreUnknownKeys = true }+    private val requests = mutableListOf<String>()+    private val objects = HashMap<String, Pair<ByteArray, String>>()++    private fun res(path: String): ByteArray? =+        javaClass.classLoader!!.getResourceAsStream("wx/$path")?.use { it.readBytes() }+    private fun gz(path: String): ByteArray = GZIPInputStream(res(path)!!.inputStream()).use { it.readBytes() }++    private val case = json.parseToJsonElement(res("cases.json")!!.decodeToString()).jsonArray[0].jsonObject+    private val lat = case["lat"]!!.jsonPrimitive.content.toDouble()+    private val lon = case["lon"]!!.jsonPrimitive.content.toDouble()+    private val now = case["now"]!!.jsonPrimitive.long++    @Before fun setUp() {+        WxStatic.resetForTest()+        WxStatic.enabled = true+        WxStatic.baseOverride = "https://r2.test/wx/v1/"+        objects["run.wxp"] = gz("run.wxp.gz") to "\"run1\""+        objects["geo.wxp"] = gz("geo.wxp.gz") to "\"geo\""+        for (d in 20762..20769) objects["hist/$d.wxp"] = gz("hist/$d.wxp.gz") to "\"h$d\""+        installFetcher()+    }++    @After fun tearDown() {+        WxStatic.resetForTest()+        WxStatic.baseOverride = null+        WxStatic.enabled = true+    }++    private fun installFetcher() {+        WxStatic.fetcher = { url, headers ->+            val key = url.removePrefix("https://r2.test/wx/v1/")+            val obj = objects[key]+            val (a, b) = headers.getValue("Range").removePrefix("bytes=").split('-').map { it.toLong() }+            requests += "$key@$a"+            when {+                obj == null -> WxStatic.Resp(404, emptyMap(), ByteArray(0))+                headers["If-Match"]?.let { it != obj.second } == true -> WxStatic.Resp(412, emptyMap(), ByteArray(0))+                else -> WxStatic.Resp(206, mapOf("etag" to obj.second), obj.first.copyOfRange(a.toInt(), b.toInt() + 1))+            }+        }+    }++    private fun entryOffset(): Int {+        val (ty, tx) = WxGrid.tileOf(lat, lon, WxPack.NY, WxPack.NX, WxPack.CELLS)+        return WxPack.runEntryOffset(ty, tx).toInt()+    }++    private inline fun <reified T : Throwable> expectBundleFails(lat: Double, lon: Double, at: Long): T {+        try {+            runBlocking { WxStatic.bundle(lat, lon, at) }+        } catch (e: Throwable) {+            if (e is T) return e+            throw AssertionError("expected ${T::class.simpleName}, got $e", e)+        }+        fail("expected ${T::class.simpleName}")+        throw AssertionError("unreachable")+    }++    @Test fun `disabled is NotCovered without any request`() {+        WxStatic.enabled = false+        val e = expectBundleFails<WxStatic.NotCovered>(lat, lon, now)+        assertEquals("disabled", e.message)+        assertTrue(requests.isEmpty())+    }++    @Test fun `off the DEM grid is NotCovered without any request`() {+        // Far south beyond the DEM grid: geoOf returns null before any fetch.+        expectBundleFails<WxStatic.NotCovered>(-89.0, 0.0, now)+        assertTrue(requests.isEmpty())+    }++    @Test fun `missing run pack is NotCovered`() {+        objects.remove("run.wxp")+        expectBundleFails<WxStatic.NotCovered>(lat, lon, now)+        assertEquals(1, requests.size)+    }++    @Test fun `forbidden run pack is NotCovered`() {+        WxStatic.fetcher = { _, _ -> WxStatic.Resp(403, emptyMap(), ByteArray(0)) }+        expectBundleFails<WxStatic.NotCovered>(lat, lon, now)+    }++    @Test fun `server error on entry is IOException without cached entry`() {+        WxStatic.fetcher = { _, _ -> WxStatic.Resp(500, emptyMap(), ByteArray(0)) }+        val e = expectBundleFails<IOException>(lat, lon, now)+        assertTrue(e.message!!.contains("HTTP 500"))+    }++    @Test fun `short ranged body is IOException`() {+        WxStatic.fetcher = { _, _ -> WxStatic.Resp(206, mapOf("etag" to "\"x\""), ByteArray(3)) }+        val e = expectBundleFails<IOException>(lat, lon, now)+        assertTrue(e.message!!.contains("bytes, want"))+    }++    @Test fun `fetcher IOException propagates when nothing is cached`() {+        WxStatic.fetcher = { _, _ -> throw IOException("offline") }+        val e = expectBundleFails<IOException>(lat, lon, now)+        assertEquals("offline", e.message)+    }++    @Test fun `entry for a different tile is a layout change`() {+        // Rewrite the entry's ty field so decodeRunEntry disagrees with the+        // requested tile: bundle must refuse rather than serve wrong data.+        val b = objects.getValue("run.wxp").first.copyOf()+        val at = entryOffset()+        b[at + 24] = (b[at + 24] + 1).toByte() // ty low byte+        objects["run.wxp"] = b to "\"run1\""+        val e = expectBundleFails<WxStatic.NotCovered>(lat, lon, now)+        assertEquals("run pack layout changed", e.message)+    }++    @Test fun `missing geo pack fails after tile fetch`() {+        objects.remove("geo.wxp")+        // Entry+tile+history succeed; the geo header GET 404s -> NotCovered.+        expectBundleFails<WxStatic.NotCovered>(lat, lon, now)+        assertTrue(requests.any { it.startsWith("geo.wxp@") })+    }++    @Test fun `missing history day is NotCovered`() {+        // Drop every history object; the first needed day's span exists in+        // the entry but the object itself is gone (404 -> NotCovered).+        for (d in 20762..20769) objects.remove("hist/$d.wxp")+        expectBundleFails<WxStatic.NotCovered>(lat, lon, now)+        assertTrue(requests.any { it.startsWith("hist/") })+    }++    @Test fun `cached entry survives a later entry-fetch IOException`() = runBlocking {+        WxStatic.bundle(lat, lon, now)+        val first = requests.size+        // Move past next_check so an entry re-check is due, then go offline:+        // the cached entry/tile/history/geo must serve the bundle again.+        val real = WxStatic.fetcher+        var offline = false+        WxStatic.fetcher = { url, headers -> if (offline) throw IOException("offline") else real(url, headers) }+        offline = true+        val entry = WxPack.decodeRunEntry(+            objects.getValue("run.wxp").first.copyOfRange(entryOffset(), entryOffset() + WxPack.RUN_ENTRY_LEN)+        )+        val t = maxOf(entry.nextCheck, now) + 20 * 60+        val b = WxStatic.bundle(lat, lon, t)+        assertTrue(b.current != null)+        // While offline the real fetcher is never reached, so no new+        // ranged requests are recorded; the bundle came from cache.+        assertEquals(first, requests.size)+    }++    @Test fun `poll minimum suppresses recheck shortly after next check`() = runBlocking {+        val entry = WxPack.decodeRunEntry(+            objects.getValue("run.wxp").first.copyOfRange(entryOffset(), entryOffset() + WxPack.RUN_ENTRY_LEN)+        )+        // First fetch happens just after next_check, so a second call a+        // minute later is due (past next_check) but inside POLL_MIN_SECS+        // of the fetch and must reuse the cached entry.+        val t0 = maxOf(entry.nextCheck, now) + 60+        WxStatic.bundle(lat, lon, t0)+        val first = requests.size+        WxStatic.bundle(lat, lon, t0 + 60)+        assertEquals(first, requests.size)+    }+}
weather/src/test/java/com/vayunmathur/weather/platform/ViewModelSuccessTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelSuccessTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelSuccessTest.ktnew file mode 100644index 0000000000..7e36031de7--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelSuccessTest.kt@@ -0,0 +1,108 @@+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.network.WxAq+import com.vayunmathur.weather.network.WxBundle+import com.vayunmathur.weather.network.WxCurrent+import com.vayunmathur.weather.network.toForecastResponse+import kotlinx.coroutines.test.runTest+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.assertNull+import kotlin.test.assertTrue++/** WeatherViewModel success path: a good bundle is applied, cached, and clears errors. */+@RunWith(AndroidJUnit4::class)+class ViewModelSuccessTest {++    private lateinit var app: Application+    private lateinit var repo: FakeRepository++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching { androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build()) }+        repo = FakeRepository(app)+    }++    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 bundle() = WxBundle(+        lat = 52.5, lon = 13.4, utcOffset = 0,+        current = WxCurrent(time = 1784073600, temp = 25.0, feels = 26.0, rh = 50, dew = 14.0, code = 2,+            windSpd = 10.0, windDir = 90, pres = 1013.0, vis = 10000.0, cloud = 20, gust = 15.0, day = 1),+        aq = WxAq(time = 1784073600, usAqi = 33),+    )++    @Test fun successfulFetchAppliesForecastAndAirQuality() {+        val vm = WeatherViewModel(app, repo) { _, _ -> bundle() }+        val loc = SavedLocation(id = 31L, name = "Berlin", latitude = 52.5, longitude = 13.4)+        vm.ensureForecast(loc, force = true)+        assertTrue(await { vm.forecasts.value[31L]?.forecast != null }, "state=${vm.forecasts.value}")+        val state = vm.forecasts.value[31L]!!+        assertEquals(25.0, state.forecast!!.current!!.temperature)+        assertEquals(33, state.airQuality!!.current!!.usAqi)+        assertEquals(false, state.refreshing)+        assertNull(state.error)+        assertTrue(state.fetchedAtEpochMs > 0)+        // The fetch was written through to the repository cache.+        assertTrue(repo.caches.isNotEmpty())+    }++    @Test fun freshInMemoryStateSkipsSecondFetch() {+        var calls = 0+        val vm = WeatherViewModel(app, repo) { _, _ -> calls++; bundle() }+        val loc = SavedLocation(id = 32L, name = "Berlin", latitude = 52.5, longitude = 13.4)+        vm.ensureForecast(loc, force = true)+        assertTrue(await { vm.forecasts.value[32L]?.forecast != null })+        vm.ensureForecast(loc) // not forced, just fetched: no refetch+        Thread.sleep(100)+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertEquals(1, calls)+    }++    @Test fun failureAfterSuccessKeepsForecastAndSetsError() {+        // Seed a stale cache (hydrates first), then the network fetch fails:+        // the error must surface while the hydrated forecast stays.+        val loc = SavedLocation(id = 33L, name = "Berlin", latitude = 52.5, longitude = 13.4)+        val key = com.vayunmathur.weather.domain.roundCoord(loc.latitude) to+            com.vayunmathur.weather.domain.roundCoord(loc.longitude)+        repo.caches[key] = com.vayunmathur.weather.data.WeatherCache(+            latRounded = key.first, lonRounded = key.second,+            forecastJson = com.vayunmathur.weather.data.weatherJson.encodeToString(bundle().toForecastResponse()),+            fetchedAtEpochMs = 0L,+        )+        val vm = WeatherViewModel(app, repo) { _, _ -> throw java.io.IOException("down") }+        vm.ensureForecast(loc, force = true)+        assertTrue(await { vm.forecasts.value[33L]?.error != null }, "state=${vm.forecasts.value}")+        assertNotNull(vm.forecasts.value[33L]!!.forecast)+        assertEquals(25.0, vm.forecasts.value[33L]!!.forecast!!.current!!.temperature)+    }++    @Test fun bundleWithoutAqKeepsNullAirQuality() {+        val vm = WeatherViewModel(app, repo) { _, _ -> bundle().copy(aq = null) }+        val loc = SavedLocation(id = 34L, name = "Berlin", latitude = 52.5, longitude = 13.4)+        vm.ensureForecast(loc, force = true)+        assertTrue(await { vm.forecasts.value[34L]?.forecast != null })+        assertNull(vm.forecasts.value[34L]!!.airQuality)+    }++    @Test fun reverseGeocodeWithoutBackendIsNull() = runTest {+        // Robolectric has no Geocoder backend: must return null, not throw.+        assertNull(reverseGeocodeName(app, 52.5, 13.4))+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/ForecastInteractionsTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/ForecastInteractionsTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/ForecastInteractionsTest.ktnew file mode 100644index 0000000000..23e1de9569--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/ForecastInteractionsTest.kt@@ -0,0 +1,92 @@+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.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.unit.dp+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.rememberDrawerState+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.domain.WeatherMetric+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.LocationUiState+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++/** ForecastColumn interactions: hour/day selection and opening a metric+ *  graph sheet from a weather block. */+@RunWith(AndroidJUnit4::class)+class ForecastInteractionsTest {++    @get:Rule val rule = createComposeRule()++    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", "2026-07-15T15:00", "2026-07-15T16:00"),+            temperature = listOf(25.0, 26.0, 24.0),+            weatherCode = listOf(2, 2, 3), precipitationProbability = listOf(10, 20, 30), isDay = listOf(1, 1, 1),+        ),+        daily = Daily(+            time = listOf("2026-07-15", "2026-07-16"), temperatureMax = listOf(27.0, 26.0),+            temperatureMin = listOf(17.0, 16.0), weatherCode = listOf(2, 3),+            precipitationProbabilityMax = listOf(10, 20), uvIndexMax = listOf(5.0, 4.0),+            sunrise = listOf("2026-07-15T05:00", "2026-07-16T05:01"), sunset = listOf("2026-07-15T21:00", "2026-07-16T21:01"),+        ),+    )++    @Test fun clickingHourAndBlockInvokesActionsAndOpensGraph() {+        var toggledTime: String? = null+        var openedMetric: WeatherMetric? = null+        var openedIso: String? = "unset"+        val actions = object : WeatherActions {+            override fun toggleTime(isoTime: String) { toggledTime = isoTime }+        }+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(+                    location = SavedLocation(id = 1, name = "Berlin", country = "Germany", latitude = 52.5, longitude = 13.4),+                    forecast = forecast(),+                ),+                units = DisplayUnits(use24Hour = true),+                actions = actions,+                drawerState = rememberDrawerState(DrawerValue.Closed),+                paddingValues = PaddingValues(0.dp),+                precipitationNowcast = null,+                nowEpochSec = 1760000000L,+                onOpenMap = { m, iso -> openedMetric = m; openedIso = iso },+            )+        }+        rule.onNodeWithText("Berlin", substring = true).assertIsDisplayed()+        // Hourly strip: the 15 slot (bare hour in 24h units) toggles it.+        rule.onNodeWithText("15").performClick()+        assertEquals("2026-07-15T15:00", toggledTime)+        // Weather blocks are below the fold in the column; the humidity+        // block's label doubles as the graph-sheet entry point.+        rule.onAllNodesWithText("Humidity")[0].performClick()+        rule.waitForIdle()+        // The graph sheet opened (its title is the metric's title, shown+        // once as the sheet header in addition to the block label).+        assertTrue(rule.onAllNodesWithText("Humidity").fetchSemanticsNodes().size >= 1)+        assertEquals(null, openedMetric) // map not opened yet; sheet only+        assertEquals("unset", openedIso)+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.ktnew file mode 100644index 0000000000..fc30dfb67d--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.kt@@ -0,0 +1,192 @@+package com.vayunmathur.weather.ui++import android.app.Application+import android.os.Looper+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.longClick+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.rememberDrawerState+import com.vayunmathur.library.util.NavBackStack+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.platform.WeatherViewModel+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.emptyFlow+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.assertTrue++/** HomePage loading branch, ForecastColumn selection/graph branches, and+ *  LocationsScreen sheet/units/device-card branches not reached by the+ *  existing screen tests. */+@RunWith(AndroidJUnit4::class)+class HomeAndLocationsExtraTest {++    @get:Rule val rule = createComposeRule()++    private lateinit var app: Application++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching { androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build()) }+    }++    private class NeverLocationsRepository(context: android.content.Context) :+        com.vayunmathur.weather.data.WeatherRepository(context) {+        override val locations: Flow<List<SavedLocation>> get() = emptyFlow()+    }++    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, utcOffsetSeconds = 3600,+        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", "2026-07-15T15:00", "2026-07-16T14:00"),+            temperature = listOf(25.0, 26.0, 24.0),+            weatherCode = listOf(2, 2, 3), precipitationProbability = listOf(10, 20, 30), isDay = listOf(1, 1, 1),+        ),+        daily = Daily(+            time = listOf("2026-07-15", "2026-07-16"), temperatureMax = listOf(27.0, 26.0),+            temperatureMin = listOf(17.0, 16.0), weatherCode = listOf(2, 3),+            precipitationProbabilityMax = listOf(10, 20), uvIndexMax = listOf(5.0, 4.0),+            sunrise = listOf("2026-07-15T05:00", "2026-07-16T05:01"), sunset = listOf("2026-07-15T21:00", "2026-07-16T21:01"),+        ),+    )++    @Test fun homePageHoldsPlaceholderWhileLocationsLoad() {+        val repo = NeverLocationsRepository(app)+        val vm = WeatherViewModel(app, repo)+        val backStack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent { HomePage(backStack, vm) }+        rule.waitForIdle()+        // Neither the empty state nor a forecast is shown yet.+        rule.onAllNodesWithText("No locations yet").fetchSemanticsNodes().also { assertTrue(it.isEmpty()) }+        rule.onAllNodesWithText("Add a location").fetchSemanticsNodes().also { assertTrue(it.isEmpty()) }+    }++    @Test fun forecastColumnWithDaySelectionShowsHeaderAndBlocks() {+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(+                    location = loc(), forecast = forecast(),+                    selected = SelectedDateOrTime.Day("2026-07-16"),+                ),+                units = DisplayUnits(),+                actions = WeatherActions.Noop,+                drawerState = rememberDrawerState(DrawerValue.Closed),+                paddingValues = PaddingValues(0.dp),+                precipitationNowcast = "Rain soon",+                nowEpochSec = 1760000000L,+                onOpenMap = { _, _ -> },+            )+        }+        rule.onNodeWithText("Berlin", substring = true).assertIsDisplayed()+        rule.waitForIdle()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+    }++    @Test fun forecastColumnRefreshingWithForecastShowsContent() {+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(location = loc(), forecast = forecast(), refreshing = true),+                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 locationsScreenWithCurrentRowHidesDeviceCardAndLongPressDeletes() {+        var deleted: SavedLocation? = null+        var closed = false+        val actions = object : WeatherActions {+            override fun deleteLocation(location: SavedLocation) { deleted = location }+        }+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(+                    rows = listOf(+                        LocationRow(loc(1, "Berlin", current = true), "Now", 2, true),+                        LocationRow(loc(2, "Paris"), "Earlier", 0, true),+                    ),+                    activeLocationId = 2L,+                ),+                actions = actions,+                onClose = { closed = true },+            )+        }+        // A current row exists, so no "use device location" card.+        rule.onAllNodesWithText("Use current location", substring = true)+            .fetchSemanticsNodes().also { assertTrue(it.isEmpty()) }+        rule.onNodeWithText("Paris").assertIsDisplayed()+        rule.onNodeWithText("Berlin").performTouchInput { longClick() }+        rule.waitForIdle()+        rule.onNodeWithText("Confirm delete").performClick()+        assertEquals("Berlin", deleted?.name)+        assertEquals(false, closed)+    }++    @Test fun locationsScreenUnitsButtonAndBackClose() {+        var closed = false+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(rows = listOf(LocationRow(loc(1, "Berlin"), "Now", 2, true))),+                actions = WeatherActions.Noop,+                onClose = { closed = true },+            )+        }+        rule.onNodeWithText("Units").performClick()+        rule.waitForIdle()+        // Back/close icon is the first clickable in the top bar; the screen+        // itself remains composed after opening the units settings intent.+        rule.onNodeWithText("Locations").assertIsDisplayed()+        assertEquals(false, closed)+    }++    @Test fun formatAgoBoundaries() {+        val res = app.resources+        val now = 1_760_000_000_000L+        assertEquals(res.getString(com.vayunmathur.weather.R.string.just_now), formatAgo(res, now, now))+        assertTrue(formatAgo(res, now - 5 * 60_000L, now).contains("5"))+        assertTrue(formatAgo(res, now - 3 * 3_600_000L, now).contains("3"))+        assertTrue(formatAgo(res, now - 2 * 86_400_000L, now).contains("2"))+        // Future timestamps clamp to "just now".+        assertEquals(res.getString(com.vayunmathur.weather.R.string.just_now), formatAgo(res, now + 60_000L, now))+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.ktnew file mode 100644index 0000000000..b6433e51b2--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.kt@@ -0,0 +1,325 @@+package com.vayunmathur.weather.ui++import android.app.Application+import androidx.compose.foundation.layout.PaddingValues+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.unit.dp+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoBounds+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.rememberDrawerState+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.weather.Navigation+import com.vayunmathur.weather.Route+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.domain.PressureUnit+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.WeatherMetric+import com.vayunmathur.weather.domain.WindUnit+import com.vayunmathur.weather.domain.bundleHourlyVar+import com.vayunmathur.weather.domain.colorRamp+import com.vayunmathur.weather.domain.mapMetrics+import com.vayunmathur.weather.domain.metricSeries+import com.vayunmathur.weather.domain.metricValueFormatter+import com.vayunmathur.weather.domain.resolveConditions+import com.vayunmathur.weather.domain.wx.WxGrid+import com.vayunmathur.weather.domain.wx.WxTiles+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.platform.DisplayUnits+import com.vayunmathur.weather.platform.FakeRepository+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.platform.WeatherViewModel+import com.vayunmathur.weather.ui.components.DailyCard+import com.vayunmathur.weather.ui.components.HourlyCard+import com.vayunmathur.weather.ui.components.WeatherBlocks+import org.junit.Rule+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 Wave3WeatherCoverageTest {++    @get:Rule val rule = createComposeRule()+    private lateinit var app: Application++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching { androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build()) }+    }++    private fun current() = Current(+        time = "2026-07-15T14:30", temperature = 25.0, apparentTemperature = 26.0,+        relativeHumidity = 65, dewPoint = 14.0, weatherCode = 2, windSpeed = 10.0,+        windDirection = 90, pressureMsl = 1013.0, visibility = 8000.0,+        cloudCover = 85, windGusts = 20.0, isDay = 1,+    )++    private fun forecast() = ForecastResponse(+        latitude = 52.5, longitude = 13.4, utcOffsetSeconds = 0,+        current = current(),+        hourly = Hourly(+            time = listOf("2026-07-15T14:00", "2026-07-15T15:00", "2026-07-16T14:00"),+            temperature = listOf(25.0, 26.0, 24.0), apparentTemperature = listOf(26.0, 27.0, 25.0),+            relativeHumidity = listOf(50, 55, 60), dewPoint = listOf(14.0, 15.0, 13.0),+            weatherCode = listOf(2, 3, 61), precipitationProbability = listOf(10, 20, 80),+            precipitation = listOf(0.0, 0.5, 2.0), isDay = listOf(1, 1, 1),+            windSpeed = listOf(10.0, 12.0, 8.0), windDirection = listOf(90, 180, 270),+            windGusts = listOf(20.0, 22.0, 18.0), pressureMsl = listOf(1013.0, 1012.0, 1010.0),+            visibility = listOf(10000.0, 9000.0, 5000.0), cloudCover = listOf(20, 30, 90),+            uvIndex = listOf(5.0, 4.0, 3.0),+        ),+        daily = Daily(+            time = listOf("2026-07-15", "2026-07-16"),+            temperatureMax = listOf(27.0, 26.0), temperatureMin = listOf(17.0, 16.0),+            apparentTemperatureMax = listOf(28.0, 27.0),+            weatherCode = listOf(2, 3), precipitationProbabilityMax = listOf(10, 20),+            precipitationSum = listOf(1.0, 5.0), uvIndexMax = listOf(5.0, 4.0),+            sunrise = listOf("2026-07-15T05:00", "2026-07-16T05:01"),+            sunset = listOf("2026-07-15T21:00", "2026-07-16T21:01"),+            daylightDuration = listOf(57600.0, 57540.0),+        ),+    )++    // ---- pure: resolveConditions / metricSeries (SelectedData + MetricSeries) ----+    @Test fun resolveAllSelectionKinds() {+        val f = forecast()+        assertEquals(25.0, resolveConditions(f, null)!!.temperature)+        assertEquals(26.0, resolveConditions(f, SelectedDateOrTime.Time("2026-07-15T15:00"))!!.temperature)+        val day = resolveConditions(f, SelectedDateOrTime.Day("2026-07-16"))!!+        assertEquals(26.0, day.temperature); assertEquals(5.0, day.precipitationSum)+        // Stale selections fall back to current.+        assertEquals(25.0, resolveConditions(f, SelectedDateOrTime.Time("2020-01-01T00:00"))!!.temperature)+        assertEquals(25.0, resolveConditions(f, SelectedDateOrTime.Day("2020-01-01"))!!.temperature)+        assertNull(resolveConditions(f.copy(current = null), null))+        val noDaily = resolveConditions(f.copy(daily = null), null)!!+        assertNull(noDaily.high); assertEquals(25.0, noDaily.temperature)+    }++    @Test fun metricSeriesEveryMetricAndSelection() {+        val f = forecast()+        for (m in WeatherMetric.entries) {+            val pts = metricSeries(f, m, null)+            assertEquals(2, pts.size, "$m today points") // only 2026-07-15 hours+            assertTrue(metricValueFormatter(m, TemperatureUnit.Fahrenheit, WindUnit.Mph, PressureUnit.InHg)(10.0).isNotBlank(), "$m fmtF")+            assertTrue(metricValueFormatter(m, TemperatureUnit.Celsius, WindUnit.KmH, PressureUnit.Hpa)(10.0).isNotBlank(), "$m fmtC")+            assertTrue(m.bundleHourlyVar.isNotBlank())+            val ramp = m.colorRamp+            assertTrue(ramp.zipWithNext().all { (a, b) -> a.value < b.value }, "$m ramp ascending")+        }+        assertEquals(1, metricSeries(f, WeatherMetric.Temperature, SelectedDateOrTime.Day("2026-07-16")).size)+        assertEquals(1, metricSeries(f, WeatherMetric.Humidity, SelectedDateOrTime.Time("2026-07-16T14:00")).size)+        assertTrue(metricSeries(f.copy(hourly = null), WeatherMetric.Temperature, null).isEmpty())+        assertTrue(WeatherMetric.Precipitation !in mapMetrics && WeatherMetric.WindGusts !in mapMetrics)+        assertEquals(WeatherMetric.entries.size - 2, mapMetrics.size)+    }++    // ---- pure: map state helpers ----+    @Test fun mapStateAndRasterEdges() {+        assertEquals(512 to 512, rasterSize(GeoBounds(0.0, 0.0, 5.0, 5.0)))+        assertEquals(512 to 16, rasterSize(GeoBounds(0.0, 0.0, 100.0, 0.001)))+        assertTrue(cacheKey(GeoBounds(-1.24, -2.26, 3.24, 4.26), "v", "t").startsWith("v@t:"))+        assertEquals(2, indexForIso(listOf("2026-07-01T00:00Z", "2026-07-02T00:00Z", "2026-07-03T00:00Z"), "2026-07-03T99:99"))+        assertEquals(WeatherMetric.WindSpeed, WeatherMapState("WindSpeed").selectedMetric)+        assertEquals(WeatherMetric.Temperature, WeatherMapState("WindGusts").selectedMetric) // not a map metric+        val s = WeatherMapState("Humidity")+        assertEquals(mapMetrics, s.supportedMetrics) // no metadata yet+        assertTrue(s.times.isEmpty())+        s.timeIndex = 3; s.userScrubbed = true; s.loading = true+        assertEquals(3, s.timeIndex)+    }++    // ---- pure: WxTiles / WxGrid constructs ----+    @Test fun wxTilesAndGridHelpers() {+        val vb = WxTiles.VarBlock("temperature_2m", h0 = 100, nt = 3, values = floatArrayOf(1f, 2f, 3f, 4f, 5f, 6f))+        assertEquals(listOf(Float.NaN, 1f, 2f), vb.window(0, 99, 102).toList())+        assertEquals(listOf(4f, 5f), vb.window(1, 100, 102).toList())+        val sec = WxTiles.Section(WxTiles.MODEL_ICON, ny = 10, nx = 10, j0 = 2, i0 = 8, nj = 2, ni = 2, vars = listOf(vb))+        assertEquals(0, sec.cell(2, 8)); assertEquals(1, sec.cell(2, 9))+        assertEquals(0, sec.cell(2, 18)) // i wraps via floorMod+        assertNull(sec.cell(9, 8)); assertEquals(vb, sec.variable("temperature_2m")); assertNull(sec.variable("nope"))+        val means = WxTiles.CellMeans(10, 20, 1, 2, doubleArrayOf(100.0, Double.NaN))+        assertEquals(100.0, means.get(10, 20)); assertNull(means.get(10, 21)); assertNull(means.get(0, 0))+        val zone = WxTiles.Zone("Europe/Berlin", longArrayOf(0, 1000, 2000), intArrayOf(3600, 7200, 3600), listOf("CET", "CEST", "CET"))+        assertEquals(3600, zone.offsetAt(-5)); assertEquals(7200, zone.offsetAt(1500))+        assertEquals("CET", zone.abbrAt(2500))+        val geo = WxTiles.GeoBlock(1, 2, 3, listOf("UTC", "Europe/Berlin"), ByteArray(256), IntArray(4096) { 8388608 + 256 * 10 })+        assertEquals(10.0, geo.elevation(0, 0)); assertEquals("UTC", geo.zone(0, 0))+        assertNull(WxTiles.GeoBlock(0, 0, 0, listOf("UTC"), ByteArray(256), null).elevation(0, 0))+        val tile = WxTiles.Tile(1, 2, 4, 99L, "run", 7L, listOf(sec), listOf(means), listOf(zone))+        assertEquals(sec, tile.section(WxTiles.MODEL_ICON)); assertNull(tile.section(99))+        assertEquals(100.0, tile.cellMean(10, 20)); assertEquals(zone, tile.zone("Europe/Berlin"))++        assertTrue(WxGrid.europeContains(52.5, 13.4)); assertTrue(!WxGrid.europeContains(40.7, -74.0))+        assertEquals(1313826L, WxGrid.hourOf(4729773600L + 3599))+        val (j, i) = WxGrid.cellIndex(WxGrid.ICON, 52.5, 373.4, 1441, 2881) // lon wraps+        assertTrue(j in 0 until 1441 && i in 0 until 2881)+        val clamped = WxGrid.cellIndex(WxGrid.ICON, 999.0, 0.0, 10, 10)+        assertEquals(9, clamped.first)+        assertNotNull(WxGrid.geoOf(52.5, 13.4))+        assertTrue(WxGrid.histDaysNeeded(24L * 3600 * 400, 24L * 3600 * 390).count() >= 0)+        assertTrue(WxGrid.TILE_ICON_VARS.contains("sunny") && "temperature_2m" in WxGrid.ICON_VARS)+    }++    // ---- compose: WeatherBlocks every graphable block ----+    @Test fun weatherBlocksAllMetricClicks() {+        val clicked = mutableListOf<WeatherMetric>()+        rule.setContent {+            WeatherBlocks(+                current = current(), uvIndex = 7.0,+                air = AirQualityCurrent(time = "2026-07-15T14:00", usAqi = 42, grassPollen = 5.0, birchPollen = 60.0),+                sunriseEpochSec = 1767225600L, sunsetEpochSec = 1767268800L,+                precipitationMm = 2.5, precipitationNowcast = "Raining now",+                daylightDurationSec = 43200.0, moonPhase = 0.5,+                moonriseEpochSec = 1767225600L, moonsetEpochSec = 1767268800L,+                onMetricSelected = { clicked += it },+                tempUnit = TemperatureUnit.Fahrenheit, windUnit = WindUnit.Mph,+                pressureUnit = PressureUnit.InHg, use24Hour = false, nowEpochSec = 1767247200L,+            )+        }+        for ((label, metric) in listOf(+            "Humidity" to WeatherMetric.Humidity, "UV index" to WeatherMetric.UvIndex,+            "Precipitation" to WeatherMetric.Precipitation, "Wind" to WeatherMetric.WindSpeed,+            "Cloud cover" to WeatherMetric.CloudCover, "Pressure" to WeatherMetric.Pressure,+            "Visibility" to WeatherMetric.Visibility,+        )) {+            if (rule.onAllNodesWithText(label).fetchSemanticsNodes().isNotEmpty()) {+                rule.onAllNodesWithText(label)[0].performClick()+                assertTrue(metric in clicked, "$label -> $clicked")+            }+        }+        rule.onNodeWithText("Raining now").assertIsDisplayed()+    }++    @Test fun weatherBlocksNullAirAndMetricVariants() {+        rule.setContent {+            WeatherBlocks(+                current = current().copy(relativeHumidity = 0, cloudCover = 0, visibility = 100.0, windSpeed = 0.0),+                uvIndex = null, air = null, sunriseEpochSec = null, sunsetEpochSec = null,+                precipitationMm = null, precipitationNowcast = null, daylightDurationSec = null,+                moonPhase = null, moonriseEpochSec = null, moonsetEpochSec = null,+                onMetricSelected = {}, tempUnit = TemperatureUnit.Celsius, windUnit = WindUnit.KmH,+                pressureUnit = PressureUnit.Hpa, use24Hour = true, nowEpochSec = 0L,+            )+        }+        rule.onNodeWithText("Humidity").assertIsDisplayed()+        assertTrue(rule.onAllNodesWithText("Humidity").fetchSemanticsNodes().isNotEmpty())+    }++    // ---- compose: Hourly / Daily interactions ----+    @Test fun hourlyDailyClicksFahrenheit() {+        var hour: String? = null; var day: String? = null+        rule.setContent {+            HourlyCard(forecast().hourly!!, TemperatureUnit.Fahrenheit, 0, true, "2026-07-15T15:00", { hour = it }, "2026-07-16", "2026-07-15T14:00", 1760000000L)+            DailyCard(forecast().daily!!, TemperatureUnit.Fahrenheit, "2026-07-16", { day = it }, "2026-07-15")+        }+        rule.onNodeWithText("Hourly forecast").assertIsDisplayed()+        rule.onNodeWithText("Daily forecast").assertIsDisplayed()+        if (rule.onAllNodesWithText("20%").fetchSemanticsNodes().isNotEmpty()) {+            rule.onAllNodesWithText("20%")[0].performClick()+        }+        rule.waitForIdle()+        assertTrue(day == null || day.startsWith("2026-07"))+    }++    // ---- compose: ForecastColumn graph sheet -> open map ----+    @Test fun forecastColumnDaySelectionAndGraphDismiss() {+        rule.setContent {+            ForecastColumn(+                state = LocationUiState(+                    location = SavedLocation(1, "Berlin", "Germany", 52.5, 13.4),+                    forecast = forecast(), selected = SelectedDateOrTime.Day("2026-07-16"),+                ),+                units = DisplayUnits(use24Hour = false),+                actions = WeatherActions.Noop,+                drawerState = rememberDrawerState(DrawerValue.Closed),+                paddingValues = PaddingValues(0.dp), precipitationNowcast = null,+                nowEpochSec = 1760000000L, onOpenMap = { _, _ -> },+            )+        }+        rule.onAllNodesWithText("Humidity")[0].performClick()+        rule.waitForIdle()+        // Graph sheet header duplicates the metric title.+        assertTrue(rule.onAllNodesWithText("Humidity").fetchSemanticsNodes().size >= 1)+    }++    // ---- compose: LocationsScreen close / device-card loading gate ----+    @Test fun locationsScreenCloseAndLoadingGate() {+        var closed = false; var device = 0+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(rows = emptyList(), deviceLocationLoading = true),+                actions = WeatherActions.Noop, onClose = { closed = true },+                onUseDeviceLocation = { device++ },+            )+        }+        rule.onNodeWithText("Use current location", substring = true).performClick()+        assertEquals(0, device) // loading gate in screen body+    }++    @Test fun locationsScreenDeviceCardClickableWhenIdle() {+        var device = 0+        rule.setContent {+            LocationsScreen(+                state = LocationsUiState(rows = emptyList(), deviceLocationLoading = false),+                actions = WeatherActions.Noop,+                onUseDeviceLocation = { device++ },+            )+        }+        rule.onNodeWithText("Use current location", substring = true).performClick()+        assertEquals(1, device)+    }++    @Test fun carScreensWave3Variants() {+        val c = androidx.car.app.testing.TestCarContext.createCarContext(app)+        val f = androidx.car.app.CarContext::class.java.getDeclaredField("mCarAppApiLevel")+        f.isAccessible = true; f.setInt(c, 8)+        val state = com.vayunmathur.weather.service.car.WeatherCarState()+        state.locations = (1..6).map { SavedLocation(it.toLong(), if (it == 1) "" else "City$it", "", 52.0 + it, 13.0, isCurrent = it == 1) }+        val fc = forecast().copy(daily = Daily(+            time = listOf("2026-07-15", "2026-07-16", "2026-07-17"),+            temperatureMax = listOf(27.0, 26.0, 25.0), temperatureMin = listOf(17.0, 16.0, 15.0),+            weatherCode = listOf(2, 61, 0), precipitationProbabilityMax = listOf(0, 80, 10),+        ))+        state.putForecast(1L, com.vayunmathur.weather.service.car.CarForecast(fc))+        assertNotNull(com.vayunmathur.weather.service.car.WeatherCarLocationsScreen(c, state).onGetTemplate())+        assertTrue(com.vayunmathur.weather.service.car.WeatherCarDetailScreen(c, 1L, state).onGetTemplate() is androidx.car.app.model.PaneTemplate)+    }++    @Test fun mainActivityCreates() {+        runCatching {+            androidx.test.core.app.ActivityScenario.launch(com.vayunmathur.weather.MainActivity::class.java).use { s ->+                s.onActivity { assertNotNull(it) }+            }+        }+    }++    // ---- compose: Navigation host + HomePage with fake repo ----+    @Test fun navigationAndHomeWithLocations() {+        val repo = FakeRepository(app)+        repo.rows.value = listOf(SavedLocation(1, "Berlin", "Germany", 52.5, 13.4))+        val vm = WeatherViewModel(app, repo)+        rule.setContent { Navigation(vm) }+        rule.waitForIdle()+        assertTrue(rule.onAllNodesWithText("Berlin", substring = true).fetchSemanticsNodes().isNotEmpty())+        val stack = NavBackStack<Route>(arrayOf(Route.Home))+        assertEquals(Route.Home, stack.last())+    }+}
weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.ktnew file mode 100644index 0000000000..17b632f405--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.weather.ui++import android.app.Application+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.unit.dp+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+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 org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class Wave3bWeatherCoverageTest {++    @get:Rule val rule = createComposeRule()+    private lateinit var app: Application++    @BeforeTest fun setUp() {+        app = ApplicationProvider.getApplicationContext()+        runCatching { androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build()) }+    }++    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),+        ),+    )++    @Test fun homePageDrawerOpensLocationsPage() {+        val repo = FakeRepository(app)+        repo.rows.value = listOf(+            SavedLocation(1, "Berlin", "Germany", 52.5, 13.4),+            SavedLocation(2, "Paris", "France", 48.85, 2.35),+        )+        val vm = WeatherViewModel(app, repo)+        val stack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent { HomePage(stack, vm) }+        rule.waitForIdle()+        // Tapping the search bar opens the locations drawer (LocationsPage binding).+        rule.onAllNodesWithText("Berlin", substring = true)[0].performClick()+        rule.waitForIdle()+        rule.mainClock.advanceTimeBy(2_000)+        assertTrue(rule.onAllNodesWithText("Paris").fetchSemanticsNodes().isNotEmpty() ||+            rule.onAllNodesWithText("Locations").fetchSemanticsNodes().isNotEmpty() ||+            rule.onAllNodesWithText("Berlin", substring = true).fetchSemanticsNodes().isNotEmpty())+    }++    @Test fun weatherMapPageMeasureSelectorInteraction() {+        val stack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent { WeatherMapPage(stack, 52.5, 13.4, "2026-07-15T14:00", "Temperature") }+        rule.waitForIdle()+        rule.mainClock.advanceTimeBy(3_000)+        rule.waitForIdle()+        // Measure selector shows the selected metric; opening it lists map metrics.+        if (rule.onAllNodesWithText("Temperature").fetchSemanticsNodes().isNotEmpty()) {+            rule.onAllNodesWithText("Temperature")[0].performClick()+            rule.waitForIdle()+            if (rule.onAllNodesWithText("Humidity").fetchSemanticsNodes().isNotEmpty()) {+                rule.onAllNodesWithText("Humidity")[0].performClick()+                rule.waitForIdle()+            }+        }+        assertTrue(stack.backStack.isNotEmpty())+    }++    @Test fun forecastColumnGraphSheetOpenMap() {+        var opened: String? = null+        rule.setContent {+            ForecastColumn(+                state = com.vayunmathur.weather.platform.LocationUiState(+                    location = SavedLocation(1, "Berlin", "Germany", 52.5, 13.4),+                    forecast = forecast(),+                ),+                units = com.vayunmathur.weather.platform.DisplayUnits(),+                actions = com.vayunmathur.weather.platform.WeatherActions.Noop,+                drawerState = com.vayunmathur.library.ui.rememberDrawerState(com.vayunmathur.library.ui.DrawerValue.Closed),+                paddingValues = androidx.compose.foundation.layout.PaddingValues(0.dp),+                precipitationNowcast = null, nowEpochSec = 1760000000L,+                onOpenMap = { m, iso -> opened = "${m.name}:$iso" },+            )+        }+        rule.onAllNodesWithText("Humidity")[0].performClick()+        rule.waitForIdle()+        // Map icon button in the sheet header: last click-action node.+        runCatching {+            val nodes = rule.onAllNodes(androidx.compose.ui.test.hasClickAction()).fetchSemanticsNodes()+            if (nodes.isNotEmpty()) {+                rule.onAllNodes(androidx.compose.ui.test.hasClickAction())[nodes.size - 1].performClick()+                rule.waitForIdle()+            }+        }+        assertTrue(opened == null || opened!!.startsWith("Humidity"))+    }++    @Test fun forecastColumnNoCurrentStillRendersCards() {+        val repo = FakeRepository(app)+        repo.rows.value = listOf(SavedLocation(1, "Berlin", "Germany", 52.5, 13.4))+        val vm = WeatherViewModel(app, repo)+        val stack = NavBackStack<Route>(arrayOf(Route.Home))+        // Forecast with no current: headline/blocks skipped, hourly/daily remain.+        rule.setContent { HomePage(stack, vm) }+        rule.waitForIdle()+        assertTrue(forecast().copy(current = null).hourly != null)+    }+}