Modern Apps git

← Modern-Apps.git

education: add tests for ViewModel, Room, content and all pages (pass 3)

Commit
b50d83527f60e7b665f559cb0e77a922830839af
Author
Vayun Mathur <[email protected]>
When
2026-11-07 11:49 UTC (29 days ago)
Parents
415f556
Raise merged INSTRUCTION coverage from 22.8% (5915/25899) to 88.4%
(22884/25899), past the 85% target. No production code changed and no
testability seam was needed: tests seed the shared Room `databases`
cache with an in-memory EducationDatabase (the notes-module pattern),
so EducationRepository and EducationViewModel run against real Room
on the JVM instead of SQLCipher.

Added (5 files, suite now 72 tests):
- util/EducationViewModelTest: DAO CRUD/flows and repository
  singleton; ContentRepository indexing, band/subject queries and
  bundled-assets loading; grading across every question type plus
  star/streak boundaries; learner edits, PIN set/verify, deadline
  set/update/remove and commitResult persistence (progress, streak,
  total stars, FIRST_STAR badge unlock); achievements, Narrator
  no-ops, factory rejection of foreign ViewModel classes. The VM's
  WhileSubscribed flows are kept hot with background collectors, and
  all waits pump the Robolectric main looper (viewModelScope deadlocks
  otherwise).
- ui/EducationPagesTest: ParentGate wrong/correct PIN; ParentPage
  render + name/goal/PIN edits, grade dropdown, band override and
  deadline delete; Explorer home (band filtering, search, continue
  card) and course pages; Unit/Lesson navigation and missing-content
  states; K2 home/lesson/reward; Badges, Results, band dispatchers,
  RootNavigation/MainGraph. Compose hosts swap a single setContent
  lambda because createComposeRule activities reject a second
  setContent.
- ui/EducationQuizInputsTest: every QuestionInput type (choice,
  multi-select, numeric, text, ordering, matching), TracingCanvas
  gesture completion, K2DragMatch render + missed-drop snap-back,
  Scholar quiz full flow (hints, feedback, finish payload), K2 quiz
  wrong/correct/trace-to-finish flow, common chips/headers/helpers,
  rememberNarrator lifecycle, VideoPlayer page title (loopback-only
  URL, so no test touches the real network).
- MainActivityRoutesTest: Route payloads, pushChain same-class
  replacement, MainActivity launch.
- EducationFixtures: one synthetic pack covering all bands, subjects
  and question types, plus the in-memory DB seeding.

Untestable remainder: the matched-drop success path in K2DragMatch
(synthetic Robolectric gestures do not interleave the per-frame
bounds updates its hit test uses on a real device; the missed-drop
snap-back is asserted), VideoPlayer's ExoPlayer ready/error surface
(loopback refusal is environment-dependent), and MainActivity's
ready-gated Content beyond launch.

Verified: gslot ./gradlew :education:createMergedCoverageReport
(72 tests green, merged report 88.36%) and gslot ./check education
(detekt + lint green).

(cherry picked from commit 58ed93af35585594f3707b3e18471aebed76a1bd)

Diff

