Modern Apps git

← Modern-Apps.git

astronomy: add tests for catalogs, location, sky map and detail

Commit
cadfabcc534bc05d15fd1b0d50a7c69486af5104
Author
Vayun Mathur <[email protected]>
When
2026-11-07 14:24 UTC (29 days ago)
Parents
59cb25a
Pass 3. Merged INSTRUCTION coverage 54.70% (10122/18506) -> 91.84%
(17031/18544); unit suite 116 tests green, instrumented
LaunchNoCrashTest green on the emulator (it crashed before the
CoordinateTransforms fix in the preceding commit).

New tests: built-in fallback catalog shape and cross-references;
CatalogRepository missing/corrupt/well-formed asset handling through
the new loader seam; model and planet-id behaviour; LocationProvider
permission gating, last-known recency and the live-listener path
against Robolectric's location shadow, plus the view model's
refreshLocation adopting a fix; SkyMapScreen top-bar routing, camera
toggle, scrubber seeding and night mode (the NavResultRegistry the
screen needs is provided in the test composition - no production
change); SkyCanvas rasterisation of every layer with native
graphics (grid, constellation lines and figure art over the real
orion.png, planets, sun/moon, deep-sky, trajectory, selection rings)
and its tap hit-testing; SkyArt colour/radius/matrix helpers;
ObjectDetail pages for moon, planets, catalog stars, deep-sky and
not-found ids; SettingsScreen switch/select/form interactions;
Navigation graph composition and Route serializer round-trips;
MainActivity under Robolectric; engine edges (lunar phase bands,
refraction, circumpolar/never-up/moving-object rise-set, batch vs
one-by-one transform agreement); projection mesh culling, centre
and rotated round-trips, and projectAll batch consistency.

Untestable remainder: CameraBackground's granted-permission bind
path (needs a real camera; the denied path is covered), the
drag/pinch gesture detectors (synthetic single-pointer injection
under Robolectric does not trigger them; tap hit-testing is
covered), sensor-driven device pointing, and SkyCanvas gesture
lambdas.

(cherry picked from commit 036e0b490e737f7da0e954c6a1467ef55cc85fa2)

Diff

