Modern Apps git

← Modern-Apps.git

weather: make the network-failure tests hermetic

Commit
4481de6d83448423ca6167ba3fc56b896e135fdc
Author
Vayun Mathur <[email protected]>
When
2026-11-07 19:50 UTC (28 days ago)
Parents
da7eb41
The 'network failure' tests passed only where the ambient network
was unreachable. The CI box has internet, so WeatherApi.bundle
really fetched api.maproj.org and live data flowed into assertions
that expected an error (6 failures in run 8f356294).

- WeatherViewModel takes a bundleFetcher seam (default
  WeatherApi.bundle); ViewModelFetchTest and ViewModelDeviceFixTest
  inject a throwing fetcher, which is what their FakeRepository setup
  always intended.
- WeatherApi gains a VisibleForTesting bundleBaseOverride;
  apiBundleFailsWithoutNetwork points it at a dead loopback port so
  the failure happens on any box, and always resets it afterwards.

Verified: :weather:testDevUnitTest green locally (was already green
here by accident of this devserver having no internet — the tests
are now hermetic by construction).

Diff

weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.ktindex 2aba5ec8ed..c25b342097 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt@@ -17,6 +17,13 @@ object WeatherApi {      private const val BUNDLE_BASE = "https://api.maproj.org/wx/v1" +    // Test seam: point the bundle API at an unroutable address so the+    // failure-path tests are hermetic on boxes that have internet.+    @androidx.annotation.VisibleForTesting+    internal var bundleBaseOverride: String? = null++    private val bundleBase: String get() = bundleBaseOverride ?: BUNDLE_BASE+     /**      * Fetch the full bundle (current + hourly + daily + 15-min + AQ) for a      * single coordinate. Single HTTP call. Throws on network / parse failure@@ -24,7 +31,7 @@ object WeatherApi {      */     suspend fun bundle(latitude: Double, longitude: Double, fields: String = "all"): WxBundle {         val url = buildString {-            append(BUNDLE_BASE).append("/bundle")+            append(bundleBase).append("/bundle")             append("?lat=").append(latitude)             append("&lon=").append(longitude)             append("&fields=").append(fields)@@ -76,7 +83,7 @@ object WeatherApi {     suspend fun currentTemperatures(points: List<Pair<Double, Double>>): Map<Pair<Double, Double>, Double> {         if (points.isEmpty()) return emptyMap()         val url = buildString {-            append(BUNDLE_BASE).append("/current?points=")+            append(bundleBase).append("/current?points=")             append(points.take(20).joinToString("|") { (lat, lon) -> "$lat,$lon" })         }         val batch: WxCurrentBatch = NetworkClient.getJson(url)
weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.ktindex 59714b5a75..d479e856e5 100644--- a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt+++ b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt@@ -17,6 +17,7 @@ import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget import com.vayunmathur.weather.network.AirQualityResponse import com.vayunmathur.weather.network.ForecastResponse import com.vayunmathur.weather.network.WeatherApi+import com.vayunmathur.weather.network.WxBundle import com.vayunmathur.weather.network.toAirQuality import com.vayunmathur.weather.network.toForecastResponse import kotlinx.coroutines.flow.MutableStateFlow@@ -40,6 +41,13 @@ data class ForecastUiState( class WeatherViewModel(     application: Application,     private val repository: WeatherRepository,+    // Test seam: the bundle fetch, so unit tests can force the offline path+    // instead of depending on the ambient network being unreachable (on a+    // box with internet the old tests' "network failure" never happened and+    // live data flowed into assertions). Production uses WeatherApi.+    private val bundleFetcher: suspend (Double, Double) -> WxBundle = { lat, lon ->+        WeatherApi.bundle(lat, lon)+    }, ) : AndroidViewModel(application), WeatherActions {      val savedLocations: StateFlow<List<SavedLocation>?> = repository.locations@@ -145,7 +153,7 @@ class WeatherViewModel(             current + (location.id to refreshing)         }         // One bundle call carries forecast + AQ (same object, zero extra I/O).-        val bundle = runCatching { WeatherApi.bundle(target.latitude, target.longitude) }+        val bundle = runCatching { bundleFetcher(target.latitude, target.longitude) }         val fetched = FetchResult(             forecast = bundle.map { it.toForecastResponse() },             air = bundle.map { it.toAirQuality() }.getOrNull(),
weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.ktindex cf13952df9..8d5dc1a43a 100644--- a/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt@@ -64,17 +64,25 @@ class GeoAndWorkerTest {      @JUnitTest(timeout = 60_000)     fun apiBundleFailsWithoutNetwork() = runTest {+        // Hermetic: point the API at a dead loopback port so the failure+        // happens on internet-connected boxes too (CI reached the real+        // api.maproj.org and the "expected failure" never came).+        com.vayunmathur.weather.network.WeatherApi.bundleBaseOverride = "https://127.0.0.1:9/wx/v1"         try {-            WeatherApi.bundle(52.0, 13.0)-            fail("expected network failure")-        } catch (e: Exception) {-            assertTrue(e.message != null || e is RuntimeException)-        }-        try {-            WeatherApi.currentTemperatures(listOf(52.0 to 13.0))-            fail("expected network failure")-        } catch (e: Exception) {-            assertTrue(true)+            try {+                WeatherApi.bundle(52.0, 13.0)+                fail("expected network failure")+            } catch (e: Exception) {+                assertTrue(e.message != null || e is RuntimeException)+            }+            try {+                WeatherApi.currentTemperatures(listOf(52.0 to 13.0))+                fail("expected network failure")+            } catch (e: Exception) {+                assertTrue(true)+            }+        } finally {+            com.vayunmathur.weather.network.WeatherApi.bundleBaseOverride = null         }     } }
weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.ktindex 1a3f9e9ca2..3d8899a06c 100644--- a/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt@@ -31,7 +31,9 @@ class ViewModelFetchTest {             androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())         }         repo = FakeRepository(app)-        vm = WeatherViewModel(app, repo)+        // Hermetic offline: the fetch always fails, on any box (these tests+        // previously relied on the ambient network being unreachable).+        vm = WeatherViewModel(app, repo) { _, _ -> throw java.io.IOException("offline (test)") }     }      private fun await(cond: () -> Boolean): Boolean {@@ -123,7 +125,9 @@ class ViewModelDeviceFixTest {             android.Manifest.permission.ACCESS_FINE_LOCATION,         )         repo = FakeRepository(app)-        vm = WeatherViewModel(app, repo)+        // Hermetic offline: the fetch always fails, on any box (these tests+        // previously relied on the ambient network being unreachable).+        vm = WeatherViewModel(app, repo) { _, _ -> throw java.io.IOException("offline (test)") }     }      private fun setFix(lat: Double, lon: Double) {