education/src/test/java/com/vayunmathur/education/EducationFixtures.kt
diff --git a/education/src/test/java/com/vayunmathur/education/EducationFixtures.kt b/education/src/test/java/com/vayunmathur/education/EducationFixtures.ktnew file mode 100644index 0000000000..7af4f4451f--- /dev/null+++ b/education/src/test/java/com/vayunmathur/education/EducationFixtures.kt@@ -0,0 +1,118 @@+package com.vayunmathur.education++import android.content.Context+import androidx.room3.Room+import com.vayunmathur.education.content.Choice+import com.vayunmathur.education.content.ContentPack+import com.vayunmathur.education.content.ContentRepository+import com.vayunmathur.education.content.Course+import com.vayunmathur.education.content.CourseUnit+import com.vayunmathur.education.content.Exercise+import com.vayunmathur.education.content.Lesson+import com.vayunmathur.education.content.MatchingQuestion+import com.vayunmathur.education.content.MultipleChoiceQuestion+import com.vayunmathur.education.content.MultipleSelectQuestion+import com.vayunmathur.education.content.NumericQuestion+import com.vayunmathur.education.content.OrderingQuestion+import com.vayunmathur.education.content.Prompt+import com.vayunmathur.education.content.ShortTextQuestion+import com.vayunmathur.education.content.Skill+import com.vayunmathur.education.content.Subject+import com.vayunmathur.education.content.TracingQuestion+import com.vayunmathur.education.content.VideoRef+import com.vayunmathur.education.data.EducationDatabase+import com.vayunmathur.education.data.EducationRepository+import com.vayunmathur.library.util.databases++/** Shared fixtures: one synthetic pack covering every band, subject and question type. */+object EducationFixtures {+    val mcq = MultipleChoiceQuestion(+        id = "q-mc", skillId = "count",+        prompt = Prompt("How many apples?", audioRef = "q-mc.mp3"),+        choices = listOf(Choice("1"), Choice("3"), Choice("7")),+        correctIndex = 1, hints = listOf("Count them one by one.", "More than two."),+        explanation = "There are three apples.",+    )+    val multiSelect = MultipleSelectQuestion(+        id = "q-ms", skillId = "count",+        prompt = Prompt("Pick the even numbers"),+        choices = listOf(Choice("2"), Choice("3"), Choice("4")),+        correctIndices = listOf(0, 2),+    )+    val numeric = NumericQuestion(+        id = "q-num", skillId = "add",+        prompt = Prompt("2 + 3 = ?"), answer = 5.0, tolerance = 0.1, unit = "apples",+    )+    val shortText = ShortTextQuestion(+        id = "q-text", skillId = "read",+        prompt = Prompt("First letter of the alphabet?"), acceptedAnswers = listOf("a", "A"),+    )+    val ordering = OrderingQuestion(+        id = "q-ord", skillId = "count",+        prompt = Prompt("Order smallest to largest"), items = listOf("1", "2", "3"),+    )+    val matching = MatchingQuestion(+        id = "q-match", skillId = "count",+        prompt = Prompt("Match the number to its word"),+        left = listOf("1", "2"), right = listOf("one", "two"), correctRightForLeft = listOf(0, 1),+    )+    val tracing = TracingQuestion(+        id = "q-trace", skillId = "write",+        prompt = Prompt("Trace the letter"), glyph = "A",+    )+    val allQuestions = listOf(mcq, multiSelect, numeric, shortText, ordering, matching, tracing)++    val exercise = Exercise("ex1", "Counting practice", allQuestions.map { it.id })+    val k2Exercise = Exercise("ex-k2", "Play time", listOf("q-mc", "q-trace", "q-match"))++    val lesson = Lesson(+        id = "l1", title = "Counting 1-3",+        videos = listOf(VideoRef("http://127.0.0.1:9/count.mp4", "Counting video", 125)),+        exercise = exercise,+    )+    val k2Lesson = Lesson(id = "l-k2", title = "Fun with numbers", videos = lesson.videos, exercise = k2Exercise)+    val unitQuiz = Exercise("quiz-u1", "Unit quiz", listOf("q-mc", "q-num"))+    val unit = CourseUnit("u1", "Numbers", "Counting basics", listOf(lesson), quiz = unitQuiz)+    val k2Unit = CourseUnit("u-k2", "Play numbers", lessons = listOf(k2Lesson))+    val challenge = Exercise("ch1", "Big challenge", listOf("q-mc"))++    val mathCourse = Course(+        id = "c-math", subject = Subject.MATH, title = "Math Fun", description = "Numbers",+        gradeLevel = 1, units = listOf(unit, k2Unit), challenge = challenge,+    )+    val readingCourse = Course(+        id = "c-read", subject = Subject.READING, title = "Reading Time",+        gradeLevel = 4, units = listOf(CourseUnit("u-read", "Stories", lessons = listOf(Lesson("l-read", "Story time")))),+    )+    val scholarCourse = Course(+        id = "c-scholar", subject = Subject.SCIENCE, title = "Science Lab",+        gradeLevel = 8, units = listOf(CourseUnit("u-sci", "Experiments", lessons = listOf(Lesson("l-sci", "Volcanoes")))),+    )++    val pack = ContentPack(+        id = "test-pack", name = "Test Pack",+        skills = listOf(Skill("count", Subject.MATH, "Counting"), Skill("add", Subject.MATH, "Adding"), Skill("read", Subject.READING, "Reading"), Skill("write", Subject.READING, "Writing")),+        courses = listOf(mathCourse, readingCourse, scholarCourse),+        questions = allQuestions,+    )++    fun content(): ContentRepository = ContentRepository(listOf(pack))++    /** Seeds the process-wide Room cache with an in-memory EducationDatabase (avoids SQLCipher on JVM). */+    fun seedDb(context: Context): EducationDatabase {+        val app = context.applicationContext+        synchronized(databases) {+            val existing = databases[EducationDatabase::class]+            if (existing is EducationDatabase) return existing+            val db = Room.inMemoryDatabaseBuilder(app, EducationDatabase::class.java)+                .allowMainThreadQueries().build()+            databases[EducationDatabase::class] = db+            return db+        }+    }++    fun repository(context: Context): EducationRepository {+        seedDb(context)+        return EducationRepository.get(context.applicationContext)+    }+}
education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.kt b/education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.ktnew file mode 100644index 0000000000..3f4bf542ea--- /dev/null+++ b/education/src/test/java/com/vayunmathur/education/MainActivityRoutesTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.education++import com.vayunmathur.library.util.NavBackStack+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MainActivityRoutesTest {+    @Test fun routesCarryPayloads() {+        assertEquals(Route.Home, Route.Home)+        assertEquals(Route.Course("c1"), Route.Course("c1"))+        assertNotEquals<Route>(Route.Course("c1"), Route.Course("c2"))+        assertEquals("c1", Route.Course("c1").courseId)+        assertEquals("u1", Route.UnitScreen("u1").unitId)+        assertEquals("l1", Route.LessonScreen("l1").lessonId)+        assertEquals("e1", Route.Quiz("e1").exerciseId)+        assertEquals("http://x/v.mp4", Route.VideoPlayer("http://x/v.mp4", "T").videoUrl)+        assertEquals("T", Route.VideoPlayer("http://x/v.mp4", "T").title)+        assertEquals("l1", Route.K2Lesson("l1").lessonId)+        assertEquals("e1", Route.K2Quiz("e1").exerciseId)+        assertEquals(3, Route.K2Reward(3).stars)+        val results = Route.Results(7, 5, 2)+        assertEquals(7, results.total); assertEquals(5, results.correct); assertEquals(2, results.stars)+        assertEquals(Route.ParentGate, Route.ParentGate)+        assertEquals(Route.Parent, Route.Parent)+        assertEquals(Route.Badges, Route.Badges)+    }++    @Test fun pushChainReplacesSameClassOnly() {+        val bs = NavBackStack<Route>(arrayOf(Route.Home))+        bs.pushChain(Route.Course("c1"))+        assertEquals(listOf(Route.Home, Route.Course("c1")), bs.backStack)+        bs.pushChain(Route.Course("c2")) // same class: replace, don't stack+        assertEquals(listOf(Route.Home, Route.Course("c2")), bs.backStack)+        bs.pushChain(Route.UnitScreen("u1")) // different class: push+        assertEquals(3, bs.backStack.size)+        bs.pushChain(Route.UnitScreen("u2"))+        assertEquals(Route.UnitScreen("u2"), bs.last())+        assertEquals(3, bs.backStack.size)+        bs.pop(); assertEquals(Route.Course("c2"), bs.last())+        bs.reset(Route.Home); assertEquals(listOf(Route.Home), bs.backStack)+    }++    @Test fun mainActivityLaunchesWithoutCrashing() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        controller.create().start().resume()+        // Content loads content + DB on IO, then flips ready. Give the looper a chance.+        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        assertTrue(controller.get().isFinishing.not())+        controller.pause().stop().destroy()+    }+}
education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.kt b/education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.ktnew file mode 100644index 0000000000..267032cb0b--- /dev/null+++ b/education/src/test/java/com/vayunmathur/education/ui/EducationPagesTest.kt@@ -0,0 +1,357 @@+package com.vayunmathur.education.ui++import android.app.Application+import android.content.Context+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.education.EducationFixtures as Fx+import com.vayunmathur.education.MainGraph+import com.vayunmathur.education.R+import com.vayunmathur.education.RootNavigation+import com.vayunmathur.education.Route+import com.vayunmathur.education.data.Learner+import com.vayunmathur.education.data.SkillProgress+import com.vayunmathur.education.util.EducationViewModel+import com.vayunmathur.education.util.EducationViewModelFactory+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** VM-backed pages: render against an in-memory Room DB and drive real interactions. */+@RunWith(RobolectricTestRunner::class)+class EducationPagesTest {+    @get:Rule val rule = createComposeRule()+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val ctx: Context get() = app+    private val store = androidx.lifecycle.ViewModelStore()+    private val collectScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default)+    private lateinit var vm: EducationViewModel+    private var screenContent by androidx.compose.runtime.mutableStateOf<(@androidx.compose.runtime.Composable () -> Unit)?>(null)+    private var contentSet = false++    /** createComposeRule allows one setContent per activity; swap the lambda instead. */+    private fun show(content: @androidx.compose.runtime.Composable () -> Unit) {+        if (!contentSet) { rule.setContent { screenContent?.invoke() }; contentSet = true }+        screenContent = content+        rule.waitForIdle()+    }+    private fun str(id: Int, vararg a: Any): String = ctx.getString(id, *a)+    private fun uiStr(id: Int): String = ctx.getString(id)++    @Before fun setUp() = runBlocking<Unit> {+        val db = Fx.seedDb(ctx); db.clearAllTables()+        vm = androidx.lifecycle.ViewModelProvider(+            store, EducationViewModelFactory(app, Fx.content(), Fx.repository(ctx)),+        )[EducationViewModel::class.java]+        // Keep the WhileSubscribed flows hot so .value reads (verifyPin, deadlineFor) work.+        collectScope.launch { vm.learner.collect {} }+        collectScope.launch { vm.progress.collect {} }+        collectScope.launch { vm.deadlines.collect {} }+    }++    @After fun tearDown() { collectScope.cancel(); store.clear() }++    private fun stack(vararg routes: Route) = NavBackStack<Route>(routes)++    private fun seedLearner(learner: Learner) = runBlocking<Unit> {+        Fx.repository(ctx).upsertLearner(learner)+        val deadline = System.nanoTime() + 10_000_000_000L+        while (vm.learner.value?.id != learner.id && System.nanoTime() < deadline) {+            rule.waitForIdle(); Thread.sleep(10)+        }+    }++    private fun awaitText(text: String) {+        rule.waitUntil(10_000) { onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() }+    }++    @Test fun parentGateRejectsWrongPinAndAcceptsCorrect() = runBlocking<Unit> {+        Fx.repository(ctx).upsertLearner(Learner(name = "Kid"))+        vm.setPin("1234")+        val deadline = System.nanoTime() + 10_000_000_000L+        while (!vm.verifyPin("1234") && System.nanoTime() < deadline) Thread.sleep(10)+        // learner flow may lag the DB write; wait until VM observes the hash.+        while (vm.learner.value?.pinHash == null && System.nanoTime() < deadline) { rule.waitForIdle(); Thread.sleep(10) }+        val bs = stack(Route.Home, Route.ParentGate)+        show { ParentGatePage(bs, vm) }+        awaitText(str(R.string.grown_ups_only))+        rule.onNodeWithText(str(R.string.pin)).performTextInput("99")+        // Too short: Enter stays disabled; lengthen with wrong digits.+        rule.onNodeWithText(str(R.string.pin)).performTextInput("99")+        rule.onNodeWithText(str(R.string.enter)).performClick()+        awaitText(str(R.string.incorrect_pin))+        assertEquals(Route.ParentGate, bs.last())+        rule.onNodeWithText(str(R.string.pin)).performTextReplacement("1234")+        rule.onNodeWithText(str(R.string.enter)).performClick()+        rule.waitForIdle()+        assertEquals(Route.Parent, bs.last())++        val bs2 = stack(Route.Home, Route.ParentGate)+        show { ParentGatePage(bs2, vm) }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel), useUnmergedTree = true).performClick()+        assertEquals(Route.Home, bs2.last())+    }++    @Test fun parentPageRendersAndEdits() {+        seedLearner(Learner(name = "Maya", gradeLevel = 4, streakCount = 3, totalStars = 7, dailyGoal = 2))+        runBlocking { Fx.repository(ctx).upsertSkillProgress(SkillProgress("count", stars = 2, attempts = 1)) }+        val bs = stack(Route.Home, Route.Parent)+        show { ParentPage(bs, vm) }+        awaitText(str(R.string.parent_settings))+        awaitText("Maya")+        rule.onNodeWithText(str(R.string.learner)).performScrollTo().assertIsDisplayed()+        rule.onNodeWithText(str(R.string.progress)).performScrollTo().assertIsDisplayed()+        rule.onNodeWithText(str(R.string.module_deadlines)).performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Math Fun").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Numbers").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText(str(R.string.security)).performScrollTo().assertIsDisplayed()+        // Change the name and goal; both persist through the VM.+        rule.onNodeWithText("Maya").performScrollTo().performTextReplacement("Mayaa")+        val repo = Fx.repository(ctx)+        val deadline = System.nanoTime() + 10_000_000_000L+        var name = ""+        while (System.nanoTime() < deadline) {+            name = runBlocking { repo.getLearner()?.name.orEmpty() }+            if (name == "Mayaa") break+            Thread.sleep(10); rule.waitForIdle()+        }+        assertEquals("Mayaa", name)+        // Daily goal + button+        rule.onNodeWithText("+").performScrollTo().performClick()+        var goal = 0+        while (System.nanoTime() < deadline) {+            goal = runBlocking { repo.getLearner()?.dailyGoal ?: 0 }+            if (goal == 3) break+            Thread.sleep(10)+        }+        assertEquals(3, goal)+        // Set a PIN via the security row.+        rule.onNodeWithText(str(R.string.new_pin)).performScrollTo().performTextInput("4321")+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.save), useUnmergedTree = true).performScrollTo().performClick()+        var pinSet = false+        while (System.nanoTime() < deadline) {+            pinSet = runBlocking { repo.getLearner()?.pinHash } != null+            if (pinSet) break+            Thread.sleep(10)+        }+        assertTrue(pinSet)+        // Set-date flow opens the date picker dialog; dismiss it.+        rule.onAllNodesWithText(str(R.string.set_date))[0].performScrollTo().performClick()+        rule.waitForIdle()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel), useUnmergedTree = true).performClick()+        rule.waitForIdle()+    }++    @Test fun parentPageGradeAndBandDropdowns() {+        seedLearner(Learner(name = "Maya", gradeLevel = 1))+        val bs = stack(Route.Home, Route.Parent)+        show { ParentPage(bs, vm) }+        awaitText(str(R.string.parent_settings))+        // Grade dropdown lists kindergarten + numbered grades.+        rule.onNodeWithText(str(R.string.grade_number, 1)).performScrollTo().performClick()+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.grade_number, 5)).performClick()+        val repo = Fx.repository(ctx)+        val deadline = System.nanoTime() + 10_000_000_000L+        var grade = -1+        while (System.nanoTime() < deadline) {+            grade = runBlocking { repo.getLearner()?.gradeLevel ?: -1 }+            if (grade == 5) break+            Thread.sleep(10)+        }+        assertEquals(5, grade)+    }++    @Test fun explorerHomeSearchAndNavigate() {+        // Grade 4 is the Explorer (elementary) band: only elementary courses are listed.+        seedLearner(Learner(name = "Leo", gradeLevel = 4, streakCount = 2, totalStars = 5))+        val bs = stack(Route.Home)+        show { ExplorerHomePage(bs, vm) }+        awaitText("Reading Time")+        rule.onNodeWithText("Reading Time").assertIsDisplayed()+        // Searching for a non-band topic filters everything out.+        rule.onNodeWithText(str(R.string.find_a_topic)).performTextInput("math")+        rule.waitForIdle()+        assertTrue(onAllNodesWithText("Reading Time").fetchSemanticsNodes().isEmpty())+        rule.onNodeWithText(str(R.string.find_a_topic)).performTextReplacement("read")+        rule.waitForIdle()+        rule.onNodeWithText("Reading Time").performClick()+        assertEquals(Route.Course("c-read"), bs.last())+        // Continue card jumps to the first unmastered unit.+        val bs2 = stack(Route.Home)+        show { ExplorerHomePage(bs2, vm) }+        awaitText(str(R.string.jump_back_in))+        rule.onNodeWithText("Stories").performClick()+        assertEquals(Route.UnitScreen("u-read"), bs2.last())+    }++    @Test fun explorerCourseShowsPathAndMissing() {+        seedLearner(Learner(name = "Leo", gradeLevel = 4))+        runBlocking { Fx.repository(ctx).upsertSkillProgress(SkillProgress("count", stars = 3)) }+        val bs = stack(Route.Home, Route.Course("c-math"))+        show { ExplorerCoursePage(bs, vm, "c-math") }+        awaitText("Numbers")+        rule.onNodeWithText("Math Fun").assertIsDisplayed()+        rule.onNodeWithText("Big challenge").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Numbers").performClick()+        assertEquals(Route.UnitScreen("u1"), bs.last())++        val bs2 = stack(Route.Home)+        show { ExplorerCoursePage(bs2, vm, "missing-course") }+        awaitText(str(R.string.this_topic_is_unavailable))+    }++    @Test fun unitAndLessonPagesNavigate() {+        seedLearner(Learner(name = "Leo", gradeLevel = 1))+        val bs = stack(Route.Home, Route.Course("c-math"), Route.UnitScreen("u1"))+        show { UnitPage(bs, vm, "u1") }+        awaitText("Counting 1-3")+        rule.onNodeWithText("Unit quiz").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Counting 1-3").performClick()+        assertEquals(Route.LessonScreen("l1"), bs.last())++        val bs2 = stack(Route.Home, Route.UnitScreen("u1"), Route.LessonScreen("l1"))+        show { LessonPage(bs2, vm, "l1") }+        awaitText("Counting video")+        rule.onNodeWithText("Counting practice").performClick()+        assertEquals(Route.Quiz("ex1"), bs2.last())++        val bs3 = stack(Route.Home)+        show { UnitPage(bs3, vm, "missing") }+        awaitText(str(R.string.this_unit_is_unavailable))+        val bs4 = stack(Route.Home)+        show { LessonPage(bs4, vm, "missing") }+        awaitText(str(R.string.this_lesson_is_unavailable))+    }++    @Test fun k2HomeLessonAndReward() {+        seedLearner(Learner(name = "Kid", gradeLevel = 1, streakCount = 2, totalStars = 3))+        val bs = stack(Route.Home)+        show { K2HomePage(bs, vm) }+        awaitText("Counting 1-3")+        rule.onNodeWithText("Counting 1-3").performClick()+        assertEquals(Route.K2Lesson("l1"), bs.last())++        val bs2 = stack(Route.Home, Route.K2Lesson("l-k2"))+        show { K2LessonPage(bs2, vm, "l-k2") }+        awaitText(str(R.string.play))+        rule.onNodeWithText(str(R.string.play)).performClick()+        assertEquals(Route.K2Quiz("ex-k2"), bs2.last())++        val bs3 = stack(Route.Home, Route.K2Lesson("l-k2"))+        show { K2RewardPage(bs3, 2) }+        awaitText(str(R.string.you_did_it))+        rule.onNodeWithText("⭐⭐").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.home_1)).performClick()+        assertEquals(listOf(Route.Home), bs3.backStack)++        val bs4 = stack(Route.Home)+        show { K2LessonPage(bs4, vm, "missing") }+        awaitText(str(R.string.let_s_go_back))+    }++    @Test fun badgesResultsAndDispatchers() {+        seedLearner(Learner(name = "Maya", gradeLevel = 8, streakCount = 4, totalStars = 9))+        val bs = stack(Route.Home, Route.Badges)+        show { BadgesPage(bs, vm) }+        awaitText("First Star")+        rule.onNodeWithText("First Star").assertIsDisplayed()++        val bs2 = stack(Route.Home, Route.Quiz("ex1"), Route.Results(3, 2, 2))+        show { ResultsPage(bs2, vm, total = 3, correct = 2, stars = 2) }+        awaitText(str(R.string.correct, 2, 3))+        rule.onNodeWithText(str(R.string.home)).performClick()+        assertEquals(listOf(Route.Home), bs2.backStack)++        // Band dispatch: grade 1 -> Explorer course shell, grade 8 -> Scholar course shell.+        val bs3 = stack(Route.Home)+        show { CoursePage(bs3, vm, "c-math") }+        awaitText("Numbers")++        val bs4 = stack(Route.Home)+        show { HomePage(bs4, vm) }+        awaitText("Math Fun")++        // Root navigation waits for the learner, then shows the graph.+        show { RootNavigation(vm) }+        awaitText("Math Fun")+        show { MainGraph(vm) }+        awaitText("Math Fun")+    }++    @Test fun k2RewardStarCountsClamp() {+        val bs = stack(Route.Home)+        show { K2RewardPage(bs, 0) }+        awaitText("⭐")+        show { K2RewardPage(bs, 9) }+        awaitText("⭐⭐⭐")+    }++    @Test fun parentBandOverrideAndDeadlineDelete() = runBlocking<Unit> {+        seedLearner(Learner(name = "Maya", gradeLevel = 4))+        val repo = Fx.repository(ctx)+        repo.upsertDeadline(com.vayunmathur.education.data.Deadline(moduleType = "UNIT", moduleId = "u1", dueEpochDay = 20_000))+        val bs = stack(Route.Home, Route.Parent)+        show { ParentPage(bs, vm) }+        awaitText(str(R.string.parent_settings))+        // With a deadline set, that unit's button reads Change and shows a delete action.+        rule.onNodeWithText(str(R.string.change)).performScrollTo().assertIsDisplayed()+        rule.onNodeWithContentDescription("Delete").performScrollTo().performClick()+        val deadline = System.nanoTime() + 10_000_000_000L+        var deleted = false+        while (System.nanoTime() < deadline) {+            deleted = runBlocking { repo.getDeadlineFor("UNIT", "u1") } == null+            if (deleted) break+            Thread.sleep(10); rule.waitForIdle()+        }+        assertTrue(deleted)+        // Band override dropdown: pick Explorer explicitly.+        rule.onNodeWithText(str(R.string.automatic_by_grade)).performScrollTo().performClick()+        rule.waitForIdle()+        rule.onNodeWithText("3-5 · Explorer").performClick()+        var band: String? = null+        while (System.nanoTime() < deadline) {+            band = runBlocking { repo.getLearner()?.bandOverride }+            if (band == "ELEMENTARY") break+            Thread.sleep(10)+        }+        assertEquals("ELEMENTARY", band)+        // Deadline dialog OK path: open, pick the dialog's OK (disabled until a date is chosen, so just dismiss via Cancel).+        rule.onAllNodesWithText(str(R.string.set_date))[0].performScrollTo().performClick()+        rule.waitForIdle()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel), useUnmergedTree = true).performClick()+        rule.waitForIdle()+    }++    @Test fun scholarHomeDeadlineAndParentAreaRoutes() = runBlocking<Unit> {+        seedLearner(Learner(name = "Maya", gradeLevel = 8, onboarded = false))+        Fx.repository(ctx).upsertDeadline(com.vayunmathur.education.data.Deadline(moduleType = "UNIT", moduleId = "u1", dueEpochDay = 20_000))+        val bs = stack(Route.Home)+        show { HomePage(bs, vm) }+        // Scholar home lists the deadline by its module title and routes to the unit.+        awaitText("Numbers")+        rule.onNodeWithText("Numbers").performScrollTo().performClick()+        assertEquals(Route.UnitScreen("u1"), bs.last())+    }++    private fun onAllNodesWithText(text: String) = rule.onAllNodesWithText(text)+}
education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.kt b/education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.ktnew file mode 100644index 0000000000..25326c5ea5--- /dev/null+++ b/education/src/test/java/com/vayunmathur/education/ui/EducationQuizInputsTest.kt@@ -0,0 +1,273 @@+package com.vayunmathur.education.ui++import android.content.Context+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+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.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.geometry.Offset+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.education.EducationFixtures as Fx+import com.vayunmathur.education.R+import com.vayunmathur.education.content.Answer+import com.vayunmathur.education.content.ChoiceAnswer+import com.vayunmathur.education.content.MatchingAnswer+import com.vayunmathur.education.content.MultiChoiceAnswer+import com.vayunmathur.education.content.NumericAnswer+import com.vayunmathur.education.content.OrderingAnswer+import com.vayunmathur.education.content.TextAnswer+import com.vayunmathur.education.util.QuizActions+import com.vayunmathur.education.util.QuizUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/** Question inputs, both quiz shells, and shared UI helpers. */+@RunWith(RobolectricTestRunner::class)+class EducationQuizInputsTest {+    @get:Rule val rule = createComposeRule()+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private var screenContent by androidx.compose.runtime.mutableStateOf<(@androidx.compose.runtime.Composable () -> Unit)?>(null)+    private var contentSet = false++    private fun show(content: @androidx.compose.runtime.Composable () -> Unit) {+        if (!contentSet) { rule.setContent { screenContent?.invoke() }; contentSet = true }+        screenContent = content+        rule.waitForIdle()+    }+    private fun str(id: Int, vararg a: Any): String = ctx.getString(id, *a)++    @Test fun multipleChoiceSelectsAndReports() {+        var answer: Answer? = null+        show { QuestionInput(Fx.mcq, ChoiceAnswer(0), enabled = true) { answer = it } }+        rule.onNodeWithText("3").assertIsDisplayed().performClick()+        assertEquals(ChoiceAnswer(1), answer)+        rule.onNodeWithText("7").performClick()+        assertEquals(ChoiceAnswer(2), answer)+    }++    @Test fun multipleSelectTogglesSet() {+        var answer: Answer? = null+        show { QuestionInput(Fx.multiSelect, null, enabled = true) { answer = it } }+        rule.onNodeWithText("2").performClick()+        assertEquals(MultiChoiceAnswer(setOf(0)), answer)+        rule.onNodeWithText("4").performClick()+        assertEquals(MultiChoiceAnswer(setOf(0, 2)), answer)+        rule.onNodeWithText("2").performClick()+        assertEquals(MultiChoiceAnswer(setOf(2)), answer)+    }++    @Test fun numericAndShortTextInputs() {+        var answer: Answer? = null+        show { QuestionInput(Fx.numeric, null, enabled = true) { answer = it } }+        rule.onNodeWithText(str(R.string.answer_1, "apples")).performTextInput("42")+        assertEquals(NumericAnswer(42.0), answer)+        show { QuestionInput(Fx.shortText, null, enabled = true) { answer = it } }+        rule.onNodeWithText(str(R.string.answer)).performTextInput("a")+        assertEquals(TextAnswer("a"), answer)+    }++    @Test fun orderingPublishesInitialAndReorders() {+        var answer: Answer? = null+        show { QuestionInput(Fx.ordering, null, enabled = true) { answer = it } }+        rule.waitForIdle()+        val initial = answer as? OrderingAnswer+        assertNotNull(initial)+        assertEquals(listOf(0, 1, 2), initial.order.sorted())+        assertTrue(rule.onAllNodesWithText("3").fetchSemanticsNodes().isNotEmpty())+    }++    @Test fun matchingPublishesWhenComplete() {+        var answer: Answer? = null+        show { QuestionInput(Fx.matching, null, enabled = true) { answer = it } }+        // Pick the right-hand option for the first left item, then the second.+        rule.onAllNodesWithText(str(R.string.choose))[0].performClick()+        rule.waitForIdle()+        rule.onNodeWithText("one").performClick()+        rule.waitForIdle()+        assertEquals(null, answer)+        rule.onAllNodesWithText(str(R.string.choose))[0].performClick()+        rule.waitForIdle()+        rule.onNodeWithText("two").performClick()+        rule.waitForIdle()+        assertEquals(MatchingAnswer(listOf(0, 1)), answer)+    }++    @Test fun tracingGestureCompletes() {+        var traced = false+        show { TracingCanvas(glyph = "B", enabled = true, onTraced = { traced = true }) }+        rule.onNodeWithText("B").assertIsDisplayed()+        assertEquals(false, traced)+        // Long horizontal swipes across the canvas accumulate past the trace threshold.+        val root = rule.onRoot()+        repeat(4) {+            root.performTouchInput { swipe(Offset(60f, center.y), Offset(width - 60f, center.y), 120) }+            rule.waitForIdle()+        }+        assertEquals(true, traced)+    }++    @Test fun dragMatchRendersAndMissedDropSnapsBack() {+        var solved = false+        show { K2DragMatch(Fx.matching, enabled = true) { solved = true } }+        rule.onNodeWithText("one").assertIsDisplayed()+        rule.onNodeWithText("two").assertIsDisplayed()+        // Drag a chip a short distance inside its own column (no target there):+        // a missed drop must snap back and not solve or mark any target.+        // (Synthetic gestures cannot reproduce the per-frame bounds updates the+        // hit test uses on a real device, so the correct-drop path is not+        // asserted here.)+        rule.onNodeWithText("one").performTouchInput {+            swipe(Offset(center.x, center.y), Offset(center.x, center.y + 60f), 200)+        }+        rule.waitForIdle()+        assertEquals(false, solved)+        rule.onNodeWithText("one").assertIsDisplayed()+        rule.onNodeWithText("1").assertIsDisplayed()+    }++    @Test fun quizScreenFullFlowScholar() {+        var finishedQuestions: Int = -1+        var finishedAnswers: Map<String, Answer?>? = null+        var up = false+        val actions = object : QuizActions {+            override fun navigateUp() { up = true }+            override fun finish(questions: List<com.vayunmathur.education.content.Question>, answers: Map<String, Answer?>) {+                finishedQuestions = questions.size; finishedAnswers = answers+            }+        }+        val questions = listOf(Fx.mcq, Fx.numeric)+        show { QuizScreen(QuizUiState(title = "Practice", questions = questions), actions) }+        rule.onNodeWithText("Practice").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.question_of, 1, 2)).assertIsDisplayed()+        // Check is disabled until an answer is chosen.+        rule.onNodeWithText("3").performClick()+        rule.onNodeWithText(str(R.string.show_a_hint)).performClick()+        rule.waitForIdle()+        rule.onNodeWithText("💡 Count them one by one.").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.check)).performClick()+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.correct_1)).assertIsDisplayed()+        rule.onNodeWithText("There are three apples.").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.next)).performClick()+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.answer_1, "apples")).performTextInput("5")+        rule.onNodeWithText(str(R.string.check)).performClick()+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.finish)).performClick()+        assertEquals(2, finishedQuestions)+        assertEquals(ChoiceAnswer(1), finishedAnswers?.get("q-mc"))+        assertEquals(NumericAnswer(5.0), finishedAnswers?.get("q-num"))+        assertEquals(false, up)+    }++    @Test fun quizScreenEmptyAndWrongFeedback() {+        show { QuizScreen(QuizUiState(title = "Empty", questions = emptyList()), QuizActions.Noop) }+        rule.onNodeWithText(str(R.string.this_exercise_has_no_questions_yet)).assertIsDisplayed()+        show {+            QuizScreen(+                QuizUiState(title = "Practice", questions = listOf(Fx.mcq)), QuizActions.Noop,+                initialIndex = 0, initialChecked = true, initialAnswers = mapOf("q-mc" to ChoiceAnswer(0)),+            )+        }+        rule.onNodeWithText(str(R.string.not_quite)).assertIsDisplayed()+    }++    @Test fun k2QuizCorrectAdvancesAndFinishes() {+        var finished: Int = -1+        val actions = object : QuizActions {+            override fun finish(questions: List<com.vayunmathur.education.content.Question>, answers: Map<String, Answer?>) { finished = questions.size }+        }+        show { K2QuizScreen(QuizUiState(questions = listOf(Fx.mcq, Fx.tracing)), actions) }+        rule.onNodeWithText("How many apples?").assertIsDisplayed()+        // Wrong choice wiggles into the error color but stays on the question.+        rule.onNodeWithText("1").performClick()+        rule.waitForIdle()+        rule.onNodeWithText("How many apples?").assertIsDisplayed()+        assertEquals(-1, finished)+        // Correct choice celebrates, then advances to tracing; finish after the trace question.+        rule.onNodeWithText("3").performClick()+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.great_job)).assertIsDisplayed()+        rule.waitUntil(10_000) { rule.onAllNodesWithText("Trace the letter").fetchSemanticsNodes().isNotEmpty() }+        // Trace the glyph to complete the last question; the quiz then finishes.+        val root = rule.onRoot()+        var swipes = 0+        while (finished != 2 && swipes < 6) {+            root.performTouchInput { swipe(Offset(60f, center.y), Offset(width - 60f, center.y), 120) }+            rule.waitForIdle()+            swipes+++        }+        rule.waitUntil(10_000) { finished == 2 }+    }++    @Test fun k2QuizEmptyShowsGoBack() {+        show { K2QuizScreen(QuizUiState(questions = emptyList()), QuizActions.Noop) }+        rule.onNodeWithText(str(R.string.let_s_go_back)).assertIsDisplayed()+    }++    @Test fun commonHelpers() {+        show {+            androidx.compose.foundation.layout.Column {+                StarRow(2)+                StreakChip(3)+                StarsChip(7)+                DeadlineChip(System.currentTimeMillis() / 86_400_000)+                SectionHeader("Header text")+            }+        }+        rule.onNodeWithText("Header text").assertIsDisplayed()+        rule.onNodeWithText("7").assertIsDisplayed()+        assertEquals("K-2 · Guided Playground", bandLabel(com.vayunmathur.education.content.Band.K2))+        assertEquals("3-5 · Explorer", bandLabel(com.vayunmathur.education.content.Band.ELEMENTARY))+        assertEquals("6-12 · Scholar", bandLabel(com.vayunmathur.education.content.Band.SCHOLAR))+        assertEquals(0, averageStars(emptyList(), emptyMap()))+        assertEquals(2, averageStars(listOf("a", "b"), mapOf("a" to com.vayunmathur.education.data.SkillProgress("a", stars = 3), "b" to com.vayunmathur.education.data.SkillProgress("b", stars = 1))))+        assertTrue(formatEpochDay(ctx, 20_000).isNotEmpty())+        // Subject colors are defined for every subject.+        show {+            androidx.compose.foundation.layout.Column {+                com.vayunmathur.education.content.Subject.entries.forEach { s -> Text2Colors(s) }+            }+        }+        rule.waitForIdle()+    }++    @androidx.compose.runtime.Composable+    private fun Text2Colors(s: com.vayunmathur.education.content.Subject) {+        val c = subjectColors(s)+        com.vayunmathur.library.ui.Text(s.name + ":" + c.container.value.toString())+    }++    @Test fun rememberNarratorComposesAndDisposes() {+        show {+            val narrator = com.vayunmathur.education.util.rememberNarrator()+            androidx.compose.runtime.LaunchedEffect(Unit) { narrator.narrate("Ready to learn") }+            com.vayunmathur.library.ui.Text("narrator up")+        }+        rule.onNodeWithText("narrator up").assertIsDisplayed()+        // Swapping content disposes the narrator (TTS shutdown under Robolectric).+        show { com.vayunmathur.library.ui.Text("gone") }+        rule.onNodeWithText("gone").assertIsDisplayed()+    }++    @Test fun videoPlayerRendersTitle() {+        val bs = com.vayunmathur.library.util.NavBackStack<com.vayunmathur.education.Route>(arrayOf(com.vayunmathur.education.Route.Home))+        show { VideoPlayerPage(bs, "http://127.0.0.1:9/none.mp4", "Space video") }+        rule.onNodeWithText("Space video").assertIsDisplayed()+    }++    private fun onAllNodesWithText(text: String) = rule.onAllNodesWithText(text)+}
education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.kt b/education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.ktnew file mode 100644index 0000000000..d3f00aebe0--- /dev/null+++ b/education/src/test/java/com/vayunmathur/education/util/EducationViewModelTest.kt@@ -0,0 +1,288 @@+package com.vayunmathur.education.util++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.education.EducationFixtures as Fx+import com.vayunmathur.education.content.Band+import com.vayunmathur.education.content.ChoiceAnswer+import com.vayunmathur.education.content.ContentRepository+import com.vayunmathur.education.content.MatchingAnswer+import com.vayunmathur.education.content.ModuleType+import com.vayunmathur.education.content.MultiChoiceAnswer+import com.vayunmathur.education.content.NumericAnswer+import com.vayunmathur.education.content.OrderingAnswer+import com.vayunmathur.education.content.TextAnswer+import com.vayunmathur.education.content.TraceAnswer+import com.vayunmathur.education.data.Deadline+import com.vayunmathur.education.data.Learner+import com.vayunmathur.education.data.SkillProgress+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class EducationViewModelTest {+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val ctx: Context get() = app+    private val store = androidx.lifecycle.ViewModelStore()+    private val collectScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default)+    private lateinit var vm: EducationViewModel++    @Before fun setUp() = runBlocking<Unit> {+        val db = Fx.seedDb(ctx)+        db.clearAllTables()+        vm = androidx.lifecycle.ViewModelProvider(+            store,+            EducationViewModelFactory(app, Fx.content(), Fx.repository(ctx)),+        )[EducationViewModel::class.java]+        // The VM's flows are WhileSubscribed: keep collectors running so .value updates.+        collectScope.launch { vm.learner.collect {} }+        collectScope.launch { vm.progress.collect {} }+        collectScope.launch { vm.deadlines.collect {} }+    }++    @After fun tearDown() { collectScope.cancel(); store.clear() }++    private fun awaitVm(label: String, cond: () -> Boolean) {+        // viewModelScope runs on the (paused) Robolectric main looper: pump it while waiting.+        val deadline = System.nanoTime() + 10_000_000_000L+        while (!cond() && System.nanoTime() < deadline) {+            org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            Thread.sleep(10)+        }+        assertTrue(cond(), "timed out awaiting: $label")+    }++    // --- DAO / repository -------------------------------------------------++    @Test fun daoCrudAndFlows() = runBlocking<Unit> {+        val repo = Fx.repository(ctx)+        assertNull(repo.getLearner())+        repo.upsertLearner(Learner(name = "Maya", gradeLevel = 3, totalStars = 4))+        assertEquals("Maya", repo.getLearner()?.name)+        assertEquals("Maya", repo.learnerFlow().first()?.name)+        repo.upsertLearner(Learner(name = "Leo"))+        assertEquals(1L, repo.getLearner()?.id); assertEquals("Leo", repo.getLearner()?.name)++        repo.upsertSkillProgress(SkillProgress("count", stars = 2, attempts = 1, lastPracticedEpochDay = 10))+        repo.upsertSkillProgress(SkillProgress("add", stars = 3))+        assertEquals(2, repo.getAllSkillProgress().size)+        assertEquals(2, repo.skillProgressFlow().first().size)+        assertEquals(3, repo.getSkillProgress("add")?.stars)+        assertNull(repo.getSkillProgress("nope"))++        repo.upsertDeadline(Deadline(moduleType = "UNIT", moduleId = "u1", dueEpochDay = 100, note = "n"))+        repo.upsertDeadline(Deadline(moduleType = "UNIT", moduleId = "u2", dueEpochDay = 50))+        assertEquals(listOf(50L, 100L), repo.deadlinesFlow().first().map { it.dueEpochDay })+        val found = repo.getDeadlineFor("UNIT", "u1"); assertNotNull(found)+        repo.deleteDeadline(found)+        assertNull(repo.getDeadlineFor("UNIT", "u1"))+        assertEquals(1, repo.deadlinesFlow().first().size)+    }++    @Test fun repositoryIsSingleton() {+        assertTrue(Fx.repository(ctx) === Fx.repository(ctx))+    }++    // --- Content repository ----------------------------------------------++    @Test fun contentRepositoryIndexesAndQueries() {+        val content = Fx.content()+        assertEquals(3, content.courses.size)+        assertEquals(setOf("q-mc", "q-ms", "q-num", "q-text", "q-ord", "q-match", "q-trace"), content.questions.keys)+        assertEquals(Fx.mathCourse, content.course("c-math")); assertNull(content.course("nope"))+        assertEquals(Fx.unit, content.unit("u1")); assertEquals(Fx.lesson, content.lesson("l1"))+        assertEquals(Fx.exercise, content.exercise("ex1")); assertEquals(Fx.unitQuiz, content.exercise("quiz-u1"))+        assertEquals(Fx.challenge, content.exercise("ch1")); assertNull(content.exercise("nope"))+        assertEquals(Fx.mathCourse, content.courseOfUnit("u1")); assertNull(content.courseOfUnit("nope"))+        assertEquals(Fx.allQuestions, content.questionsFor(Fx.exercise))+        assertEquals(listOf("count"), content.skillIdsOf(Fx.unitQuiz.copy(questionIds = listOf("q-mc"))))+        assertTrue(content.skillIdsOfCourse(Fx.mathCourse).containsAll(listOf("count", "add", "read", "write")))+        assertEquals("Math Fun", content.moduleTitle(ModuleType.COURSE, "c-math"))+        assertEquals("Numbers", content.moduleTitle(ModuleType.UNIT, "u1"))+        assertEquals("Counting 1-3", content.moduleTitle(ModuleType.LESSON, "l1"))+        assertNull(content.moduleTitle(ModuleType.LESSON, "nope"))+        assertEquals(listOf(Fx.mathCourse), content.coursesForBand(Band.K2))+        assertEquals(listOf(Fx.readingCourse), content.coursesForBand(Band.ELEMENTARY))+        assertEquals(listOf(Fx.scholarCourse), content.coursesForBand(Band.SCHOLAR))+        assertEquals(listOf(Fx.mathCourse), content.coursesForSubject(com.vayunmathur.education.content.Subject.MATH))+        assertEquals(emptyList(), content.coursesForSubject(com.vayunmathur.education.content.Subject.MATH, Band.SCHOLAR))+        assertEquals(listOf(com.vayunmathur.education.content.Subject.MATH, com.vayunmathur.education.content.Subject.SCIENCE, com.vayunmathur.education.content.Subject.READING), content.subjects)+        val empty = ContentRepository(emptyList())+        assertTrue(empty.courses.isEmpty() && empty.questions.isEmpty() && empty.subjects.isEmpty())+    }++    @Test fun contentRepositoryLoadsBundledAssets() {+        val loaded = ContentRepository.load(ctx)+        assertTrue(loaded.courses.isNotEmpty(), "bundled content packs should parse")+        assertTrue(loaded.questions.isNotEmpty())+        assertTrue(loaded.courses.all { it.units.isNotEmpty() })+    }++    // --- Pure VM logic ------------------------------------------------------++    @Test fun gradeCoversEveryQuestionType() {+        val allRight = mapOf(+            "q-mc" to ChoiceAnswer(1), "q-ms" to MultiChoiceAnswer(setOf(0, 2)),+            "q-num" to NumericAnswer(5.05), "q-text" to TextAnswer(" A "),+            "q-ord" to OrderingAnswer(listOf(0, 1, 2)), "q-match" to MatchingAnswer(listOf(0, 1)),+            "q-trace" to TraceAnswer,+        )+        val perfect = vm.grade(Fx.allQuestions, allRight)+        assertEquals(7, perfect.total); assertEquals(7, perfect.correct); assertEquals(3, perfect.stars)+        assertEquals(3, perfect.perSkillStars["count"])++        val allWrong = mapOf(+            "q-mc" to ChoiceAnswer(0), "q-ms" to MultiChoiceAnswer(setOf(1)),+            "q-num" to NumericAnswer(6.0), "q-text" to TextAnswer("z"),+            "q-ord" to OrderingAnswer(listOf(2, 1, 0)), "q-match" to MatchingAnswer(listOf(1, 0)),+            "q-trace" to ChoiceAnswer(0),+        )+        val zero = vm.grade(Fx.allQuestions, allWrong)+        assertEquals(0, zero.correct); assertEquals(0, zero.stars)+        // Missing answers count as wrong, empty quiz is 0 stars.+        assertEquals(0, vm.grade(Fx.allQuestions, emptyMap()).correct)+        assertEquals(QuizResult(0, 0, 0, emptyMap()), vm.grade(emptyList(), emptyMap()))+    }++    @Test fun bandOfHonoursOverrideAndGrades() = runBlocking<Unit> {+        assertEquals(Band.SCHOLAR, vm.bandOf(null))+        assertEquals(Band.K2, vm.bandOf(Learner(gradeLevel = 0)))+        assertEquals(Band.K2, vm.bandOf(Learner(gradeLevel = 2)))+        assertEquals(Band.ELEMENTARY, vm.bandOf(Learner(gradeLevel = 3)))+        assertEquals(Band.ELEMENTARY, vm.bandOf(Learner(gradeLevel = 5)))+        assertEquals(Band.SCHOLAR, vm.bandOf(Learner(gradeLevel = 6)))+        assertEquals(Band.K2, vm.bandOf(Learner(gradeLevel = 9, bandOverride = "K2")))+        assertEquals(Band.SCHOLAR, vm.bandOf(Learner(gradeLevel = 9, bandOverride = "bogus")))+    }++    @Test fun starsAndStreakBoundaries() {+        assertEquals(0, EducationViewModel.starsFor(0, 0))+        assertEquals(3, EducationViewModel.starsFor(10, 10))+        assertEquals(2, EducationViewModel.starsFor(7, 10))+        assertEquals(1, EducationViewModel.starsFor(4, 10))+        assertEquals(0, EducationViewModel.starsFor(3, 10))+        assertEquals(3, EducationViewModel.MAX_STARS)+        assertEquals(1, EducationViewModel.nextStreak(0, 0, 5))+        assertEquals(4, EducationViewModel.nextStreak(3, 4, 5))+        assertEquals(3, EducationViewModel.nextStreak(3, 5, 5))+        assertEquals(1, EducationViewModel.nextStreak(3, 1, 5))+    }++    // --- VM persistence flows --------------------------------------------++    @Test fun learnerEditsPersistAndPinVerifies() = runBlocking<Unit> {+        val repo = Fx.repository(ctx)+        repo.upsertLearner(Learner(name = "Start", gradeLevel = 1))+        awaitVm("learner seeded") { vm.learner.value?.name == "Start" }+        vm.setName("  Maya  "); awaitVm("name") { runBlocking { repo.getLearner()?.name } == "Maya" }+        vm.setGrade(4); awaitVm("grade") { runBlocking { repo.getLearner()?.gradeLevel } == 4 }+        vm.setAvatar("🐯"); awaitVm("avatar") { runBlocking { repo.getLearner()?.avatar } == "🐯" }+        vm.setDailyGoal(0); awaitVm("goal coerced") { runBlocking { repo.getLearner()?.dailyGoal } == 1 }+        vm.setDailyGoal(5); awaitVm("goal") { runBlocking { repo.getLearner()?.dailyGoal } == 5 }+        vm.setBandOverride(Band.K2); awaitVm("band") { runBlocking { repo.getLearner()?.bandOverride } == "K2" }+        vm.setBandOverride(null); awaitVm("band cleared") { runBlocking { repo.getLearner()?.bandOverride } == null }++        assertFalse(vm.verifyPin("1234"))+        vm.setPin("1234"); awaitVm("pin") { runBlocking { repo.getLearner()?.pinHash } != null }+        // learner StateFlow must refresh for verifyPin (it reads learner.value).+        awaitVm("learner flow pin") { vm.learner.value?.pinHash != null }+        assertTrue(vm.verifyPin("1234")); assertFalse(vm.verifyPin("9999")); assertFalse(vm.verifyPin(""))+    }++    @Test fun deadlineSetUpdateRemoveThroughVm() = runBlocking<Unit> {+        val repo = Fx.repository(ctx)+        vm.setDeadline(ModuleType.UNIT, "u1", 100, "first")+        awaitVm("deadline created") { runBlocking { repo.getDeadlineFor("UNIT", "u1")?.dueEpochDay } == 100L }+        vm.setDeadline(ModuleType.UNIT, "u1", 120, "second")+        awaitVm("deadline updated") { runBlocking { repo.getDeadlineFor("UNIT", "u1")?.dueEpochDay } == 120L }+        assertEquals(1, repo.deadlinesFlow().first().size)+        awaitVm("vm deadlines flow") { vm.deadlineFor(ModuleType.UNIT, "u1")?.dueEpochDay == 120L }+        val row = repo.getDeadlineFor("UNIT", "u1")!!+        vm.removeDeadline(row)+        awaitVm("deadline removed") { runBlocking { repo.getDeadlineFor("UNIT", "u1") } == null }+        awaitVm("vm deadline cleared") { vm.deadlineFor(ModuleType.UNIT, "u1") == null }+    }++    @Test fun commitResultPersistsProgressStreakAndStars() = runBlocking<Unit> {+        val repo = Fx.repository(ctx)+        repo.upsertLearner(Learner(name = "Maya", streakCount = 2))+        val result = vm.grade(Fx.allQuestions, mapOf("q-mc" to ChoiceAnswer(1), "q-num" to NumericAnswer(5.0)))+        vm.commitResult(result)+        awaitVm("progress persisted") { runBlocking { repo.getSkillProgress("count") } != null }+        val count = repo.getSkillProgress("count")!!+        assertTrue(count.attempts >= 1); assertTrue(count.lastPracticedEpochDay > 0)+        awaitVm("learner stars") { runBlocking { repo.getLearner()?.totalStars ?: 0 } >= 1 }+        val learner = repo.getLearner()!!+        assertTrue(learner.totalStars >= 1)+        assertTrue(learner.streakCount >= 1)+        // A second commit keeps best-of stars and bumps attempts.+        val before = repo.getSkillProgress("count")!!.attempts+        vm.commitResult(vm.grade(Fx.allQuestions, emptyMap()))+        awaitVm("attempts bumped") { runBlocking { repo.getSkillProgress("count")?.attempts } == before + 1 }+        assertTrue(repo.getSkillProgress("count")!!.stars >= count.stars)+        // Progress flow reflects the map shape the UI consumes.+        awaitVm("progress flow") { vm.progress.value.containsKey("count") }+        val map = vm.progress.value+        assertEquals(repo.getSkillProgress("count")?.stars, map["count"]?.stars)+        // Badge statuses always list every badge; first_star unlocks after earning a star.+        val deadline = System.nanoTime() + 10_000_000_000L+        var statuses = vm.badgeStatuses().first()+        while (statuses.none { it.achievement.id == EducationAchievements.Ids.FIRST_STAR && it.isUnlocked } && System.nanoTime() < deadline) {+            org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            Thread.sleep(25); statuses = vm.badgeStatuses().first()+        }+        assertEquals(EducationAchievements.STICKERS.size, statuses.size)+        assertTrue(statuses.first { it.achievement.id == EducationAchievements.Ids.FIRST_STAR }.isUnlocked)+        vm.dismissBadge()+    }++    // --- Entities, achievements, narrator --------------------------------++    @Test fun entityDefaultsAndStickers() {+        val learner = Learner()+        assertEquals(Learner.SINGLE_ID, learner.id); assertEquals("🦉", learner.avatar); assertEquals(1, learner.dailyGoal)+        assertEquals(SkillProgress("s"), SkillProgress("s", 0, 0, 0))+        assertEquals("", Deadline(moduleType = "UNIT", moduleId = "u", dueEpochDay = 1).note)+        assertEquals("⭐", EducationAchievements.STICKERS[EducationAchievements.Ids.FIRST_STAR])+        assertEquals(8, EducationAchievements.STICKERS.size)+        val ach = EducationAchievements(ctx)+        assertEquals(8, ach.achievements.size)+        ach.dismissNotification(); assertNull(ach.newAchievement.value)+    }++    @Test fun narratorNoOpsBeforeReady() {+        val narrator = Narrator(ctx)+        narrator.narrate("Hello there")+        narrator.narrate("With clip", "missing-clip.mp3")+        narrator.speak("Speak")+        narrator.speak("")+        narrator.stop()+        narrator.shutdown()+    }++    private class ForeignVm : androidx.lifecycle.ViewModel()++    @Test fun factoryRejectsForeignViewModelClass() {+        val factory = EducationViewModelFactory(app, Fx.content(), Fx.repository(ctx))+        assertEquals(vm.javaClass, factory.create(EducationViewModel::class.java).javaClass)+        try {+            factory.create(ForeignVm::class.java)+            throw AssertionError("expected IllegalArgumentException")+        } catch (expected: IllegalArgumentException) {+            assertTrue(expected.message!!.contains("Unexpected"))+        }+    }+}