astronomy/src/test/java/com/vayunmathur/astronomy/MainActivityRoboTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/MainActivityRoboTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/MainActivityRoboTest.ktnew file mode 100644index 0000000000..67da876d1a--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/MainActivityRoboTest.kt@@ -0,0 +1,35 @@+package com.vayunmathur.astronomy++import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import kotlin.test.assertFalse++/**+ * Robolectric tests for [MainActivity]: it creates, composes the+ * permission gate / navigation, and tears down cleanly on the JVM.+ * Location permission starts ungranted, so the gate is what composes;+ * the sky itself is covered by the screen tests.+ */+@RunWith(AndroidJUnit4::class)+class MainActivityRoboTest {++    @Test+    fun `activity creates and destroys cleanly`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        assertFalse(activity.isFinishing)+        controller.pause().stop().destroy()+    }++    @Test+    fun `activity survives a restart cycle`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        controller.setup()+        controller.restart()+        val activity = controller.get()+        assertFalse(activity.isFinishing)+        controller.pause().stop().destroy()+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/NavigationRouteTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/NavigationRouteTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/NavigationRouteTest.ktnew file mode 100644index 0000000000..d8819e1bf9--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/NavigationRouteTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.astronomy++import android.app.Application+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.astronomy.platform.AstronomyViewModel+import com.vayunmathur.library.util.LocalNavResultRegistry+import com.vayunmathur.library.util.NavResultRegistry+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.datetime.LocalDate+import kotlinx.serialization.json.Json+import org.junit.After+import org.junit.Before+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals++/**+ * Tests for the app [Navigation] graph and the [Route] serializers the+ * back stack persists: the graph composes the sky map entry, top-bar+ * navigation reaches the search entry, and every route round-trips.+ */+@OptIn(ExperimentalCoroutinesApi::class, kotlin.time.ExperimentalTime::class)+@RunWith(AndroidJUnit4::class)+class NavigationRouteTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+    }++    @After+    fun tearDown() {+        Dispatchers.resetMain()+    }++    @Test+    fun `navigation composes the sky map and reaches search`() {+        val viewModel = AstronomyViewModel(app)+        composeRule.setContent {+            CompositionLocalProvider(LocalNavResultRegistry provides NavResultRegistry()) {+                Navigation(viewModel)+            }+        }+        composeRule.waitForIdle()+        composeRule.onNodeWithContentDescription("Search").assertIsDisplayed()+        composeRule.onNodeWithContentDescription("Search").performClick()+        composeRule.waitForIdle()+        // The search entry is now on top; its box takes queries.+        composeRule.onNodeWithContentDescription("Settings").assertDoesNotExist()+    }++    @Test+    fun `routes round-trip through their serializers`() {+        val json = Json+        val routes: List<Route> = listOf(+            Route.SkyMap,+            Route.Search,+            Route.Settings,+            Route.ObjectDetail("PLANET_MARS"),+            Route.HistoryDatePicker(LocalDate(2026, 1, 15)),+        )+        for (route in routes) {+            val encoded = json.encodeToString(Route.serializer(), route)+            val decoded = json.decodeFromString(Route.serializer(), encoded)+            assertEquals(route, decoded, "round trip failed for $encoded")+        }+        // Distinct routes encode distinctly (the stack can tell them apart).+        assertNotEquals(+            json.encodeToString(Route.serializer(), Route.SkyMap),+            json.encodeToString(Route.serializer(), Route.Search),+        )+        assertEquals(+            "PLANET_MARS",+            (Json.decodeFromString(Route.serializer(), Json.encodeToString(Route.serializer(), Route.ObjectDetail("PLANET_MARS"))) as Route.ObjectDetail).id,+        )+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/data/BuiltInCatalogsTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/data/BuiltInCatalogsTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/data/BuiltInCatalogsTest.ktnew file mode 100644index 0000000000..5e62bff26d--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/data/BuiltInCatalogsTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.astronomy.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Sanity tests for the built-in fallback catalogs: these are what the app+ * shows when the bundled JSON assets cannot be read, so their shape and+ * cross-references must hold on their own.+ */+class BuiltInCatalogsTest {++    @Test+    fun `brightest built-in star is Sirius and named stars come first`() {+        val stars = BuiltInCatalogs.stars+        assertEquals("Sirius", stars.first().properName)+        assertEquals(-1.44, stars.first().mag)+        // The named stars come first and are all bright.+        val named = stars.takeWhile { it.properName != null }+        assertTrue(named.size >= 20)+        assertTrue(named.all { it.mag < 3.0 })+        assertTrue(stars.all { it.ra in 0.0..(2 * Math.PI) })+        assertTrue(stars.all { it.dec in -Math.PI / 2..Math.PI / 2 })+    }++    @Test+    fun `filler stars are deterministic and complete the catalog`() {+        val stars = BuiltInCatalogs.stars+        val namedCount = stars.takeWhile { it.properName != null }.size+        assertEquals(namedCount + 4000, stars.size)+        val filler = stars.dropWhile { it.properName != null }+        assertTrue(filler.all { it.name == null && it.properName == null })+        assertEquals((100 until 4100).toList(), filler.map { it.id })+        assertTrue(filler.all { it.mag in 3.5..6.5 })+        // Unique ids across the whole catalog.+        assertEquals(stars.size, stars.map { it.id }.toSet().size)+    }++    @Test+    fun `constellation lines only reference built-in stars`() {+        val starIds = BuiltInCatalogs.stars.map { it.id }.toSet()+        assertTrue(BuiltInCatalogs.constellations.isNotEmpty())+        for (constellation in BuiltInCatalogs.constellations) {+            assertTrue(constellation.lines.isNotEmpty(), constellation.abbr)+            for (line in constellation.lines) {+                assertEquals(2, line.size)+                assertTrue(line.all { it in starIds }, "${constellation.abbr}: $line")+            }+        }+        assertTrue(BuiltInCatalogs.constellations.any { it.abbr == "Ori" && it.name == "Orion" })+    }++    @Test+    fun `messier fallback holds the bright showpieces`() {+        val byId = BuiltInCatalogs.messier.associateBy { it.id }+        assertEquals("Andromeda Galaxy", byId["M31"]?.name)+        assertEquals("Orion Nebula", byId["M42"]?.name)+        assertNotNull(byId["M45"])+        assertTrue(BuiltInCatalogs.messier.all { it.mag < 9.0 })+        assertTrue(BuiltInCatalogs.messier.all { it.ra in 0.0..(2 * Math.PI) })+    }++    @Test+    fun `orbital fallback has the sun earth and planets in order`() {+        val orbital = BuiltInCatalogs.orbital+        assertEquals("SUN", orbital.first().id)+        val earth = orbital.firstOrNull { it.id == "EARTH" }+        assertNotNull(earth)+        assertEquals(1.0, earth.a)+        val ids = orbital.map { it.id }+        for (planet in listOf("MERCURY", "VENUS", "MARS", "JUPITER", "SATURN")) {+            assertTrue(planet in ids, planet)+        }+        // Semi-major axes grow with distance from the Sun.+        val byId = orbital.associateBy { it.id }+        val solarOrder = listOf("MERCURY", "VENUS", "EARTH", "MARS", "JUPITER", "SATURN")+        val axes = solarOrder.map { byId.getValue(it).a }+        assertEquals(axes, axes.sorted())+        assertTrue(orbital.drop(1).all { it.e in 0.0..1.0 })+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogModelsTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogModelsTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogModelsTest.ktnew file mode 100644index 0000000000..55e7ac27f6--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogModelsTest.kt@@ -0,0 +1,53 @@+package com.vayunmathur.astronomy.data++import com.vayunmathur.astronomy.data.model.OrbitalElements+import com.vayunmathur.astronomy.data.model.PlanetId+import com.vayunmathur.astronomy.data.model.Star+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++/** Model tests: planet ids, orbital element defaults and star equality. */+class CatalogModelsTest {++    @Test+    fun `planet ids cover the sun moon and eight planets with resources`() {+        assertEquals(9, PlanetId.entries.size)+        assertEquals(PlanetId.SUN, PlanetId.valueOf("SUN"))+        assertEquals(PlanetId.NEPTUNE, PlanetId.valueOf("NEPTUNE"))+        assertTrue(PlanetId.entries.all { it.displayNameRes != 0 })+        assertEquals(+            PlanetId.entries.map { it.name },+            PlanetId.entries.map { it.toString() },+        )+    }++    @Test+    fun `orbital elements default the optional fields and copy cleanly`() {+        val mars = OrbitalElements("MARS", "Mars", 1.52, 0.09, 1.85, 49.5, 286.4, 355.4, 355.4, 0.524)+        assertEquals(null, mars.diameterKm)+        assertEquals(null, mars.colorArgb)+        assertEquals(null, mars.magBase)+        val bigger = mars.copy(diameterKm = 6779.0)+        assertEquals(6779.0, bigger.diameterKm)+        assertEquals(mars.a, bigger.a)+        assertNotEquals(mars, bigger)+        assertEquals(mars, mars.copy())+        assertEquals(mars.hashCode(), mars.copy().hashCode())+    }++    @Test+    fun `star defaults and component accessors`() {+        val star = Star(id = 5, ra = 1.0, dec = 0.5, mag = 2.0)+        assertEquals(0.0, star.bv)+        assertEquals(null, star.name)+        assertEquals(null, star.constellation)+        val (id, ra, dec, mag) = star+        assertEquals(5, id)+        assertEquals(1.0, ra)+        assertEquals(0.5, dec)+        assertEquals(2.0, mag)+        assertTrue(star.toString().contains("5"))+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogRepositoryFallbackTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogRepositoryFallbackTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogRepositoryFallbackTest.ktnew file mode 100644index 0000000000..61420f63bd--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/data/CatalogRepositoryFallbackTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.astronomy.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.runBlocking+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Fallback tests for [CatalogRepository] through its asset-loader seam:+ * missing assets and corrupt JSON both fall back to the built-in catalogs,+ * while well-formed asset JSON (catalog-shaped or bare-list) is honoured.+ */+@RunWith(AndroidJUnit4::class)+class CatalogRepositoryFallbackTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `missing assets fall back to the built-in catalogs`() {+        runBlocking {+        val repo = CatalogRepository(context) { null }+        repo.loadAll()+        assertEquals(BuiltInCatalogs.stars, repo.stars)+        assertEquals(BuiltInCatalogs.constellations, repo.constellations)+        assertEquals(BuiltInCatalogs.messier, repo.deepSky)+        assertEquals(BuiltInCatalogs.orbital, repo.planets)+        assertEquals("EARTH", repo.earth?.id)+        // Constellation art has no built-in fallback.+        assertTrue(repo.constellationArt.isEmpty())+        }+    }++    @Test+    fun `corrupt assets fall back to the built-in catalogs`() {+        runBlocking {+        val repo = CatalogRepository(context) { "this is not json {{{" }+        repo.loadAll()+        assertEquals(BuiltInCatalogs.stars, repo.stars)+        assertEquals(BuiltInCatalogs.constellations, repo.constellations)+        assertEquals(BuiltInCatalogs.messier, repo.deepSky)+        assertEquals(BuiltInCatalogs.orbital, repo.planets)+        assertTrue(repo.constellationArt.isEmpty())+        }+    }++    @Test+    fun `well-formed catalog-shaped assets are honoured`() {+        runBlocking {+        val assets = mapOf(+            "catalog/stars.json" to """{"stars":[{"id":42,"ra":1.0,"dec":0.5,"mag":2.0,"properName":"Answer"}]}""",+            "catalog/constellations.json" to """{"constellations":[{"abbr":"Tst","name":"Test","lines":[[42,42]]}]}""",+            "catalog/constellation_art.json" to """{"art":[{"abbr":"Tst","image":"tst.png","anchors":[{"x":1,"y":2,"hip":42}]}]}""",+            "catalog/messier.json" to """{"objects":[{"id":"M99","name":"Test Galaxy","ra":1.0,"dec":0.5,"mag":5.0,"type":"galaxy"}]}""",+            "catalog/orbital_elements.json" to """{"planets":[{"id":"EARTH","name":"Earth","a":1.0,"e":0.0,"iDeg":0.0,"omegaDeg":0.0,"wDeg":0.0,"lDeg":0.0,"m0Deg":0.0,"nDegPerDay":1.0}]}""",+        )+        val repo = CatalogRepository(context) { path -> assets[path] }+        repo.loadAll()+        assertEquals(listOf(42), repo.stars.map { it.id })+        assertEquals("Answer", repo.stars.single().properName)+        assertEquals("Tst", repo.constellations.single().abbr)+        assertEquals("tst.png", repo.constellationArt.single().image)+        assertEquals(listOf("M99"), repo.deepSky.map { it.id })+        assertEquals("EARTH", repo.earth?.id)+        assertEquals(1, repo.planets.size)+        }+    }++    @Test+    fun `bare-list asset shapes are honoured`() {+        runBlocking {+        val assets = mapOf(+            "catalog/stars.json" to """[{"id":7,"ra":0.1,"dec":0.2,"mag":3.0}]""",+            "catalog/constellations.json" to """[{"abbr":"Lst","name":"List","lines":[]}]""",+            "catalog/constellation_art.json" to """[{"abbr":"Lst","image":"l.png","anchors":[]}]""",+            "catalog/messier.json" to """[{"id":"M1","name":"Crab","ra":1.4,"dec":0.38,"mag":8.4,"type":"nebula"}]""",+            "catalog/orbital_elements.json" to """[{"id":"MARS","name":"Mars","a":1.52,"e":0.09,"iDeg":1.85,"omegaDeg":49.5,"wDeg":286.4,"lDeg":355.4,"m0Deg":355.4,"nDegPerDay":0.524}]""",+        )+        val repo = CatalogRepository(context) { path -> assets[path] }+        repo.loadAll()+        assertEquals(listOf(7), repo.stars.map { it.id })+        assertEquals("Lst", repo.constellations.single().abbr)+        assertEquals("l.png", repo.constellationArt.single().image)+        assertEquals(listOf("M1"), repo.deepSky.map { it.id })+        assertEquals(listOf("MARS"), repo.planets.map { it.id })+        // No EARTH in this orbital list.+        assertEquals(null, repo.earth)+        assertNotNull(repo.stars.single())+        }+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/EngineEdgeCasesTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/EngineEdgeCasesTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/EngineEdgeCasesTest.ktnew file mode 100644index 0000000000..56d4786b91--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/EngineEdgeCasesTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.astronomy.domain.engine++import kotlin.math.PI+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Edge and boundary tests for the engine helpers the happy-path suites skip. */+class EngineEdgeCasesTest {++    @Test+    fun `phase names cover every band and boundary`() {+        assertEquals("New Moon", LunarCalculator.phaseName(0.0))+        assertEquals("New Moon", LunarCalculator.phaseName(0.02))+        assertEquals("New Moon", LunarCalculator.phaseName(0.98))+        assertEquals("New Moon", LunarCalculator.phaseName(1.0))+        assertEquals("Waxing Crescent", LunarCalculator.phaseName(0.03))+        assertEquals("Waxing Crescent", LunarCalculator.phaseName(0.21))+        assertEquals("First Quarter", LunarCalculator.phaseName(0.22))+        assertEquals("First Quarter", LunarCalculator.phaseName(0.27))+        assertEquals("Waxing Gibbous", LunarCalculator.phaseName(0.28))+        assertEquals("Waxing Gibbous", LunarCalculator.phaseName(0.46))+        assertEquals("Full Moon", LunarCalculator.phaseName(0.47))+        assertEquals("Full Moon", LunarCalculator.phaseName(0.52))+        assertEquals("Waning Gibbous", LunarCalculator.phaseName(0.53))+        assertEquals("Waning Gibbous", LunarCalculator.phaseName(0.71))+        assertEquals("Last Quarter", LunarCalculator.phaseName(0.72))+        assertEquals("Last Quarter", LunarCalculator.phaseName(0.77))+        assertEquals("Waning Crescent", LunarCalculator.phaseName(0.78))+        assertEquals("Waning Crescent", LunarCalculator.phaseName(0.96))+    }++    @Test+    fun `batch transform agrees with the one-by-one transform`() {+        val radecs = listOf(+            RaDec(0.0, 0.0),+            RaDec(1.0, 0.5),+            RaDec(3.0, -0.4),+            RaDec(5.5, 1.2),+        )+        val lst = 1.3+        val lat = 0.65+        assertEquals(emptyList(), CoordinateTransforms.batchRaDecToAltAz(emptyList(), lst, lat))+        val batch = CoordinateTransforms.batchRaDecToAltAz(radecs, lst, lat)+        assertEquals(radecs.size, batch.size)+        radecs.forEachIndexed { index, raDec ->+            val single = CoordinateTransforms.raDecToAltAz(raDec, lst, lat)+            assertEquals(single.azRad, batch[index].azRad, 1e-9, "az[$index]")+            assertEquals(single.altRad, batch[index].altRad, 1e-9, "alt[$index]")+        }+    }++    @Test+    fun `refraction is zero below the horizon band and shrinks with altitude`() {+        assertEquals(0.0, CoordinateTransforms.atmosphericRefractionDeg(-1.5))+        assertEquals(0.0, CoordinateTransforms.atmosphericRefractionDeg(-2.0))+        val horizon = CoordinateTransforms.atmosphericRefractionDeg(0.0)+        assertTrue(horizon > 0.4 && horizon < 0.6, "horizon refraction $horizon")+        val ten = CoordinateTransforms.atmosphericRefractionDeg(10.0)+        val fortyFive = CoordinateTransforms.atmosphericRefractionDeg(45.0)+        assertTrue(ten < horizon, "10deg $ten vs horizon $horizon")+        assertTrue(fortyFive < ten, "45deg $fortyFive vs 10deg $ten")+        assertTrue(fortyFive > 0.0)+    }++    @Test+    fun `rise-set for a circumpolar object has a transit but no rise or set`() {+        // At lat +80, an object at dec +85 never sets.+        val lat = 80.0 * PI / 180.0+        val result = RiseSetCalculator.calc(2460000.5, lat, 0.0, { RaDec(1.0, 85.0 * PI / 180.0) })+        assertTrue(result.isCircumpolar)+        assertEquals(false, result.isNeverUp)+        assertNotNull(result.transitJd)+        assertNull(result.riseJd)+        assertNull(result.setJd)+    }++    @Test+    fun `rise-set for a never-up object reports no events`() {+        val lat = 80.0 * PI / 180.0+        val result = RiseSetCalculator.calc(2460000.5, lat, 0.0, { RaDec(1.0, -85.0 * PI / 180.0) })+        assertTrue(result.isNeverUp)+        assertEquals(false, result.isCircumpolar)+        assertNull(result.riseJd)+        assertNull(result.transitJd)+        assertNull(result.setJd)+    }++    @Test+    fun `rise-set for an equatorial object brackets the transit`() {+        val lat = 37.0 * PI / 180.0+        val jd0 = 2460000.5+        val result = RiseSetCalculator.calc(jd0, lat, 0.0, { RaDec(1.0, 0.0) })+        assertEquals(false, result.isCircumpolar)+        assertEquals(false, result.isNeverUp)+        assertNotNull(result.riseJd)+        assertNotNull(result.transitJd)+        assertNotNull(result.setJd)+        assertTrue(result.riseJd!! < result.transitJd!!)+        assertTrue(result.transitJd!! < result.setJd!!)+        // Everything happens within the requested day (plus the crossing search margin).+        assertTrue(result.riseJd!! > jd0 - 0.25 && result.setJd!! < jd0 + 1.25)+    }++    @Test+    fun `rise-set for a fast-moving object still finds its crossings`() {+        // A moon-like provider: RA sweeps half a radian across the day, so+        // the fixed rise/set guesses bracket the crossings only loosely and+        // the sub-scan has to find them.+        val lat = 37.0 * PI / 180.0+        val jd0 = 2460000.5+        val moving = RiseSetCalculator.calc(jd0, lat, 0.0, { jd ->+            RaDec(1.0 + (jd - jd0) * 0.5, 0.1)+        })+        assertEquals(false, moving.isNeverUp)+        assertEquals(false, moving.isCircumpolar)+        assertNotNull(moving.riseJd)+        assertNotNull(moving.setJd)+        assertTrue(moving.riseJd!! < moving.setJd!!)+    }++    @Test+    fun `rise-set honours the sun horizon depression`() {+        val lat = 37.0 * PI / 180.0+        val jd0 = 2460000.5+        val star = RiseSetCalculator.calc(jd0, lat, 0.0, { RaDec(1.0, 0.0) }, RiseSetCalculator.H0_STAR_DEG)+        val sun = RiseSetCalculator.calc(jd0, lat, 0.0, { RaDec(1.0, 0.0) }, RiseSetCalculator.H0_SUN_DEG)+        assertNotNull(sun.riseJd)+        assertNotNull(star.riseJd)+        // A deeper horizon depression means an earlier rise and a later set.+        assertTrue(sun.riseJd!! < star.riseJd!!)+        assertTrue(sun.setJd!! > star.setJd!!)+        assertEquals(-0.833, RiseSetCalculator.H0_SUN_DEG)+        assertEquals(-0.5667, RiseSetCalculator.H0_STAR_DEG)+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ProjectionEdgeCasesTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ProjectionEdgeCasesTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ProjectionEdgeCasesTest.ktnew file mode 100644index 0000000000..73a99094e5--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ProjectionEdgeCasesTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.astronomy.domain.projection++import androidx.compose.ui.geometry.Offset+import com.vayunmathur.astronomy.domain.AstronomyNative+import com.vayunmathur.astronomy.domain.engine.AltAz+import com.vayunmathur.astronomy.domain.engine.toRad+import kotlin.math.PI+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Edge cases for the projection layer: mesh culling, centre handling, rotation, batch paths. */+class ProjectionEdgeCasesTest {++    @Test+    fun `mesh projection culls points beyond 175 degrees`() {+        val vs = ViewState(0.0, 0.0, 70f, 1080f, 1920f)+        val proj = StereographicProjection(vs)+        // Antipode of the centre is far past the mesh cutoff.+        assertNull(proj.projectMesh(AltAz(PI, 0.0)))+        // The centre itself projects to the middle of the screen.+        val centre = proj.projectMesh(AltAz(0.0, 0.0))+        assertNotNull(centre)+        assertEquals(540f, centre.x, 1f)+        assertEquals(960f, centre.y, 1f)+        // A nearby point projects near the centre.+        val near = proj.projectMesh(AltAz(5.0.toRad(), 5.0.toRad()))+        assertNotNull(near)+    }++    @Test+    fun `unproject of the screen centre is the view centre`() {+        val vs = ViewState(30.0.toRad(), 45.0.toRad(), 70f, 1080f, 1920f, rotationRad = 0.0)+        val proj = StereographicProjection(vs)+        val centre = proj.unproject(Offset(540f, 960f))+        assertNotNull(centre)+        assertTrue(abs(centre.azRad - 30.0.toRad()) < 1e-9)+        assertTrue(abs(centre.altRad - 45.0.toRad()) < 1e-9)+    }++    @Test+    fun `project then unproject round-trips off-centre with rotation`() {+        val vs = ViewState(100.0.toRad(), 20.0.toRad(), 90f, 800f, 600f, rotationRad = 0.4)+        val proj = StereographicProjection(vs)+        val orig = AltAz(110.0.toRad(), 30.0.toRad())+        val projected = proj.project(orig)+        assertNotNull(projected)+        val back = proj.unproject(projected)+        assertNotNull(back)+        assertTrue(abs(back.azRad - orig.azRad) < 0.002, "az ${back.azRad} vs ${orig.azRad}")+        assertTrue(abs(back.altRad - orig.altRad) < 0.002, "alt ${back.altRad} vs ${orig.altRad}")+    }++    @Test+    fun `projectAll of an empty list is empty`() {+        val vs = ViewState(0.0, 0.0, 70f, 1080f, 1920f)+        assertEquals(emptyList(), projectAll(vs, emptyList()))+    }++    @Test+    fun `projectAll matches one-by-one projection`() {+        val vs = ViewState(0.0, 45.0.toRad(), 70f, 1080f, 1920f)+        val points = listOf(+            AltAz(0.0, 45.0.toRad()),+            AltAz(10.0.toRad(), 50.0.toRad()),+            AltAz((-20.0).toRad(), 30.0.toRad()),+        )+        val batch = projectAll(vs, points)+        assertEquals(points.size, batch.size)+        val single = StereographicProjection(vs)+        points.forEachIndexed { index, point ->+            val expected = single.project(point)+            val actual = batch[index]+            if (expected == null) {+                // Native batch marks culled points NaN; the Kotlin path returns null.+                assertTrue(actual == null || actual.x.isNaN(), "index $index")+            } else {+                assertNotNull(actual)+                assertTrue(abs(actual.x - expected.x) < 2f, "index $index x ${actual.x} vs ${expected.x}")+                assertTrue(abs(actual.y - expected.y) < 2f, "index $index y ${actual.y} vs ${expected.y}")+            }+        }+    }++    @Test+    fun `native bridge availability is a stable answer`() {+        // On the unit-test host the Rust library is on java.library.path; in+        // Layoutlib it is not. Either way the flag must be readable and the+        // batch entry points must agree with it.+        val available = AstronomyNative.available+        if (available) {+            val out = AstronomyNative.batchRaDecToAltAz(+                doubleArrayOf(1.0, 0.5, 2.0, -0.2),+                lstRad = 1.0,+                latRad = 0.6,+            )+            assertEquals(4, out.size)+            assertTrue(out.all { it.isFinite() })+        }+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelLocationTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelLocationTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelLocationTest.ktnew file mode 100644index 0000000000..3b14023e7a--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelLocationTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.astronomy.platform++import android.Manifest+import android.app.Application+import android.location.Location+import android.location.LocationManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Location-refresh tests for [AstronomyViewModel]: with a granted+ * permission and a last-known fix in Robolectric's location shadow, the+ * observer moves to the fix; without permission it stays put.+ */+@OptIn(ExperimentalCoroutinesApi::class, kotlin.time.ExperimentalTime::class)+@RunWith(AndroidJUnit4::class)+class AstronomyViewModelLocationTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+    }++    @After+    fun tearDown() {+        Dispatchers.resetMain()+    }++    private fun await(desc: String, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 20_000+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return+            Thread.sleep(50)+        }+        assertTrue(cond(), "timed out: $desc")+    }++    @Test+    fun `refresh location adopts the last-known fix`() {+        val locationManager = app.getSystemService(LocationManager::class.java)+        val shadow = shadowOf(locationManager)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, false)+        shadow.setLastKnownLocation(+            LocationManager.GPS_PROVIDER,+            Location(LocationManager.GPS_PROVIDER).apply {+                latitude = 48.85+                longitude = 2.35+                altitude = 35.0+                time = 1_700_000_000_000L+            },+        )+        shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)++        val vm = AstronomyViewModel(app)+        vm.refreshLocation()+        await("observer at fix") {+            val observer = vm.observer.value+            observer != null && kotlin.math.abs(observer.latDeg - 48.85) < 1e-6+        }+        val observer = vm.observer.value+        assertNotNull(observer)+        assertEquals(48.85, observer.latDeg, 1e-6)+        assertEquals(2.35, observer.lonDeg, 1e-6)+    }++    @Test+    fun `refresh location without permission keeps the manual observer`() {+        val vm = AstronomyViewModel(app)+        vm.setManualLocation(37.0, -122.0)+        vm.refreshLocation()+        // No permission granted: the refresh must not move the observer.+        Thread.sleep(300)+        assertEquals(37.0, vm.observer.value?.latDeg)+        assertEquals(-122.0, vm.observer.value?.lonDeg)+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/platform/ViewCenterResolutionTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/platform/ViewCenterResolutionTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/ViewCenterResolutionTest.ktnew file mode 100644index 0000000000..e095236e9e--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/ViewCenterResolutionTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.astronomy.platform++import com.vayunmathur.astronomy.domain.engine.toRad+import com.vayunmathur.library.sensor.DeviceOrientation+import kotlin.math.PI+import kotlin.test.Test+import kotlin.test.assertEquals++/** Resolution tests for every CenterOption shape, with and without a device orientation. */+class ViewCenterResolutionTest {++    private fun orientation() = DeviceOrientation(+        azimuthTrueDeg = 90.0,+        azimuthMagDeg = 88.0,+        pitchDeg = 10.0,+        rollDeg = 0.0,+        accuracy = 3,+        pointingAzTrueDeg = 90.0,+        pointingAltDeg = 30.0,+        viewRotationDeg = 15.0,+    )++    @Test+    fun `device pointing follows the orientation when present`() {+        val centre = resolveViewCenter(CenterOption.DevicePointing, orientation())+        assertEquals(PI / 2 to 30.0.toRad(), centre)+        assertEquals(15.0.toRad(), resolveViewRotation(CenterOption.DevicePointing, orientation()))+    }++    @Test+    fun `device pointing without orientation looks north at 45 degrees`() {+        assertEquals(0.0 to 45.0.toRad(), resolveViewCenter(CenterOption.DevicePointing, null))+        assertEquals(0.0, resolveViewRotation(CenterOption.DevicePointing, null))+    }++    @Test+    fun `manual and target centres pass through with no rotation`() {+        assertEquals(2.0 to 1.0, resolveViewCenter(CenterOption.Manual(2.0, 1.0), orientation()))+        assertEquals(+            3.0 to 1.5,+            resolveViewCenter(CenterOption.TargetObject("M31", 3.0, 1.5), orientation()),+        )+        assertEquals(0.0, resolveViewRotation(CenterOption.Manual(2.0, 1.0), orientation()))+        assertEquals(0.0, resolveViewRotation(CenterOption.TargetObject("M31", 3.0, 1.5), null))+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/platform/sensor/LocationProviderTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/platform/sensor/LocationProviderTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/sensor/LocationProviderTest.ktnew file mode 100644index 0000000000..1ca39bd620--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/sensor/LocationProviderTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.astronomy.platform.sensor++import android.Manifest+import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.yield+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * Tests for [LocationProvider] against Robolectric's location shadow:+ * permission gating, last-known selection by recency, and the live+ * listener path when no last-known fix exists.+ */+@RunWith(AndroidJUnit4::class)+class LocationProviderTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val locationManager: LocationManager+        get() = context.getSystemService(LocationManager::class.java)++    private fun grantLocation() {+        shadowOf(+            ApplicationProvider.getApplicationContext<android.app.Application>(),+        ).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+        )+    }++    private fun location(provider: String, lat: Double, time: Long) = Location(provider).apply {+        latitude = lat+        longitude = -0.12+        this.time = time+    }++    @Test+    fun `no permission means no location`() {+        runBlocking {+        assertFalse(LocationProvider.hasPermission(context))+        assertNull(LocationProvider.currentLocation(context))+        }+    }++    @Test+    fun `permission without enabled providers yields null`() {+        runBlocking {+        grantLocation()+        assertTrue(LocationProvider.hasPermission(context))+        val shadow = shadowOf(locationManager)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, false)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, false)+        assertNull(LocationProvider.currentLocation(context))+        }+    }++    @Test+    fun `newest last-known fix across providers wins`() {+        runBlocking {+        grantLocation()+        val shadow = shadowOf(locationManager)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        val gps = location(LocationManager.GPS_PROVIDER, 51.5, 1_000L)+        val network = location(LocationManager.NETWORK_PROVIDER, 40.0, 2_000L)+        shadow.setLastKnownLocation(LocationManager.GPS_PROVIDER, gps)+        shadow.setLastKnownLocation(LocationManager.NETWORK_PROVIDER, network)++        val found = LocationProvider.currentLocation(context)+        assertSame(network, found)+        assertEquals(40.0, found?.latitude)+        }+    }++    @Test+    fun `gps-only last-known fix is returned`() {+        runBlocking {+        grantLocation()+        val shadow = shadowOf(locationManager)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, false)+        val gps = location(LocationManager.GPS_PROVIDER, 35.0, 500L)+        shadow.setLastKnownLocation(LocationManager.GPS_PROVIDER, gps)+        assertSame(gps, LocationProvider.currentLocation(context))+        }+    }++    @Test+    fun `live listener delivers the first simulated fix`() {+        runBlocking {+        grantLocation()+        val shadow = shadowOf(locationManager)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, false)+        // No last-known location: the provider must wait for a live fix.+        val deferred = async { LocationProvider.currentLocation(context) }+        // Let the listeners register, then deliver a fix.+        var delivered: Location? = null+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline) {+            if (shadow.requestLocationUpdateListeners.isNotEmpty()) {+                delivered = location(LocationManager.GPS_PROVIDER, 48.85, 3_000L)+                // Deliver through the registered listeners, as the platform would.+                shadow.getLocationUpdateListeners(LocationManager.GPS_PROVIDER)+                    .forEach { it.onLocationChanged(delivered) }+                shadow.simulateLocation(LocationManager.GPS_PROVIDER, delivered)+                break+            }+            yield()+            Thread.sleep(10)+        }+        assertNotNull(delivered)+        val found = deferred.await()+        assertSame(delivered, found)+        assertEquals(48.85, found?.latitude)+        }+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/ui/ObjectDetailPagesTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/ObjectDetailPagesTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/ObjectDetailPagesTest.ktnew file mode 100644index 0000000000..cfbc9bbf52--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/ObjectDetailPagesTest.kt@@ -0,0 +1,172 @@+package com.vayunmathur.astronomy.ui++import android.app.Application+import androidx.compose.runtime.Composable+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.performScrollTo+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.astronomy.Route+import com.vayunmathur.astronomy.platform.AstronomyViewModel+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Detail-page tests for every object family the resolver knows: moon,+ * planets, catalog stars (visible and merely catalogued), deep-sky+ * objects, and the not-found shapes for malformed or unknown ids.+ */+@OptIn(ExperimentalCoroutinesApi::class, kotlin.time.ExperimentalTime::class)+@RunWith(RobolectricTestRunner::class)+class ObjectDetailPagesTest {++    @get:Rule+    val rule = createComposeRule()++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+    }++    @AfterTest+    fun tearDown() {+        Dispatchers.resetMain()+    }++    @Composable+    private fun stack(): NavBackStack<Route> = rememberNavBackStack(Route.SkyMap)++    private fun await(desc: String, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 20_000+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return+            Thread.sleep(50)+        }+        assertTrue(cond(), "timed out: $desc")+    }++    private fun viewModel(): AstronomyViewModel {+        val vm = AstronomyViewModel(app)+        await("catalog") { vm.catalogReady.value }+        vm.setManualLocation(37.0, -122.0)+        return vm+    }++    private fun showDetail(vm: AstronomyViewModel, id: String): NavBackStack<Route> {+        lateinit var stack: NavBackStack<Route>+        rule.setContent {+            stack = rememberNavBackStack(+                Route.SkyMap,+                Route.ObjectDetail(id),+            )+            ObjectDetailPage(backStack = stack, viewModel = vm, objectId = id)+        }+        return stack+    }++    @Test+    fun `moon detail shows phase and illumination`() {+        val vm = viewModel()+        vm.selectObject("MOON")+        showDetail(vm, "MOON")+        rule.onNodeWithText("Moon", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Illum", substring = true).assertExists()+    }++    @Test+    fun `planet detail shows name distance and magnitude`() {+        val vm = viewModel()+        vm.selectObject("PLANET_MARS")+        showDetail(vm, "PLANET_MARS")+        rule.onNodeWithText("Mars", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Planet", substring = true).assertExists()+        rule.onNodeWithText("Dist", substring = true).assertExists()+    }++    @Test+    fun `unknown planet and sun-less sky are not found`() {+        val vm = viewModel()+        showDetail(vm, "PLANET_PLUTO")+        rule.onNodeWithText("PLANET_PLUTO", substring = true).assertExists()+    }++    @Test+    fun `catalog star detail resolves by id`() {+        val vm = viewModel()+        // A named star from the bundled catalog, resolved through the+        // catalog-projection path (it need not be currently visible).+        val named = vm.catalog.stars.firstOrNull { it.properName != null }+        assertNotNull(named)+        val id = "STAR_${named.id}"+        vm.selectObject(id)+        await("visible sky") { vm.visibleSky.value.observer != null }+        showDetail(vm, id)+        rule.onNodeWithText(named.properName!!, substring = true).assertIsDisplayed()+        rule.onNodeWithText("BV", substring = true).assertExists()+    }++    @Test+    fun `malformed and unknown star ids are not found`() {+        val vm = viewModel()+        showDetail(vm, "STAR_abc")+        rule.onNodeWithText("STAR_abc", substring = true).assertExists()+    }++    @Test+    fun `deep sky detail shows type and size`() {+        val vm = viewModel()+        vm.selectObject("M31")+        showDetail(vm, "M31")+        rule.onNodeWithText("M31", substring = true).assertIsDisplayed()+        rule.onNodeWithText("arcmin", substring = true).assertExists()+    }++    @Test+    fun `unknown object is not found`() {+        val vm = viewModel()+        val stack = showDetail(vm, "NOPE_NOT_REAL")+        rule.onNodeWithText("NOPE_NOT_REAL", substring = true).assertExists()+        assertEquals(Route.ObjectDetail("NOPE_NOT_REAL"), stack.last())+    }++    @Test+    fun `close button pops the stack`() {+        val vm = viewModel()+        vm.selectObject("M31")+        val stack = showDetail(vm, "M31")+        assertEquals(Route.ObjectDetail("M31"), stack.last())+        rule.onNodeWithText("Close").performScrollTo().performClick()+        assertEquals(Route.SkyMap, stack.last())+    }++    @Test+    fun `rise-set card resolves for a selected object`() {+        val vm = viewModel()+        vm.selectObject("SUN")+        await("riseSet") { vm.riseSet.value != null }+        showDetail(vm, "SUN")+        rule.onNodeWithText("Sun", substring = true).assertIsDisplayed()+        // Both the card title and the rise row contain "Rise".+        assertTrue(+            rule.onAllNodesWithText("Rise", substring = true).fetchSemanticsNodes().size >= 2,+        )+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/ui/SettingsScreenInteractionsTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SettingsScreenInteractionsTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SettingsScreenInteractionsTest.ktnew file mode 100644index 0000000000..a92312b609--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SettingsScreenInteractionsTest.kt@@ -0,0 +1,171 @@+package com.vayunmathur.astronomy.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.astronomy.R+import com.vayunmathur.astronomy.Route+import com.vayunmathur.astronomy.platform.ConstellationMode+import com.vayunmathur.astronomy.platform.SettingsActions+import com.vayunmathur.astronomy.platform.SettingsUiState+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.rememberNavBackStack+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Interaction tests for [SettingsScreen]: every switch, the constellation+ * select, and the manual-location form route through the actions.+ */+@RunWith(AndroidJUnit4::class)+class SettingsScreenInteractionsTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    private class Recorder : SettingsActions {+        var mode: ConstellationMode? = null+        val switches = mutableListOf<Pair<String, Boolean>>()+        var manualLocation: Pair<Double, Double>? = null+        var refreshes = 0++        override fun setShowConstellations(mode: ConstellationMode) {+            this.mode = mode+        }++        override fun setShowGrid(v: Boolean) {+            switches += "grid" to v+        }++        override fun setShowDeepSky(v: Boolean) {+            switches += "deep" to v+        }++        override fun setShowPlanets(v: Boolean) {+            switches += "planets" to v+        }++        override fun setShowBelowHorizon(v: Boolean) {+            switches += "below" to v+        }++        override fun setNightMode(v: Boolean) {+            switches += "night" to v+        }++        override fun setManualLocation(latDeg: Double, lonDeg: Double) {+            manualLocation = latDeg to lonDeg+        }++        override fun refreshLocation() {+            refreshes+++        }+    }++    private fun state() = SettingsUiState(+        constellationMode = ConstellationMode.LINES,+        showGrid = true,+        showDeepSky = true,+        showPlanets = true,+        showBelowHorizon = false,+        nightMode = false,+        magLimit = 5.0f,+        fovDeg = 70f,+        starCount = 100,+        constellationCount = 9,+        deepSkyCount = 6,+    )++    private fun show(actions: SettingsActions): NavBackStack<Route> {+        lateinit var stack: NavBackStack<Route>+        composeRule.setContent {+            stack = rememberNavBackStack(Route.SkyMap, Route.Settings)+            SettingsScreen(backStack = stack, state = state(), actions = actions)+        }+        @Suppress("UNCHECKED_CAST")+        return stack as NavBackStack<Route>+    }++    private fun string(res: Int): String = context.getString(res)++    @Test+    fun `toggling switches routes each one`() {+        val actions = Recorder()+        show(actions)+        composeRule.onNodeWithText(string(R.string.coordinate_grid_whole_sphere)).performClick()+        composeRule.onNodeWithText(string(R.string.show_deep_sky)).performClick()+        composeRule.onNodeWithText(string(R.string.planets_sun_moon)).performClick()+        composeRule.onNodeWithText(string(R.string.night_mode)).performClick()+        assertEquals(+            listOf("grid" to false, "deep" to false, "planets" to false, "night" to true),+            actions.switches,+        )+    }++    @Test+    fun `constellation mode select routes the choice`() {+        val actions = Recorder()+        show(actions)+        composeRule.onNodeWithText(string(R.string.constellations)).performClick()+        composeRule.onNodeWithText(string(R.string.lines_art)).performClick()+        assertEquals(ConstellationMode.LINES_AND_ART, actions.mode)+        composeRule.onNodeWithText(string(R.string.constellations)).performClick()+        composeRule.onNodeWithText(string(R.string.off)).performClick()+        assertEquals(ConstellationMode.OFF, actions.mode)+    }++    @Test+    fun `manual location form saves parsed coordinates and refresh asks for gps`() {+        val actions = Recorder()+        show(actions)+        // Scroll the form into view: the location section is below the fold.+        composeRule.onNodeWithText(string(R.string.latitude_deg)).performScrollTo()+        val fields = composeRule.onAllNodes(androidx.compose.ui.test.hasSetTextAction())+        assertEquals(2, fields.fetchSemanticsNodes().size)+        fields[0].performTextReplacement("48.85")+        fields[1].performTextReplacement("2.35")+        // The fields must actually hold the typed text before saving.+        assertTrue(+            fields[0].fetchSemanticsNode().config[+                androidx.compose.ui.semantics.SemanticsProperties.EditableText,+            ].text.contains("48.85"),+        )+        composeRule.onNodeWithText(string(R.string.save_location)).performScrollTo().performClick()+        assertEquals(48.85 to 2.35, actions.manualLocation)++        composeRule.onNodeWithText(string(R.string.use_current_location)).performScrollTo().performClick()+        assertEquals(1, actions.refreshes)+    }++    @Test+    fun `invalid manual location is not saved`() {+        val actions = Recorder()+        show(actions)+        composeRule.onNodeWithText(string(R.string.latitude_deg)).performScrollTo()+        composeRule.onAllNodes(androidx.compose.ui.test.hasSetTextAction())[0]+            .performTextReplacement("north")+        composeRule.onNodeWithText(string(R.string.save_location)).performScrollTo().performClick()+        assertEquals(null, actions.manualLocation)+        assertTrue(actions.switches.isEmpty())+    }++    @Test+    fun `settings renders its sections and catalog counts`() {+        show(Recorder())+        composeRule.onNodeWithText(string(R.string.settings)).assertIsDisplayed()+        composeRule.onNodeWithText(string(R.string.display)).assertIsDisplayed()+    }+}+
astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyArtHelpersTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyArtHelpersTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyArtHelpersTest.ktnew file mode 100644index 0000000000..601c06869b--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyArtHelpersTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.astronomy.ui++import androidx.compose.ui.graphics.Color+import com.vayunmathur.astronomy.domain.engine.AltAz+import kotlin.math.PI+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Pure-helper tests for SkyArt: colour bands, radii, vectors and matrix inversion. */+class SkyArtHelpersTest {++    @Test+    fun `star radius shrinks with magnitude and clamps at both ends`() {+        assertEquals(5.5f, starRadius(-3.0), 0.001f)+        assertEquals(4.2f, starRadius(0.0), 0.001f)+        assertTrue(starRadius(3.0) < starRadius(1.0))+        assertEquals(0.9f, starRadius(10.0), 0.001f)+        assertEquals(0.9f, starRadius(100.0), 0.001f)+    }++    @Test+    fun `bv colour walks the temperature bands`() {+        assertEquals(Color(0xFF9BB0FF), bvToColor(-0.3))+        assertEquals(Color(0xFFC6D2FF), bvToColor(-0.2))+        assertEquals(Color(0xFFC6D2FF), bvToColor(-0.1))+        assertEquals(Color.White, bvToColor(0.0))+        assertEquals(Color.White, bvToColor(0.29))+        assertEquals(Color(0xFFFFFFE0), bvToColor(0.3))+        assertEquals(Color(0xFFFFE4B5), bvToColor(0.6))+        assertEquals(Color(0xFFFFA500), bvToColor(1.0))+        assertEquals(Color(0xFFFF6347), bvToColor(1.4))+        assertEquals(Color(0xFFFF6347), bvToColor(2.0))+    }++    @Test+    fun `planet colours are known for solar system bodies and white otherwise`() {+        assertEquals(Color(0xFFFF4500), planetColor("MARS"))+        assertEquals(Color(0xFFFFE0B0), planetColor("VENUS"))+        assertNotNull(planetColor("JUPITER"))+        assertNotNull(planetColor("SATURN"))+        assertEquals(Color.White, planetColor("PLUTO"))+        assertEquals(Color.White, planetColor(""))+    }++    @Test+    fun `alt-az to vector is a unit vector pointing the right way`() {+        val zenith = altAzToVec(AltAz(0.0, PI / 2))+        assertTrue(abs(zenith[2] - 1.0) < 1e-9)+        val north = altAzToVec(AltAz(0.0, 0.0))+        assertTrue(abs(north[0]) < 1e-9 && abs(north[1] - 1.0) < 1e-9 && abs(north[2]) < 1e-9)+        val east = altAzToVec(AltAz(PI / 2, 0.0))+        assertTrue(abs(east[0] - 1.0) < 1e-9 && abs(east[1]) < 1e-9)+        val arbitrary = altAzToVec(AltAz(1.1, 0.4))+        val len = kotlin.math.sqrt(arbitrary.sumOf { it * it })+        assertTrue(abs(len - 1.0) < 1e-9)+    }++    @Test+    fun `invert3x3 inverts a well-formed matrix and rejects a singular one`() {+        // Identity inverts to itself.+        val identity = invert3x3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)+        assertNotNull(identity)+        assertTrue(identity.contentEquals(doubleArrayOf(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)))+        // Rows linearly dependent (anchor pixels collinear) -> singular.+        assertNull(invert3x3(0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0))+        assertNull(invert3x3(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))+        // A scaled matrix inverts to the reciprocal scale.+        val scaled = invert3x3(2.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 5.0)+        assertNotNull(scaled)+        assertEquals(0.5, scaled[0], 1e-9)+        assertEquals(0.25, scaled[4], 1e-9)+        assertEquals(0.2, scaled[8], 1e-9)+    }++    @Test+    fun `art mesh constant is positive`() {+        assertTrue(ART_MESH > 0)+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.ktnew file mode 100644index 0000000000..4ccc43926e--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.kt@@ -0,0 +1,255 @@+package com.vayunmathur.astronomy.ui++import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.click+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.astronomy.data.model.DeepSkyObject+import com.vayunmathur.astronomy.data.model.Star+import com.vayunmathur.astronomy.domain.engine.AltAz+import com.vayunmathur.astronomy.domain.engine.RaDec+import com.vayunmathur.astronomy.domain.projection.ViewState+import com.vayunmathur.astronomy.platform.ConstellationLine+import com.vayunmathur.astronomy.platform.TrajectoryPoint+import com.vayunmathur.astronomy.platform.VisibleArt+import com.vayunmathur.astronomy.platform.VisibleArtAnchor+import com.vayunmathur.astronomy.platform.VisibleDeepSky+import com.vayunmathur.astronomy.platform.VisibleMoon+import com.vayunmathur.astronomy.platform.VisiblePlanet+import com.vayunmathur.astronomy.platform.VisibleSky+import com.vayunmathur.astronomy.platform.VisibleStar+import com.vayunmathur.astronomy.platform.VisibleSun+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Draw-path tests for [SkyCanvas]: a fully populated sky (stars of several+ * colours, planets, sun, moon, deep-sky, constellation lines and figure+ * art, a trajectory and a selection ring) is rasterised with native+ * graphics so every layer's draw code runs, and tap/drag gestures route+ * to the right callbacks.+ */+@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SkyCanvasDrawTest {++    @get:Rule+    val composeRule = createComposeRule()++    // Sized to Robolectric's default 320x470 display so projected points+    // land where touch injection expects them.+    private val viewState = ViewState(+        centerAzRad = 0.0,+        centerAltRad = 0.5,+        fovDeg = 70f,+        screenW = 320f,+        screenH = 470f,+    )++    private fun richSky(selectedArt: Boolean = true): VisibleSky {+        val sirius = Star(id = 1, name = "Sirius", properName = "Sirius", ra = 1.0, dec = 0.5, mag = -1.4, bv = 0.0)+        val red = Star(id = 2, name = "Red", properName = "Red", ra = 1.1, dec = 0.4, mag = 2.5, bv = 1.6)+        val blue = Star(id = 3, name = "Blue", properName = "Blue", ra = 0.9, dec = 0.6, mag = 4.5, bv = -0.3)+        return VisibleSky(+            stars = listOf(+                VisibleStar(sirius, AltAz(0.0, 0.5), RaDec(1.0, 0.5)),+                VisibleStar(red, AltAz(0.1, 0.45), RaDec(1.1, 0.4)),+                VisibleStar(blue, AltAz(-0.1, 0.55), RaDec(0.9, 0.6)),+            ),+            planets = listOf(+                VisiblePlanet("MARS", "Mars", AltAz(0.05, 0.42), RaDec(1.2, 0.3), -0.5, 0.7),+                VisiblePlanet("VENUS", "Venus", AltAz(-0.05, 0.6), RaDec(0.8, 0.5), -4.0, 0.3),+            ),+            sun = VisibleSun(AltAz(0.02, 0.3), RaDec(0.8, 0.1), 1.0),+            moon = VisibleMoon(AltAz(-0.02, 0.65), RaDec(1.5, 0.4), 0.5, 0.75, 7.0),+            deepSky = listOf(+                VisibleDeepSky(DeepSkyObject("M31", "Andromeda Galaxy", 0.71, 0.71, 3.4, "galaxy"), AltAz(0.03, 0.48), RaDec(0.71, 0.71)),+                VisibleDeepSky(DeepSkyObject("M42", "Orion Nebula", 1.46, -0.09, 4.0, "nebula"), AltAz(-0.03, 0.52), RaDec(1.46, -0.09)),+                VisibleDeepSky(DeepSkyObject("M45", "Pleiades", 0.99, 0.42, 1.6, "cluster"), AltAz(0.06, 0.44), RaDec(0.99, 0.42)),+            ),+            constellations = listOf(+                ConstellationLine("Ori", "Orion", listOf(listOf(1, 2), listOf(2, 3))),+            ),+            art = if (selectedArt) {+                listOf(+                    VisibleArt(+                        abbr = "Ori",+                        image = "orion.png",+                        anchors = listOf(+                            VisibleArtAnchor(0f, 0f, AltAz(0.0, 0.5)),+                            VisibleArtAnchor(500f, 0f, AltAz(0.1, 0.45)),+                            VisibleArtAnchor(0f, 500f, AltAz(-0.1, 0.55)),+                        ),+                    )+                )+            } else {+                emptyList()+            },+        )+    }++    private class Recorder {+        val pans = mutableListOf<Pair<Double, Double>>()+        val zooms = mutableListOf<Float>()+        val taps = mutableListOf<androidx.compose.ui.geometry.Offset>()+        val objectTaps = mutableListOf<String>()+        val objectOpens = mutableListOf<String>()+    }++    private fun show(+        sky: VisibleSky,+        recorder: Recorder,+        selectedId: String? = null,+        transparent: Boolean = false,+        art: Boolean = true,+    ) {+        composeRule.setContent {+            SkyCanvas(+                visibleSky = sky,+                viewState = viewState,+                showConstellationLines = true,+                showConstellationArt = art,+                showGrid = true,+                showDeepSky = true,+                showPlanets = true,+                transparentBackground = transparent,+                trajectory = listOf(+                    TrajectoryPoint(2460000.5, AltAz(0.0, 0.4), RaDec(1.0, 0.5)),+                    TrajectoryPoint(2460000.6, AltAz(0.05, 0.5), RaDec(1.05, 0.5)),+                    TrajectoryPoint(2460000.7, AltAz(0.1, 0.6), RaDec(1.1, 0.5)),+                ),+                selectedId = selectedId,+                onPan = { az, alt -> recorder.pans += az to alt },+                onZoom = { recorder.zooms += it },+                onTap = { recorder.taps += it },+                onObjectTap = { recorder.objectTaps += it },+                onObjectOpen = { recorder.objectOpens += it },+            )+        }+        composeRule.waitForIdle()+    }++    @Test+    fun `fully populated sky rasterises every layer`() {+        val recorder = Recorder()+        show(richSky(), recorder, selectedId = "STAR_1")+        val image = composeRule.onRoot().captureToImage()+        assertTrue(image.width > 0 && image.height > 0)+    }++    @Test+    fun `selection ring for the sun draws`() {+        val recorder = Recorder()+        show(richSky(), recorder, selectedId = "SUN")+        composeRule.onRoot().captureToImage()+        assertTrue(recorder.objectTaps.isEmpty())+    }++    @Test+    fun `selection ring for a planet draws`() {+        val recorder = Recorder()+        show(richSky(), recorder, selectedId = "PLANET_MARS")+        composeRule.onRoot().captureToImage()+        assertTrue(recorder.objectTaps.isEmpty())+    }++    @Test+    fun `selection ring for a deep sky object draws`() {+        val recorder = Recorder()+        show(richSky(), recorder, selectedId = "M31")+        composeRule.onRoot().captureToImage()+        assertTrue(recorder.objectTaps.isEmpty())+    }++    @Test+    fun `tap on the centred star selects it`() {+        val recorder = Recorder()+        // A lone centred star: nothing else is within hit distance.+        val lone = VisibleSky(+            stars = listOf(+                VisibleStar(+                    Star(id = 1, name = "Sirius", properName = "Sirius", ra = 1.0, dec = 0.5, mag = -1.4, bv = 0.0),+                    AltAz(0.0, 0.5),+                    RaDec(1.0, 0.5),+                )+            ),+        )+        show(lone, recorder, selectedId = null)+        composeRule.onRoot().performTouchInput { click(center) }+        assertEquals(listOf("STAR_1"), recorder.objectTaps)+        assertTrue(recorder.objectOpens.isEmpty())+    }++    @Test+    fun `tap with the star already selected opens it`() {+        val recorder = Recorder()+        val lone = VisibleSky(+            stars = listOf(+                VisibleStar(+                    Star(id = 1, name = "Sirius", properName = "Sirius", ra = 1.0, dec = 0.5, mag = -1.4, bv = 0.0),+                    AltAz(0.0, 0.5),+                    RaDec(1.0, 0.5),+                )+            ),+        )+        show(lone, recorder, selectedId = "STAR_1")+        composeRule.onRoot().performTouchInput { click(center) }+        assertEquals(listOf("STAR_1"), recorder.objectOpens)+        assertTrue(recorder.objectTaps.isEmpty())+    }++    @Test+    fun `tap away from objects is a plain canvas tap`() {+        val recorder = Recorder()+        show(richSky(), recorder, selectedId = null)+        composeRule.onRoot().performTouchInput {+            click(androidx.compose.ui.geometry.Offset(20f, 20f))+        }+        assertEquals(1, recorder.taps.size)+        assertTrue(recorder.objectTaps.isEmpty())+    }++    // Drag/zoom gesture handlers (detectDragGestures/detectTransformGestures)+    // do not trigger from synthetic single-pointer injection under+    // Robolectric; the tap handler above is the gesture path that does.++    @Test+    fun `empty transparent sky draws only the grid and horizon`() {+        val recorder = Recorder()+        show(VisibleSky(), recorder, transparent = true, art = false)+        val image = composeRule.onRoot().captureToImage()+        assertTrue(image.width > 0)+    }++    @Test+    fun `art with too few anchors or off-screen is skipped`() {+        val recorder = Recorder()+        val sky = richSky(selectedArt = false).copy(+            art = listOf(+                VisibleArt(+                    abbr = "Ori",+                    image = "orion.png",+                    anchors = listOf(VisibleArtAnchor(0f, 0f, AltAz(0.0, 0.5))),+                ),+                VisibleArt(+                    abbr = "Nope",+                    image = "does-not-exist.png",+                    anchors = listOf(+                        VisibleArtAnchor(0f, 0f, AltAz(0.0, 0.5)),+                        VisibleArtAnchor(500f, 0f, AltAz(0.1, 0.45)),+                        VisibleArtAnchor(0f, 500f, AltAz(-0.1, 0.55)),+                    ),+                ),+            ),+        )+        show(sky, recorder)+        composeRule.onRoot().captureToImage()+    }+}
astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.ktnew file mode 100644index 0000000000..1ca71ffaab--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.kt@@ -0,0 +1,228 @@+package com.vayunmathur.astronomy.ui++import android.app.Application+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.astronomy.Route+import com.vayunmathur.astronomy.data.model.DeepSkyObject+import com.vayunmathur.astronomy.data.model.Star+import com.vayunmathur.astronomy.domain.engine.AltAz+import com.vayunmathur.astronomy.domain.engine.RaDec+import com.vayunmathur.astronomy.platform.AstronomyViewModel+import com.vayunmathur.astronomy.platform.ConstellationMode+import com.vayunmathur.astronomy.platform.SkyMapActions+import com.vayunmathur.astronomy.platform.SkyMapUiState+import com.vayunmathur.astronomy.platform.VisibleDeepSky+import com.vayunmathur.astronomy.platform.VisibleMoon+import com.vayunmathur.astronomy.platform.VisiblePlanet+import com.vayunmathur.astronomy.platform.VisibleSky+import com.vayunmathur.astronomy.platform.VisibleStar+import com.vayunmathur.astronomy.platform.VisibleSun+import com.vayunmathur.library.util.LocalNavResultRegistry+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavResultRegistry+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.datetime.TimeZone+import org.junit.After+import org.junit.Before+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Instant++/**+ * Tests for [SkyMapScreen] and [SkyMapPage]: top-bar navigation routes,+ * the camera toggle composing the AR background's permission path, night+ * mode, the time scrubber seeding the actions, and a native-graphics+ * capture that forces the canvas draw layers (grid, art, labels) to run.+ */+@OptIn(ExperimentalCoroutinesApi::class, kotlin.time.ExperimentalTime::class)+@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SkyMapScreenTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+    }++    @After+    fun tearDown() {+        Dispatchers.resetMain()+    }++    private class RecordingActions : SkyMapActions {+        val fovs = mutableListOf<Float>()+        val selected = mutableListOf<String>()+        val times = mutableListOf<Pair<Instant, Boolean>>()++        override fun setFov(v: Float) {+            fovs += v+        }++        override fun selectObject(id: String) {+            selected += id+        }++        override fun setTime(instant: Instant, live: Boolean) {+            times += instant to live+        }+    }++    private fun skyState(+        nightMode: Boolean = false,+        constellationMode: ConstellationMode = ConstellationMode.LINES_AND_ART,+    ): SkyMapUiState {+        val star = Star(id = 1, name = "Testar", properName = "Testar", ra = 1.0, dec = 0.5, mag = 1.5)+        val visible = VisibleSky(+            stars = listOf(VisibleStar(star, AltAz(0.5, 0.5), RaDec(1.0, 0.5))),+            planets = listOf(VisiblePlanet("PLANET_MARS", "Mars", AltAz(0.6, 0.4), RaDec(1.2, 0.3), -0.5, 0.7)),+            sun = VisibleSun(AltAz(0.3, 0.2), RaDec(0.8, 0.1), 1.0),+            moon = VisibleMoon(AltAz(0.9, 0.6), RaDec(1.5, 0.4), 0.5, 0.75, 7.0),+            deepSky = listOf(+                VisibleDeepSky(+                    DeepSkyObject("M31", "Andromeda Galaxy", 0.71, 0.71, 3.4, "Galaxy"),+                    AltAz(0.4, 0.4),+                    RaDec(0.71, 0.71),+                )+            ),+        )+        return SkyMapUiState(+            visibleSky = visible,+            simTime = Instant.fromEpochMilliseconds(1_700_000_000_000),+            timeZone = TimeZone.UTC,+            isLive = true,+            nightMode = nightMode,+            constellationMode = constellationMode,+            selectedObjectId = "STAR_1",+        )+    }++    private fun showScreen(+        state: SkyMapUiState = skyState(),+        actions: SkyMapActions,+        initialCameraOn: Boolean = false,+    ): NavBackStack<Route> {+        lateinit var stack: NavBackStack<Route>+        composeRule.setContent {+            stack = rememberNavBackStack(Route.SkyMap)+            // SkyMapScreen's history scrubber delivers results through the+            // registry MainNavigation normally provides.+            CompositionLocalProvider(LocalNavResultRegistry provides NavResultRegistry()) {+                SkyMapScreen(+                    backStack = stack,+                    state = state,+                    actions = actions,+                    initialCameraOn = initialCameraOn,+                )+            }+        }+        @Suppress("UNCHECKED_CAST")+        return stack+    }++    @Test+    fun `top bar search and settings push their routes`() {+        val stack = showScreen(actions = RecordingActions())+        composeRule.onNodeWithContentDescription("Search").performClick()+        assertEquals(Route.Search, stack.last())+        composeRule.onNodeWithContentDescription("Settings").performClick()+        assertEquals(Route.Settings, stack.last())+    }++    @Test+    fun `camera toggle composes the camera background permission path`() {+        showScreen(actions = RecordingActions())+        // No CAMERA permission under Robolectric: toggling composes+        // CameraBackground, which asks and (unanswered) renders nothing.+        composeRule.onNodeWithContentDescription("Camera").performClick()+        composeRule.waitForIdle()+        // The screen survives the toggle whatever the permission answer was.+        composeRule.onNodeWithContentDescription("Search").assertIsDisplayed()+    }++    @Test+    fun `camera starting on renders behind the sky`() {+        showScreen(actions = RecordingActions(), initialCameraOn = true)+        composeRule.waitForIdle()+        composeRule.onNodeWithContentDescription("Search").assertIsDisplayed()+    }++    @Test+    fun `time scrubber seeds actions with the sim time in live mode`() {+        val actions = RecordingActions()+        showScreen(actions = actions)+        composeRule.waitForIdle()+        assertTrue(actions.times.isNotEmpty(), "scrubber never set a time")+        assertEquals(true, actions.times.first().second)+    }++    @Test+    fun `night mode composes and draws`() {+        showScreen(state = skyState(nightMode = true), actions = RecordingActions())+        // Forcing a capture rasterises the canvas: grid, constellation art,+        // planet/star/deep-sky layers and labels all execute their draw code.+        val image = composeRule.onRoot().captureToImage()+        assertTrue(image.width > 0 && image.height > 0)+    }++    @Test+    fun `constellations off composes and draws`() {+        showScreen(+            state = skyState(constellationMode = ConstellationMode.OFF),+            actions = RecordingActions(),+        )+        val image = composeRule.onRoot().captureToImage()+        assertTrue(image.width > 0 && image.height > 0)+    }++    @Test+    fun `sky map page binds the real view model`() {+        val viewModel = AstronomyViewModel(app)+        lateinit var stack: NavBackStack<Route>+        composeRule.setContent {+            stack = rememberNavBackStack(Route.SkyMap)+            CompositionLocalProvider(LocalNavResultRegistry provides NavResultRegistry()) {+                SkyMapPage(backStack = stack, viewModel = viewModel)+            }+        }+        composeRule.waitForIdle()+        composeRule.onNodeWithContentDescription("Search").assertIsDisplayed()+        composeRule.onNodeWithContentDescription("Settings").performClick()+        assertEquals(Route.Settings, stack.last())+        assertNotNull(viewModel.visibleSky.value)+    }++    @Test+    fun `low accuracy shows the compass calibration banner`() {+        val state = skyState().copy(+            accuracy = android.hardware.SensorManager.SENSOR_STATUS_UNRELIABLE,+        )+        showScreen(state = state, actions = RecordingActions())+        composeRule.waitForIdle()+        // The banner renders for unreliable sensors (text is library-owned);+        // composing without crashing is the assertion available here.+        composeRule.onNodeWithContentDescription("Search").assertIsDisplayed()+    }+}