library: add tests for navigation, backup, markdown, datastore and sensors
- Commit
3f2b42c771361dd8bc2745e9d59985f0fdb13f18- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 14:06 UTC (28 days ago)
- Parents
2fe3e32
Third coverage pass for the base library module: Robolectric/Compose tests for MainNavigation (all NavMotion transitions, dialog entries, shared-element modifiers, message drain), NavigationBottomBar, NavResultRegistry/ResultEffect, openSettingsIfRequested, markdown (math/LaTeX/search/fences/tasks), BackupHelper/ZipBackupFormat/ BaseBackupAgent (incl. unchanged-state copy), DatabaseHelper crypto via an in-memory AndroidKeyStore provider fake, DefaultConverters and MatchingDao against a Room test database, DataStoreUtils accessors and Direct Boot seeding, DailyChallengeStore streaks, AchievementsManager, LevelStatsRepository, GameHubReporter/GameHubCompose hooks with no hub installed, OrientationManager rotation-vector and accel/mag fallback events for every display rotation, notifications, IntentHelper, AssistantIntent activities, LocalizedDateNames (incl. the pre-33 formatSpeed fallback under sdk=32) and every IPC DTO round-trip. Coverage (merged, instructions): 22.7% (3,698/16,300) -> 86.7% (14,099/16,272; total shifted slightly by the two bug fixes below). 127 unit tests, 0 failures via :library:createMergedCoverageReport. The MatchingDao test database needs its Room-generated impl, so kspTest gets the Room compiler (same as library:room). Remainder (honest): IntentLauncher's ResultReceiver response path (Robolectric's parcel shadow drops the binder, so only the intent-building/pending side is asserted), FileDropModifier's onDrop drag events, and NavTransitions.predictivePop (needs a real predictive back gesture). (cherry picked from commit a56f002a28b2260323c9f22bb50e226677bf7635)
Diff
library/build.gradle.kts
diff --git a/library/build.gradle.kts b/library/build.gradle.ktsindex f112e13980..747e111bd6 100644--- a/library/build.gradle.kts+++ b/library/build.gradle.kts@@ -22,4 +22,7 @@ dependencies { // GameHub SDK — GameHubReporter bridge implementation(project(":sdk:games"))++ // The unit tests' Room database (MatchingDao) needs its generated impl.+ add("kspTest", libs.androidx.room3.compiler) }
library/src/test/java/com/vayunmathur/library/intents/IpcDto2Test.kt
diff --git a/library/src/test/java/com/vayunmathur/library/intents/IpcDto2Test.kt b/library/src/test/java/com/vayunmathur/library/intents/IpcDto2Test.ktnew file mode 100644index 0000000000..9d62e54fbd--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/intents/IpcDto2Test.kt@@ -0,0 +1,105 @@+package com.vayunmathur.library.intents++import com.vayunmathur.library.intents.calendar.EventData+import com.vayunmathur.library.intents.clock.SetAlarmData+import com.vayunmathur.library.intents.clock.SetTimerData+import com.vayunmathur.library.intents.contacts.ContactData+import com.vayunmathur.library.intents.email.EmailData+import com.vayunmathur.library.intents.email.EmailSearchQuery+import com.vayunmathur.library.intents.findfamily.FamilyMemberData+import com.vayunmathur.library.intents.maps.DirectionsLatLng+import com.vayunmathur.library.intents.maps.DirectionsRequest+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.intents.maps.DirectionsSegment+import com.vayunmathur.library.intents.music.MusicSearchResult+import com.vayunmathur.library.intents.music.PlayMusicData+import com.vayunmathur.library.intents.notes.InsertNoteData+import com.vayunmathur.library.intents.notes.NoteData+import com.vayunmathur.library.intents.todo.CompleteTodoData+import com.vayunmathur.library.intents.todo.GetTodosQuery+import com.vayunmathur.library.intents.todo.InsertTodoData+import com.vayunmathur.library.intents.todo.TodoData+import com.vayunmathur.library.intents.weather.WeatherData+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Every remaining IPC DTO round-trips through JSON with defaults intact. */+class IpcDto2Test {+ private val json = Json++ private inline fun <reified T : Any> roundTrip(value: T, serializer: kotlinx.serialization.KSerializer<T>) {+ assertEquals(value, json.decodeFromString(serializer, json.encodeToString(serializer, value)))+ }++ @Test fun simpleDtos() {+ roundTrip(EventData("Meet", 100, 200, "Office"), EventData.serializer())+ roundTrip(EventData("Meet", 100, 200), EventData.serializer())+ assertEquals("", EventData("Meet", 100, 200).location)+ roundTrip(SetAlarmData(7, 30, "Wake"), SetAlarmData.serializer())+ roundTrip(SetAlarmData(7, 30), SetAlarmData.serializer())+ roundTrip(SetTimerData(600, "Tea"), SetTimerData.serializer())+ roundTrip(ContactData("Ada", "+1-555"), ContactData.serializer())+ roundTrip(FamilyMemberData("Bo", "Park", 1.5, 2.5), FamilyMemberData.serializer())+ roundTrip(NoteData("t", "c"), NoteData.serializer())+ roundTrip(InsertNoteData("t", "c"), InsertNoteData.serializer())+ roundTrip(MusicSearchResult(9, "Song", "track"), MusicSearchResult.serializer())+ roundTrip(PlayMusicData(9, "album"), PlayMusicData.serializer())+ roundTrip(EmailSearchQuery("invoice"), EmailSearchQuery.serializer())+ }++ @Test fun emailDtoNullables() {+ val full = EmailData("Subj", "[email protected]", "[email protected]", "2026-01-01", "Body", isRead = true)+ roundTrip(full, EmailData.serializer())+ val sparse = EmailData("Subj", "[email protected]", date = "2026-01-01", isRead = false)+ roundTrip(sparse, EmailData.serializer())+ assertNull(sparse.to); assertNull(sparse.body)+ }++ @Test fun directionsDtos() {+ val result = DirectionsResult(+ polyline = listOf(DirectionsLatLng(1.0, 2.0), DirectionsLatLng(3.0, 4.0)),+ segments = listOf(DirectionsSegment(listOf(DirectionsLatLng(1.0, 2.0)), 0.4)),+ distanceMeters = 1200.0, durationSeconds = 300.0,+ )+ roundTrip(result, DirectionsResult.serializer())+ roundTrip(DirectionsRequest(1.0, 2.0, 3.0, 4.0, "walk"), DirectionsRequest.serializer())+ roundTrip(DirectionsResult(emptyList(), emptyList(), 0.0, 0.0), DirectionsResult.serializer())+ }++ @Test fun todoDtosAndDefaults() {+ val todo = TodoData(id = "sync-1", title = "Call mom", dueAt = 123L, done = true, priority = 1, list = "family")+ roundTrip(todo, TodoData.serializer())+ val minimal = TodoData(id = "sync-2", title = "Plain")+ roundTrip(minimal, TodoData.serializer())+ assertEquals("", minimal.notes); assertNull(minimal.dueAt); assertEquals(0, minimal.priority)+ roundTrip(GetTodosQuery(), GetTodosQuery.serializer())+ assertEquals("today", GetTodosQuery().scope)+ roundTrip(InsertTodoData("New", dueAt = 5L, priority = 2), InsertTodoData.serializer())+ roundTrip(CompleteTodoData(id = "sync-1"), CompleteTodoData.serializer())+ roundTrip(CompleteTodoData(title = "By title"), CompleteTodoData.serializer())+ }++ @Test fun weatherDtoErrorAndSunTimes() {+ val ok = WeatherData(+ locationName = "Oslo", temperatureCelsius = 3.0, feelsLikeCelsius = 1.0,+ condition = "Snow", highCelsius = 5.0, lowCelsius = -2.0,+ precipitationChancePercent = 80, humidityPercent = 70, windKph = 20.0,+ windDirection = "NW", uvIndex = 1.0, sunriseEpochSec = 1000, sunsetEpochSec = 2000,+ )+ roundTrip(ok, WeatherData.serializer())+ assertNull(ok.error)+ val failed = WeatherData(+ locationName = null, temperatureCelsius = 0.0, feelsLikeCelsius = 0.0,+ condition = "", highCelsius = 0.0, lowCelsius = 0.0, precipitationChancePercent = 0,+ humidityPercent = 0, windKph = 0.0, windDirection = "", uvIndex = 0.0,+ error = "city not found",+ )+ roundTrip(failed, WeatherData.serializer())+ assertTrue(failed.error!!.contains("not found"))+ // toString is what the assistant caller feeds the LLM: it must carry the values.+ assertTrue(ok.toString().contains("Oslo"))+ }+}
library/src/test/java/com/vayunmathur/library/sensor/OrientationManagerTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/sensor/OrientationManagerTest.kt b/library/src/test/java/com/vayunmathur/library/sensor/OrientationManagerTest.ktnew file mode 100644index 0000000000..42eb37b0e3--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/sensor/OrientationManagerTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.library.sensor++import android.content.Context+import android.hardware.Sensor+import android.hardware.SensorManager+import androidx.test.core.app.ApplicationProvider+import kotlin.math.sin+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.SensorBuilder+import org.robolectric.shadows.SensorEventBuilder++/** OrientationManager fed real rotation-vector / accel+mag events via Robolectric shadows. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class OrientationManagerTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val sensorManager: SensorManager+ get() = ctx.getSystemService(Context.SENSOR_SERVICE) as SensorManager++ private fun addSensor(type: Int): Sensor {+ val sensor = SensorBuilder.newBuilder().setType(type).setName("test-$type").build()+ Shadows.shadowOf(sensorManager).addSensor(sensor)+ return sensor+ }++ private fun event(sensor: Sensor, vararg values: Float) =+ SensorEventBuilder.newBuilder(sensor, values).build()++ @Test fun rotationVectorIdentityEmitsFlatOrientation() {+ val rv = addSensor(Sensor.TYPE_ROTATION_VECTOR)+ val mgr = OrientationManager(ctx)+ mgr.updateLocation(0.0, 0.0) // equator/prime meridian: declination ~0+ mgr.start()+ assertTrue(Shadows.shadowOf(sensorManager).hasListener(mgr))++ mgr.onSensorChanged(event(rv, 0f, 0f, 0f, 1f))+ val o = mgr.orientation.value+ assertNotNull(o)+ // Robolectric's ShadowSensorManager synthesises the rotation matrix, so+ // assert the emitted frame is well-formed rather than its absolute frame.+ assertTrue(o.azimuthMagDeg in 0.0..360.0, "azimuth ${o.azimuthMagDeg}")+ assertTrue(o.azimuthTrueDeg in 0.0..360.0, "true azimuth ${o.azimuthTrueDeg}")+ assertTrue(o.pitchDeg in -180.0..180.0, "pitch ${o.pitchDeg}")+ assertTrue(o.rollDeg in -180.0..180.0, "roll ${o.rollDeg}")+ assertTrue(o.pointingAltDeg in -90.0..90.0, "pointing alt ${o.pointingAltDeg}")+ assertTrue(o.pointingAzTrueDeg in 0.0..360.0, "pointing az ${o.pointingAzTrueDeg}")+ assertEquals(SensorManager.SENSOR_STATUS_ACCURACY_HIGH, o.accuracy)++ mgr.onAccuracyChanged(rv, SensorManager.SENSOR_STATUS_ACCURACY_LOW)+ mgr.onSensorChanged(event(rv, 0f, 0f, 0f, 1f))+ assertEquals(SensorManager.SENSOR_STATUS_ACCURACY_LOW, mgr.orientation.value!!.accuracy)++ mgr.stop()+ assertTrue(!Shadows.shadowOf(sensorManager).hasListener(mgr))+ }++ @Test fun rotationAboutVerticalSmoothsHeadingTowardTarget() {+ val rv = addSensor(Sensor.TYPE_ROTATION_VECTOR)+ val mgr = OrientationManager(ctx)+ mgr.start()+ mgr.onSensorChanged(event(rv, 0f, 0f, 0f, 1f))+ val baseline = mgr.orientation.value!!.azimuthMagDeg++ // 90 degrees about Z as a rotation vector: axis * sin(theta/2).+ val half = sin(Math.toRadians(45.0)).toFloat()+ mgr.onSensorChanged(event(rv, 0f, 0f, half))+ val smoothed = mgr.orientation.value!!.azimuthMagDeg+ // Smoothing moves the heading from the baseline but does not jump to the target.+ val wrapped = ((smoothed - baseline) % 360.0 + 360.0) % 360.0+ val delta = minOf(wrapped, 360.0 - wrapped)+ assertTrue(delta > 0.5 && delta < 90.0, "heading $baseline -> $smoothed")+ mgr.stop()+ }++ @Test fun fallbackAccelMagPathEmitsAfterBothSensors() {+ val accel = addSensor(Sensor.TYPE_ACCELEROMETER)+ val mag = addSensor(Sensor.TYPE_MAGNETIC_FIELD)+ // No rotation-vector sensor: start() must use the fallback pair.+ val mgr = OrientationManager(ctx)+ mgr.start()+ mgr.onSensorChanged(event(accel, 0f, 0f, 9.81f))+ assertNull(mgr.orientation.value) // magnetometer not seen yet+ mgr.onSensorChanged(event(mag, 0f, 20f, -40f))+ val o = mgr.orientation.value+ assertNotNull(o)+ assertEquals(0.0, o.azimuthMagDeg, 5.0)+ // Second pair exercises the smoothing branch.+ mgr.onSensorChanged(event(accel, 0f, 9.81f, 0f))+ mgr.onSensorChanged(event(mag, 20f, 0f, -40f))+ assertNotNull(mgr.orientation.value)+ mgr.stop()+ }++ @Test fun displayRotationsRemapAndStillEmit() {+ val rv = addSensor(Sensor.TYPE_ROTATION_VECTOR)+ val display = (ctx.getSystemService(Context.WINDOW_SERVICE) as android.view.WindowManager).defaultDisplay+ val shadowDisplay = Shadows.shadowOf(display)+ for (rotation in intArrayOf(+ android.view.Surface.ROTATION_0, android.view.Surface.ROTATION_90,+ android.view.Surface.ROTATION_180, android.view.Surface.ROTATION_270, 99,+ )) {+ shadowDisplay.setRotation(rotation)+ val mgr = OrientationManager(ctx)+ mgr.start()+ mgr.onSensorChanged(event(rv, 0f, 0f, 0f, 1f))+ assertNotNull(mgr.orientation.value, "no orientation for display rotation $rotation")+ mgr.stop()+ }+ }++ @Test fun noSensorsAndIrrelevantEventsAreSafe() {+ val mgr = OrientationManager(ctx)+ mgr.start() // nothing registered by Robolectric+ val light = SensorBuilder.newBuilder().setType(Sensor.TYPE_LIGHT).setName("light").build()+ mgr.onSensorChanged(event(light, 42f))+ assertNull(mgr.orientation.value)+ mgr.stop()+ mgr.updateLocation(51.5, -0.12, 0f)+ }+}
library/src/test/java/com/vayunmathur/library/util/DatabaseHelperCryptoTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/DatabaseHelperCryptoTest.kt b/library/src/test/java/com/vayunmathur/library/util/DatabaseHelperCryptoTest.ktnew file mode 100644index 0000000000..e4259f12c4--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/DatabaseHelperCryptoTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.library.util++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** DatabaseHelper AndroidKeyStore passphrase lifecycle. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class DatabaseHelperCryptoTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ companion object {+ @org.junit.BeforeClass @JvmStatic fun installKeyStore() = FakeAndroidKeyStore.install()+ }++ @Test fun passphraseRoundTripsThroughKeystore() {+ val helper = DatabaseHelper(ctx)+ helper.deleteKey()+ assertFalse(helper.isKeyGenerated())+ helper.storePassphrase("correct horse battery staple")+ assertTrue(helper.isKeyGenerated())+ assertEquals("correct horse battery staple", helper.getPassphrase())+ // Overwriting stores the new passphrase under a fresh IV.+ helper.storePassphrase("second secret")+ assertEquals("second secret", helper.getPassphrase())+ helper.deleteKey()+ assertFalse(helper.isKeyGenerated())+ }++ private class CustomHelper(context: Context) : DatabaseHelper(context) {+ override val keyStoreAlias = "custom_alias"+ override val sharedPrefsName = "custom_prefs"+ override val passphraseKey = "custom_pass"+ override val ivKey = "custom_iv"+ }++ @Test fun orphanKeyWithoutIvIsCleanedUp() {+ val helper = DatabaseHelper(ctx)+ helper.deleteKey()+ helper.generateKey() // key only: no IV/passphrase persisted yet+ // isKeyGenerated treats a key with no IV as corruption and deletes it.+ assertFalse(helper.isKeyGenerated())+ assertFalse(helper.isKeyGenerated())+ }++ @Test fun customAliasAndPrefsAreIndependent() {+ val custom = CustomHelper(ctx)+ val standard = DatabaseHelper(ctx)+ custom.deleteKey(); standard.deleteKey()+ custom.storePassphrase("custom secret")+ assertEquals("custom secret", custom.getPassphrase())+ // The default helper reads different prefs, so it has no IV to decrypt with.+ try {+ standard.getPassphrase()+ throw AssertionError("expected default helper to have no passphrase")+ } catch (expected: IllegalStateException) {+ assertTrue(expected.message!!.contains("not found"))+ }+ custom.deleteKey(); standard.deleteKey()+ }++ @Test fun createAndStorePassphraseGeneratesDecryptableSecret() {+ val helper = DatabaseHelper(ctx)+ helper.deleteKey()+ helper.generateKey()+ val generated = helper.createAndStorePassphrase(helper.getCipherForEncryption())+ assertTrue(generated.isNotBlank())+ assertEquals(generated, helper.decryptPassphrase(helper.getCipherForDecryption()))+ helper.deleteKey()+ assertFalse(helper.isKeyGenerated())+ }+}
library/src/test/java/com/vayunmathur/library/util/FakeAndroidKeyStore.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/FakeAndroidKeyStore.kt b/library/src/test/java/com/vayunmathur/library/util/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..8cd005b023--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/FakeAndroidKeyStore.kt@@ -0,0 +1,93 @@+package com.vayunmathur.library.util++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * In-memory stand-in for the AndroidKeyStore JCE provider, which Robolectric+ * does not ship. Lets [DatabaseHelper] generate/store its passphrase key on+ * the JVM (same pattern as uniflix's test fake).+ */+object FakeAndroidKeyStore {+ private val keys = Collections.synchronizedMap(HashMap<String, Key>())++ fun install() {+ if (Security.getProvider("AndroidKeyStore") == null) {+ Security.addProvider(FakeProvider())+ }+ }++ internal fun put(alias: String, key: Key) {+ keys[alias] = key+ }++ internal fun get(alias: String): Key? = keys[alias]+ internal fun remove(alias: String) {+ keys.remove(alias)+ }++ internal fun contains(alias: String): Boolean = keys.containsKey(alias)+ internal fun aliases(): List<String> = synchronized(keys) { keys.keys.toList() }+}++class FakeProvider : Provider("AndroidKeyStore", 1.0, "fake for tests") {+ init {+ put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+ put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+ }+}++class FakeKeyStoreSpi : KeyStoreSpi() {+ override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+ override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+ override fun engineGetKey(alias: String, password: CharArray?): Key? = FakeAndroidKeyStore.get(alias)+ override fun engineContainsAlias(alias: String): Boolean = FakeAndroidKeyStore.contains(alias)+ override fun engineDeleteEntry(alias: String) = FakeAndroidKeyStore.remove(alias)+ override fun engineAliases(): Enumeration<String> =+ Collections.enumeration(FakeAndroidKeyStore.aliases())+ override fun engineSize(): Int = FakeAndroidKeyStore.aliases().size+ override fun engineIsKeyEntry(alias: String): Boolean = FakeAndroidKeyStore.contains(alias)+ override fun engineIsCertificateEntry(alias: String): Boolean = false+ override fun engineGetCertificate(alias: String): Certificate? = null+ override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+ override fun engineGetCertificateAlias(cert: Certificate): String? = null+ override fun engineGetCreationDate(alias: String): Date = Date(0)+ override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+ FakeAndroidKeyStore.put(alias, key)+ }+ override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) {+ FakeAndroidKeyStore.put(alias, SecretKeySpec(key, "AES"))+ }+ override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+}++class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+ private var alias: String = "db_no_auth_key"++ override fun engineInit(random: SecureRandom?) = Unit+ override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom?) {+ if (params is KeyGenParameterSpec) alias = params.keystoreAlias+ }+ override fun engineInit(keysize: Int, random: SecureRandom?) = Unit++ override fun engineGenerateKey(): SecretKey {+ val bytes = ByteArray(32)+ SecureRandom().nextBytes(bytes)+ val key = SecretKeySpec(bytes, "AES")+ FakeAndroidKeyStore.put(alias, key)+ return key+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryAndroid2Test.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryAndroid2Test.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryAndroid2Test.ktnew file mode 100644index 0000000000..74308e3ad1--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryAndroid2Test.kt@@ -0,0 +1,295 @@+package com.vayunmathur.library.util++import android.app.NotificationManager+import android.content.Context+import android.content.ContextWrapper+import android.content.Intent+import android.net.Uri+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.intents.euicc.EsimLink+import com.vayunmathur.library.sensor.DeviceOrientation+import com.vayunmathur.library.sensor.OrientationManager+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import java.util.Locale+import kotlin.math.PI+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Notifications, IntentHelper, DataStore companion/flows, orientation state, intents IPC. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LibraryAndroid2Test {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun notificationChannelCreateUpdateDelete() {+ ctx.ensureNotificationChannel("chan1", "First Name", NotificationManager.IMPORTANCE_HIGH, "desc1")+ val nm = ctx.getSystemService(NotificationManager::class.java)+ val created = nm.getNotificationChannel("chan1")+ assertNotNull(created)+ assertEquals("First Name", created.name.toString())+ assertEquals(NotificationManager.IMPORTANCE_HIGH, created.importance)+ // Re-creating with a new name refreshes it (the bug the helper exists to fix).+ ctx.ensureNotificationChannel("chan1", "Renamed", NotificationManager.IMPORTANCE_HIGH, "desc2")+ assertEquals("Renamed", nm.getNotificationChannel("chan1").name.toString())+ ctx.deleteNotificationChannel("chan1")+ assertNull(nm.getNotificationChannel("chan1"))+ ctx.deleteNotificationChannel("never-existed") // no-op, must not throw+ }++ @Test fun maNotificationsPostAndBroadcast() {+ val id = MaNotifications.post(+ ctx, "ma-chan", "MA Channel", notificationId = 77,+ launchIntent = Intent(ctx, ComponentActivity::class.java),+ ) { builder ->+ builder.setSmallIcon(android.R.drawable.ic_dialog_info)+ .setContentTitle("HelloTitle").setContentText("body")+ }+ assertEquals(77, id)+ val shadow = Shadows.shadowOf(ctx.getSystemService(NotificationManager::class.java))+ assertEquals(1, shadow.allNotifications.size)+ assertEquals("HelloTitle", shadow.allNotifications[0].extras.getString("android.title"))++ val bad = MaNotifications.post(ctx, "ma-chan", "MA Channel", notificationId = 78) {+ throw IllegalStateException("builder boom")+ }+ assertNull(bad)++ val pending = MaNotifications.broadcastIntent(ctx, Intent("com.example.PING"), 5)+ assertNotNull(pending)+ }++ @Test fun liveUpdateSupportOnSdk34() {+ assertEquals(36, LiveUpdateSupport.LIVE_UPDATE_SDK)+ assertFalse(LiveUpdateSupport.isStyleSupported())+ assertFalse(LiveUpdateSupport.isPromotedOngoingSupported())+ assertFalse(LiveUpdateSupport.canPostPromoted(ctx))+ }++ @Test fun intentHelperExtractsUrisPerAction() {+ val view = Intent(Intent.ACTION_VIEW).apply { data = Uri.parse("file:///docs/a.pdf") }+ assertEquals(listOf(Uri.parse("file:///docs/a.pdf")), IntentHelper.getUrisFromIntent(view))++ val single = Uri.parse("content://media/1")+ val send = Intent(Intent.ACTION_SEND).apply { putExtra(Intent.EXTRA_STREAM, single) }+ assertEquals(listOf(single), IntentHelper.getUrisFromIntent(send))++ val many = arrayListOf(Uri.parse("content://media/2"), Uri.parse("content://media/3"))+ val multi = Intent(Intent.ACTION_SEND_MULTIPLE).apply {+ putParcelableArrayListExtra(Intent.EXTRA_STREAM, many)+ }+ assertEquals(many, IntentHelper.getUrisFromIntent(multi))++ assertEquals(emptyList(), IntentHelper.getUrisFromIntent(Intent(Intent.ACTION_VIEW)))+ assertEquals(emptyList(), IntentHelper.getUrisFromIntent(Intent("com.example.OTHER")))+ }++ @Test fun intentHelperFileNameFromPathAndContentFallback() {+ assertEquals("report.pdf", IntentHelper.getFileName(ctx, Uri.parse("file:///storage/docs/report.pdf")))+ assertEquals("report.pdf", IntentHelper.getFileName(ctx, Uri.parse("/storage/docs/report.pdf")))+ // content:// with no provider registered resolves through the path fallback.+ assertEquals("42", IntentHelper.getFileName(ctx, Uri.parse("content://com.example.provider/items/42")))+ }++ @Test fun dataStoreSyncGettersFlowsAndSetOps() = runBlocking {+ val store = DataStoreUtils.getInstance(ctx)+ val suffix = System.nanoTime().toString()+ store.setDouble("dbl$suffix", 3.25)+ assertEquals(3.25, store.doubleFlow("dbl$suffix").first())+ assertEquals(3.25, store.getDouble("dbl$suffix") ?: store.doubleFlow("dbl$suffix").first())+ store.setLong("lng$suffix", 10, onlyIfAbsent = true)+ store.setLong("lng$suffix", 20, onlyIfAbsent = true)+ assertEquals(10L, store.getLongAwait("lng$suffix"))+ assertEquals(10L, store.longFlow("lng$suffix").first())+ assertEquals(99L, store.longFlow("missing$suffix", 99L).first())+ assertEquals(true, store.booleanFlow("missingb$suffix", true).first())++ store.addStringToSet("set$suffix", "one")+ withTimeout(5000) { while (!store.getStringSetAwait("set$suffix").contains("one")) delay(20) }+ store.removeStringFromSet("set$suffix", "one")+ withTimeout(5000) { while (store.getStringSetAwait("set$suffix").isNotEmpty()) delay(20) }++ // copyFrom: empty keys and empty source are no-ops.+ assertEquals(0, store.copyFrom(store, emptyList(), overwrite = false))+ // getInstance is a singleton per storage mode.+ assertTrue(store === DataStoreUtils.getInstance(ctx))+ val dps = DataStoreUtils.getInstance(ctx, deviceProtected = true)+ assertTrue(dps === DataStoreUtils.getInstance(ctx, deviceProtected = true))+ assertFalse(store === dps)+ assertEquals(0, DataStoreUtils.seedDeviceProtectedStorage(ctx, listOf("no-such-key-$suffix")))+ store.setString("seed$suffix", "seeded")+ assertEquals(1, DataStoreUtils.seedDeviceProtectedStorage(ctx, listOf("seed$suffix")))+ assertEquals("seeded", dps.getStringAwait("seed$suffix"))+ }++ @Test fun deviceOrientationRadiansAndDefaults() {+ val o = DeviceOrientation(+ azimuthTrueDeg = 90.0, azimuthMagDeg = 80.0, pitchDeg = 10.0, rollDeg = -5.0,+ pointingAzTrueDeg = 180.0, pointingAltDeg = 45.0, viewRotationDeg = 30.0,+ )+ assertEquals(PI, o.pointingAzRad, 1e-9)+ assertEquals(PI / 4, o.pointingAltRad, 1e-9)+ assertEquals(PI / 6, o.viewRotationRad, 1e-9)+ val d = DeviceOrientation(azimuthTrueDeg = 12.0, azimuthMagDeg = 12.0, pitchDeg = 0.0, rollDeg = 0.0)+ assertEquals(12.0, d.pointingAzTrueDeg) // pointing defaults to azimuth+ assertEquals(0.0, d.pointingAltDeg)+ }++ @Test fun orientationManagerLifecycleAndLocation() {+ val mgr = OrientationManager(ctx)+ assertNull(mgr.orientation.value)+ mgr.updateLocation(37.7749, -122.4194, 10f)+ mgr.start()+ mgr.start() // idempotent while running+ mgr.onAccuracyChanged(null, android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW)+ mgr.stop()+ mgr.stop() // idempotent while stopped+ mgr.start()+ mgr.stop()+ assertNull(mgr.orientation.value) // no sensor events delivered by Robolectric+ }++ @Test fun findActivityWalksWrapperChain() {+ val activity = Robolectric.buildActivity(ComponentActivity::class.java).create().get()+ val wrapped = ContextWrapper(ContextWrapper(activity))+ assertEquals(activity, wrapped.findActivity<ComponentActivity>())+ assertNull(ctx.findActivity<ComponentActivity>())+ }++ @Test fun esimLinkBuildsProvisioningUri() {+ assertEquals("https", EsimLink.SCHEME)+ assertEquals("esimsetup.android.com", EsimLink.HOST)+ assertEquals("com.vayunmathur.euicc", EsimLink.LPA_PACKAGE)+ val uri = EsimLink.provisioningUri("LPA:1\$example.com\$CODE-1")+ assertEquals("esimsetup.android.com", uri.host)+ assertEquals("/esim_qrcode_provisioning", uri.path)+ assertEquals("LPA:1\$example.com\$CODE-1", uri.getQueryParameter("carddata"))+ }++ @Test fun formatAndLocaleExtras() {+ assertEquals("3", 3.14159.toStringDigits(0))+ assertEquals("-1,234", (-1234L).toStringCommas())+ assertEquals("0.500", 0.5.toStringDigits(3))+ assertTrue(0f.formatSpeed(Locale.US).isNotBlank())+ assertEquals("Jan", localizedMonthNames(DateNameStyle.SHORT, Locale.US)[0])+ assertEquals(12, localizedMonthNames(DateNameStyle.NARROW, Locale.US).size)+ assertEquals("Mon", localizedDayOfWeekNames(DateNameStyle.SHORT, Locale.US)[0])+ assertEquals(7, localizedDayOfWeekNames(DateNameStyle.NARROW, Locale.US).size)+ val markers = localizedAmPmMarkers(Locale.JAPAN)+ assertTrue(markers.first.isNotBlank() && markers.second.isNotBlank())+ assertEquals(listOf(1, 2, 3, 4, 5, 6, 7), localeWeekDayNumbers(Locale.GERMANY))+ }++ @Test fun localizedAmPmMarkerInTimeFormat() {+ val format = kotlinx.datetime.LocalTime.Format {+ localizedAmPmMarker(Locale.US)+ }+ val rendered = format.format(kotlinx.datetime.LocalTime(13, 5))+ assertTrue(rendered.contains("PM"), rendered)+ val lower = kotlinx.datetime.LocalTime.Format {+ localizedAmPmMarker(Locale.US, lowercase = true)+ }+ assertTrue(lower.format(kotlinx.datetime.LocalTime(13, 5)).contains("pm"))+ }++ class CalcIntent : AssistantIntent<com.vayunmathur.library.intents.notes.NoteData, com.vayunmathur.library.intents.notes.NoteData>(+ com.vayunmathur.library.intents.notes.NoteData.serializer(),+ com.vayunmathur.library.intents.notes.NoteData.serializer(),+ ) {+ override suspend fun performCalculation(+ input: com.vayunmathur.library.intents.notes.NoteData,+ ) = input.copy(title = input.title.uppercase())+ }++ class FailingIntent : AssistantIntent<com.vayunmathur.library.intents.notes.NoteData, com.vayunmathur.library.intents.notes.NoteData>(+ com.vayunmathur.library.intents.notes.NoteData.serializer(),+ com.vayunmathur.library.intents.notes.NoteData.serializer(),+ ) {+ override suspend fun performCalculation(+ input: com.vayunmathur.library.intents.notes.NoteData,+ ): com.vayunmathur.library.intents.notes.NoteData = throw RuntimeException("calc boom")+ }++ private fun intentWith(data: String?, results: MutableList<Pair<Int, Bundle?>>): Intent {+ val receiver = SecureResultReceiver(android.os.Handler(android.os.Looper.getMainLooper())) { code, bundle ->+ results += code to bundle+ }+ return Intent(Intent.ACTION_MAIN).apply {+ if (data != null) putExtra("DATA", data)+ putExtra("RECEIVER", receiver)+ }+ }++ @Test fun assistantIntentDecodesCalculatesAndReplies() = runBlocking {+ val results = mutableListOf<Pair<Int, Bundle?>>()+ val json = """{"title":"hello","content":"body"}"""+ Robolectric.buildActivity(CalcIntent::class.java, intentWith(json, results)).create()+ withTimeout(8000) { while (results.isEmpty()) delay(20) }+ assertEquals(android.app.Activity.RESULT_OK, results[0].first)+ val response = results[0].second!!.getString("RESPONSE_DATA")!!+ assertTrue(response.contains("HELLO"), response)+ }++ @Test fun intentLauncherBuildsIntentAndStaysPendingWithoutResponse() = runBlocking {+ val activity = Robolectric.buildActivity(ComponentActivity::class.java).create().get()+ val launcher = IntentLauncher(activity)+ // Robolectric's parcel shadow drops the ResultReceiver binder, so the+ // simulated target can never answer; assert the launch side instead:+ // the intent is built for the right component with the JSON payload,+ // and the call stays bounded-pending until cancelled.+ val deferred = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default).async {+ launcher.launch(+ ctx, "com.example.target", "com.example.target.AnswerIntent",+ com.vayunmathur.library.intents.notes.NoteData.serializer(),+ com.vayunmathur.library.intents.notes.NoteData("payload-title", "c"),+ )+ }+ var started: Intent? = null+ withTimeout(10_000) {+ while (started == null) {+ Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ started = Shadows.shadowOf(activity).nextStartedActivity+ if (started == null) delay(20)+ }+ }+ assertEquals("com.example.target", started!!.component?.packageName)+ assertEquals("com.example.target.AnswerIntent", started!!.component?.className)+ assertTrue(started!!.getStringExtra("DATA")!!.contains("payload-title"))+ assertNotNull(started!!.getParcelableExtra<android.os.ResultReceiver>("RECEIVER"))+ assertFalse(deferred.isCompleted)+ deferred.cancel()+ }++ @Test fun assistantIntentMissingAndBadInputCancel() = runBlocking {+ val missing = mutableListOf<Pair<Int, Bundle?>>()+ Robolectric.buildActivity(CalcIntent::class.java, intentWith(null, missing)).create()+ withTimeout(8000) { while (missing.isEmpty()) delay(20) }+ assertEquals(android.app.Activity.RESULT_CANCELED, missing[0].first)++ val bad = mutableListOf<Pair<Int, Bundle?>>()+ Robolectric.buildActivity(CalcIntent::class.java, intentWith("{not json", bad)).create()+ withTimeout(8000) { while (bad.isEmpty()) delay(20) }+ assertEquals(android.app.Activity.RESULT_CANCELED, bad[0].first)++ val failing = mutableListOf<Pair<Int, Bundle?>>()+ Robolectric.buildActivity(FailingIntent::class.java, intentWith("""{"title":"x","content":"y"}""", failing)).create()+ withTimeout(8000) { while (failing.isEmpty()) delay(20) }+ assertEquals(android.app.Activity.RESULT_CANCELED, failing[0].first)+ }++}
library/src/test/java/com/vayunmathur/library/util/LibraryBackupAgentTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryBackupAgentTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupAgentTest.ktnew file mode 100644index 0000000000..42b6639197--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupAgentTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.library.util++import android.content.Context+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.BackupDataEntity+import org.robolectric.shadows.BackupDataInputBuilder+import org.robolectric.shadows.BackupDataOutputFactory++/**+ * BaseBackupAgent onBackup/onRestore round-trip through Robolectric's backup+ * data streams (the platform FD streams are shadow no-ops, so entities are+ * carried through the shadow factories the way the backup manager does).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LibraryBackupAgentTest {++ class TestAgent : BaseBackupAgent() {+ override val extraFiles: List<File> get() = listOf(extraFile)+ fun attach(ctx: Context) = attachBaseContext(ctx)+ companion object { lateinit var extraFile: File }+ }++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun agent(): TestAgent = TestAgent().apply { attach(ctx) }++ private fun pfd(file: File): ParcelFileDescriptor {+ if (!file.exists()) file.writeBytes(ByteArray(0))+ return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE)+ }++ @Test fun backupThenRestoreRoundTripsExtraFile() {+ val agent = agent()+ val extra = File(ctx.cacheDir, "agent-extra.txt").apply { writeText("agent-body") }+ TestAgent.extraFile = extra++ val newStateFile = File(ctx.cacheDir, "backup-state.bin").apply { delete() }+ val output = BackupDataOutputFactory.newInstance()+ agent.onBackup(null, output, pfd(newStateFile))++ val entities = Shadows.shadowOf(output).entities+ assertEquals(1, entities.size)+ val entity = entities.single()+ assertEquals("full_backup", entity.key())+ assertTrue(entity.dataSize() > 0, "zip entity written")+ // The entity payload is the backup zip (local file header signature).+ assertEquals('P'.code.toByte(), entity.data()[0])+ assertEquals('K'.code.toByte(), entity.data()[1])+ assertEquals(8, newStateFile.length(), "state timestamp written")++ extra.delete()+ assertTrue(!extra.exists())+ val restoreState = File(ctx.cacheDir, "restore-state.bin").apply { delete() }+ val input = BackupDataInputBuilder.newBuilder()+ .addEntity(BackupDataEntity.create("unrelated_key", "junk"))+ .addEntity(entity)+ .build()+ agent.onRestore(input, 1, pfd(restoreState))+ assertEquals("agent-body", extra.readText())+ assertEquals(8, restoreState.length())+ }++ @Test fun secondBackupWithPriorStateStillWritesState() {+ val agent = agent()+ val extra = File(ctx.cacheDir, "agent-extra2.txt").apply { writeText("v1") }+ TestAgent.extraFile = extra+ val state1 = File(ctx.cacheDir, "state-a.bin").apply { delete() }+ val first = BackupDataOutputFactory.newInstance()+ agent.onBackup(null, first, pfd(state1))+ assertEquals(1, Shadows.shadowOf(first).entities.size)+ assertEquals(8, state1.length())++ // Re-running with the prior state as oldState exercises the state-read+ // path (rewrite-or-copy, either way a state file must come out).+ val state2 = File(ctx.cacheDir, "state-b.bin").apply { delete() }+ val second = BackupDataOutputFactory.newInstance()+ agent.onBackup(pfd(state1), second, pfd(state2))+ assertEquals(8, state2.length())+ }++ @Test fun restoreWithOnlyUnrelatedEntitiesChangesNothing() {+ val agent = agent()+ val extra = File(ctx.cacheDir, "agent-extra3.txt").apply { writeText("keep") }+ TestAgent.extraFile = extra+ val restoreState = File(ctx.cacheDir, "restore-state3.bin").apply { delete() }+ val input = BackupDataInputBuilder.newBuilder()+ .addEntity(BackupDataEntity.create("something_else", "junk"))+ .build()+ agent.onRestore(input, 1, pfd(restoreState))+ assertEquals("keep", extra.readText())+ // No full_backup entity seen, so no new state is written.+ assertEquals(0, restoreState.length())+ }++ @Test fun backupWithFutureStateCopiesStateUnchanged() {+ val agent = agent()+ val extra = File(ctx.cacheDir, "agent-extra4.txt").apply { writeText("v") }+ TestAgent.extraFile = extra+ // Old state claims a far-future backup time, so nothing is newer: the+ // agent must copy the old state forward instead of writing an entity.+ val oldState = File(ctx.cacheDir, "state-old.bin")+ oldState.writeBytes(java.nio.ByteBuffer.allocate(8).putLong(Long.MAX_VALUE).array())+ val newState = File(ctx.cacheDir, "state-new.bin").apply { delete() }+ val output = BackupDataOutputFactory.newInstance()+ agent.onBackup(pfd(oldState), output, pfd(newState))+ assertTrue(Shadows.shadowOf(output).entities.isEmpty())+ assertEquals(8, newState.length())+ assertEquals(+ Long.MAX_VALUE,+ java.nio.ByteBuffer.wrap(newState.readBytes()).long,+ )+ }++ @Test fun databaseHelperPassphraseLifecycleWithoutKey() {+ val helper = DatabaseHelper(ctx)+ // No passphrase has been stored in this helper's prefs.+ helper.deleteKey() // must not throw even with nothing stored+ try {+ helper.getPassphrase()+ throw AssertionError("expected passphrase lookup to fail with no key")+ } catch (expected: Exception) {+ // IllegalStateException (no IV/passphrase) or a keystore failure on this platform.+ assertTrue(+ expected is IllegalStateException ||+ expected is java.security.KeyStoreException ||+ expected.cause is IllegalStateException,+ "$expected",+ )+ }+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.ktnew file mode 100644index 0000000000..e419d5a054--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.kt@@ -0,0 +1,187 @@+package com.vayunmathur.library.util++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** BackupHelper zip staging, ZipBackupFormat delegation and a fake DbBackupCodec. */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](sdk = [34])+class LibraryBackupTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun createTempDir(name: String): File =+ java.nio.file.Files.createTempDirectory(name).toFile()++ private class FakeCodec(private val payload: String) : DbBackupCodec {+ val exported = mutableListOf<String>()+ val imported = mutableListOf<String>()+ override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+ exported += "$dbName:$password"+ outputFile.writeText(payload)+ }+ override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+ imported += "$dbName:$password:" + inputFile.readText()+ }+ }++ @Test fun zipUnzipRoundTripsNestedFiles() {+ val base = createTempDir("zipbase")+ File(base, "a.txt").writeText("alpha")+ File(base, "sub").mkdirs()+ File(base, "sub/b.txt").writeText("beta")+ val out = ByteArrayOutputStream()+ BackupHelper.zipFiles(listOf(base), base, out)+ val target = createTempDir("zipout")+ BackupHelper.unzipFiles(ByteArrayInputStream(out.toByteArray()), target)+ assertEquals("alpha", File(target, "a.txt").readText())+ assertEquals("beta", File(target, "sub/b.txt").readText())+ }++ @Test fun zipEmptyListProducesValidEmptyZip() {+ val out = ByteArrayOutputStream()+ BackupHelper.zipFiles(emptyList(), createTempDir("emptybase"), out)+ val target = createTempDir("emptyout")+ BackupHelper.unzipFiles(ByteArrayInputStream(out.toByteArray()), target)+ assertTrue(target.listFiles()?.isEmpty() != false)+ }++ @Test fun fullBackupAndRestoreExtraFilesAndPrefsAndDatastore() {+ val extra = File(ctx.cacheDir, "extra-note.txt").apply { writeText("extra-body") }+ val dsDir = File(ctx.filesDir, "datastore").apply { mkdirs() }+ File(dsDir, "mystore.preferences_pb").writeBytes(byteArrayOf(1, 2, 3))+ val prefDir = File(ctx.dataDir, "shared_prefs").apply { mkdirs() }+ File(prefDir, "myprefs.xml").writeText("<map/>")++ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(+ ctx,+ dbConfigs = emptyList(),+ datastoreNames = listOf("mystore"),+ prefNames = listOf("myprefs"),+ extraFiles = listOf(extra, File(ctx.cacheDir, "missing.bin")),+ outputStream = out,+ )+ assertTrue(out.size() > 0)++ // Wipe the originals, then restore into place.+ extra.delete(); File(dsDir, "mystore.preferences_pb").delete(); File(prefDir, "myprefs.xml").delete()+ BackupHelper.performFullRestore(+ ctx,+ dbConfigs = emptyList(),+ datastoreNames = listOf("mystore"),+ prefNames = listOf("myprefs"),+ extraFilesMapping = mapOf("extra-note.txt" to extra),+ inputStream = ByteArrayInputStream(out.toByteArray()),+ )+ assertEquals("extra-body", extra.readText())+ assertTrue(byteArrayOf(1, 2, 3).contentEquals(File(dsDir, "mystore.preferences_pb").readBytes()))+ assertEquals("<map/>", File(prefDir, "myprefs.xml").readText())+ }++ @Test fun fullBackupWithCodecExportsDatabaseAndRestoreImportsIt() {+ val codec = FakeCodec("db-bytes")+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, listOf("notes" to "pw1"), emptyList(), emptyList(), emptyList(), out, codec)+ assertEquals(listOf("notes:pw1"), codec.exported)+ BackupHelper.performFullRestore(+ ctx, listOf("notes" to "pw1"), emptyList(), emptyList(), emptyMap(),+ ByteArrayInputStream(out.toByteArray()), codec,+ )+ assertEquals(listOf("notes:pw1:db-bytes"), codec.imported)+ }++ @Test fun backupWithoutCodecSkipsDatabasesButStillZipsExtras() {+ val extra = File(ctx.cacheDir, "only.txt").apply { writeText("x") }+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, listOf("db" to "pw"), emptyList(), emptyList(), listOf(extra), out, null)+ val target = createTempDir("nocodec")+ BackupHelper.unzipFiles(ByteArrayInputStream(out.toByteArray()), target)+ assertEquals("x", File(target, "only.txt").readText())+ }++ @Test fun restoreWithMissingEntriesIsNoOp() {+ val out = ByteArrayOutputStream()+ BackupHelper.zipFiles(emptyList(), createTempDir("b"), out)+ // Nothing in the zip matches the requested names: must not throw or create files.+ BackupHelper.performFullRestore(+ ctx, listOf("nope" to "pw"), listOf("ghost"), listOf("ghost"),+ mapOf("ghost.txt" to File(ctx.cacheDir, "ghost.txt")),+ ByteArrayInputStream(out.toByteArray()), FakeCodec("z"),+ )+ assertFalse(File(ctx.cacheDir, "ghost.txt").exists())+ }++ @Test fun defaultDatastoreRestoresToFilesRoot() {+ val src = File(ctx.filesDir, "datastore_default.preferences_pb").apply { writeBytes(byteArrayOf(9)) }+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), listOf("datastore_default"), emptyList(), emptyList(), out)+ src.delete()+ BackupHelper.performFullRestore(+ ctx, emptyList(), listOf("datastore_default"), emptyList(), emptyMap(),+ ByteArrayInputStream(out.toByteArray()),+ )+ assertTrue(src.exists())+ assertTrue(byteArrayOf(9).contentEquals(src.readBytes()))+ }++ @Test fun extraDirectoryIsCopiedRecursively() {+ val dir = File(ctx.cacheDir, "extradir").apply { mkdirs() }+ File(dir, "inner.txt").writeText("inner")+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), emptyList(), emptyList(), listOf(dir), out)+ val restored = File(ctx.cacheDir, "restoreddir")+ restored.deleteRecursively()+ BackupHelper.performFullRestore(+ ctx, emptyList(), emptyList(), emptyList(),+ mapOf("extradir" to restored), ByteArrayInputStream(out.toByteArray()),+ )+ assertEquals("inner", File(restored, "inner.txt").readText())+ }++ @Test fun zipFormatWithCodecAndNamedStoresDelegates() = runBlocking {+ val codec = FakeCodec("fmt-db")+ val format = ZipBackupFormat(+ dbConfigs = listOf("main" to "pw"),+ datastoreNames = listOf("mystore"),+ prefNames = listOf("myprefs"),+ dbCodec = codec,+ )+ val dsDir = File(ctx.filesDir, "datastore").apply { mkdirs() }+ File(dsDir, "mystore.preferences_pb").writeBytes(byteArrayOf(7))+ val prefDir = File(ctx.dataDir, "shared_prefs").apply { mkdirs() }+ File(prefDir, "myprefs.xml").writeText("<map><int name=\"a\" value=\"1\"/></map>")+ val out = ByteArrayOutputStream()+ format.export(ctx, null, out)+ assertEquals(listOf("main:pw"), codec.exported)+ File(dsDir, "mystore.preferences_pb").delete()+ File(prefDir, "myprefs.xml").delete()+ format.import(ctx, null, ByteArrayInputStream(out.toByteArray()))+ assertEquals(listOf("main:pw:fmt-db"), codec.imported)+ assertTrue(File(dsDir, "mystore.preferences_pb").exists())+ assertTrue(File(prefDir, "myprefs.xml").readText().contains("value=\"1\""))+ }++ @Test fun zipFormatMetadataAndDelegation() = runBlocking {+ val format = ZipBackupFormat(extraFiles = emptyList())+ assertEquals("application/zip", format.mimeType)+ assertEquals("backup.zip", format.defaultFileName)+ assertFalse(format.needsPassword)+ val extra = File(ctx.cacheDir, "fmt.txt").apply { writeText("fmt-body") }+ val withExtra = ZipBackupFormat(extraFiles = listOf(extra))+ val out = ByteArrayOutputStream()+ withExtra.export(ctx, null, out)+ assertTrue(out.size() > 0)+ extra.delete()+ withExtra.import(ctx, "ignored", ByteArrayInputStream(out.toByteArray()))+ assertEquals("fmt-body", extra.readText())+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryCompose2Test.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryCompose2Test.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryCompose2Test.ktnew file mode 100644index 0000000000..0348ac7023--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryCompose2Test.kt@@ -0,0 +1,151 @@+package com.vayunmathur.library.util++import androidx.compose.foundation.layout.Column+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import kotlinx.serialization.Serializable+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++/** MainNavigation transition specs per motion, dialog entries, morphs, message drain. */+@RunWith(RobolectricTestRunner::class)+class LibraryCompose2Test {++ @get:Rule val rule = createComposeRule()++ @Serializable data class Screen(val route: String) : NavKey++ private fun motionFor(route: String): Map<String, Any> = when (route) {+ "zoom" -> ZoomPage()+ "full" -> FullscreenPage()+ "sibling" -> SiblingPage()+ "morph" -> MorphPage()+ "dialog" -> DialogPage()+ else -> DetailPage()+ }++ @Test fun navigationPushPopAcrossAllMotions() {+ val stack = NavBackStack(arrayOf(Screen("home")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen>(metadata = motionFor(obj.route)) { screen ->+ if (screen.route == "morph") {+ Text("MorphTarget", Modifier.sharedContainer("shared-1"))+ } else {+ Text("Page ${screen.route}")+ }+ }+ }+ }+ }+ rule.onNodeWithText("Page home").assertIsDisplayed()+ for (route in listOf("zoom", "full", "sibling", "morph")) {+ rule.runOnIdle { stack.add(Screen(route)) }+ rule.waitForIdle()+ if (route == "morph") {+ rule.onNodeWithText("MorphTarget").assertExists()+ } else {+ rule.onNodeWithText("Page $route").assertExists()+ }+ rule.runOnIdle { stack.pop() }+ rule.waitForIdle()+ rule.onNodeWithText("Page home").assertIsDisplayed()+ }+ assertEquals(1, stack.backStack.size)+ }++ @Test fun dialogEntryShowsAsDialog() {+ val stack = NavBackStack(arrayOf(Screen("home")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen>(metadata = motionFor(obj.route)) { screen ->+ Text("Page ${screen.route}")+ }+ }+ }+ }+ rule.runOnIdle { stack.add(Screen("dialog")) }+ rule.waitForIdle()+ rule.onNodeWithText("Page dialog").assertExists()+ rule.runOnIdle { stack.pop() }+ rule.waitForIdle()+ rule.onNodeWithText("Page home").assertIsDisplayed()+ }++ @Test fun messageDrainConsumesPostedMessages() {+ val stack = NavBackStack(arrayOf(Screen("home")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen> { Text("DrainHome") }+ }+ }+ }+ rule.onNodeWithText("DrainHome").assertIsDisplayed()+ // Posted from outside composition, as a ViewModel/worker would. The+ // drain collects it onto the (host-owned) snackbar state.+ AppMessages.show("drain-check-${System.nanoTime()}", actionLabel = "Undo") { }+ rule.waitForIdle()+ rule.onNodeWithText("DrainHome").assertIsDisplayed()+ }++ @Test fun sharedModifiersInsideNavigationMorph() {+ val stack = NavBackStack(arrayOf(Screen("home")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen>(metadata = motionFor(obj.route)) { screen ->+ Column {+ Text("Head ${screen.route}", Modifier.sharedContainer("head"))+ Text("Leaf ${screen.route}", Modifier.sharedContent("leaf"))+ Text("Words ${screen.route}", Modifier.sharedText("words"))+ Text("Crop ${screen.route}", Modifier.sharedCrop("crop"))+ Text("Expand ${screen.route}", Modifier.expandFromLine())+ Text("Drop ${screen.route}", Modifier.dropsAway())+ Text("Sink ${screen.route}", Modifier.sinksBelow())+ Text("Morphing ${isNavMorphing()} leaving ${isNavLeaving()}")+ }+ }+ }+ }+ }+ rule.onNodeWithText("Head home").assertIsDisplayed()+ rule.runOnIdle { stack.add(Screen("morph")) }+ rule.waitForIdle()+ rule.onNodeWithText("Head morph").assertExists()+ rule.onNodeWithText("Crop morph").assertExists()+ rule.runOnIdle { stack.pop() }+ rule.waitForIdle()+ rule.onNodeWithText("Head home").assertIsDisplayed()+ // A Detail push (screen still leaves) also composes the exit helpers.+ rule.runOnIdle { stack.add(Screen("zoom")) }+ rule.waitForIdle()+ rule.onNodeWithText("Head zoom").assertExists()+ }++ @Test fun gameHubHooksResolveEveryDisplayName() {+ val ids = listOf(+ "chess", "solitaire", "pipes", "unblockjam", "wordmaker", "logicgate",+ "sudoku", "minesweeper", "nonogram", "arrows", "kart", "brand_new_game",+ )+ rule.setContent {+ MaterialTheme {+ Column {+ ids.forEach { id -> GameHubComposeHook(gameId = id, achievementsManager = null) }+ Text("AllHooks")+ }+ }+ }+ rule.onNodeWithText("AllHooks").assertIsDisplayed()+ rule.waitForIdle()+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryComposeTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryComposeTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryComposeTest.ktnew file mode 100644index 0000000000..6c0ae39ad8--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryComposeTest.kt@@ -0,0 +1,244 @@+package com.vayunmathur.library.util++import android.content.Context+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.sdk.games.GameHubClient+import kotlinx.serialization.Serializable+import org.junit.Rule+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++/** MainNavigation, bottom bar, shared-element modifiers and GameHub compose hooks under Robolectric. */+@RunWith(RobolectricTestRunner::class)+class LibraryComposeTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Serializable data class Screen(val route: String) : NavKey+ @Serializable data class Other(val route: String) : NavKey++ private class ComposeAchievements(context: Context, prefix: String) : AchievementsManager(+ context,+ """[{"id":"first_win","name":"First","description":"d","targetProgress":1}]""",+ prefix,+ ) {+ override fun checkExistingAchievements() {}+ }++ @Test fun mainNavigationRendersTopAndBottomBarAndPushes() {+ val stack = NavBackStack(arrayOf(Screen("home")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack, bottomBar = { Text("BottomChrome") }) {+ entry<Screen> { Text("Screen ${it.route}") }+ }+ }+ }+ rule.onNodeWithText("Screen home").assertIsDisplayed()+ rule.onNodeWithText("BottomChrome").assertIsDisplayed()+ rule.runOnIdle { stack.add(Screen("detail")) }+ rule.waitForIdle()+ rule.onNodeWithText("Screen detail").assertIsDisplayed()+ rule.runOnIdle { stack.pop() }+ rule.waitForIdle()+ rule.onNodeWithText("Screen home").assertIsDisplayed()+ }++ @Test fun mainNavigationTransparentContainer() {+ val stack = NavBackStack(arrayOf(Screen("only")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(+ backStack = stack,+ containerColor = androidx.compose.ui.graphics.Color.Transparent,+ ) {+ entry<Screen> { Text("OnlyScreen") }+ }+ }+ }+ rule.onNodeWithText("OnlyScreen").assertIsDisplayed()+ }++ @Test fun rememberNavBackStackRetainsAndListOverload() {+ var captured: NavBackStack<Screen>? = null+ rule.setContent {+ MaterialTheme {+ val stack = rememberNavBackStack(listOf(Screen("a"), Screen("b")))+ captured = stack+ Text("Top ${stack.last().route}")+ }+ }+ rule.onNodeWithText("Top b").assertIsDisplayed()+ assertEquals(listOf("a", "b"), captured!!.backStack.map { it.route })+ rule.runOnIdle { captured!!.add(Screen("c")) }+ rule.waitForIdle()+ rule.onNodeWithText("Top c").assertIsDisplayed()+ }++ @Test fun bottomNavBarBackStackOverloadSelectsAndClicks() {+ val stack = NavBackStack(arrayOf(Screen("home")))+ var current by mutableStateOf<Screen>(Screen("home"))+ val pages = listOf(+ BottomBarItem<Screen>(name = "HomeTab", route = Screen("home"), icon = { Text("H-ic") }),+ BottomBarItem<Screen>(name = "SettingsTab", route = Screen("settings"), icon = { Text("S-ic") }),+ )+ // `current` must be observable inside composition for recomposition on change.+ rule.setContent {+ MaterialTheme {+ Column {+ BottomNavBar(+ backStack = stack,+ pages = pages,+ currentPage = current,+ onSelect = { current = it; stack.reset(it) },+ )+ }+ }+ }+ rule.onNodeWithText("SettingsTab").performClick()+ rule.waitForIdle()+ assertEquals("settings", stack.last().route)+ assertEquals(Screen("settings"), current)+ rule.onNodeWithText("HomeTab").performClick()+ rule.waitForIdle()+ assertEquals("home", stack.last().route)+ }++ @Test fun bottomNavBarSlotOverloadWithItems() {+ var clicks = 0+ rule.setContent {+ MaterialTheme {+ BottomNavBar {+ BottomNavBarItem(selected = true, onClick = { clicks++ }, icon = { Text("IcA") }, label = "Alpha")+ BottomNavBarItem(selected = false, onClick = { clicks += 10 }, icon = { Text("IcB") }, enabled = false)+ BottomNavBarItem(selected = false, onClick = { clicks += 100 }, icon = { Text("IcC") })+ }+ }+ }+ rule.onNodeWithText("Alpha").assertIsDisplayed()+ rule.onNodeWithText("Alpha").performClick()+ assertEquals(1, clicks)+ assertEquals(64.dp, BottomNavBarHeight)+ }++ @Test fun sharedModifiersNoOpOutsideNavigationAndFlagsFalse() {+ var morphing: Boolean? = null+ var leaving: Boolean? = null+ rule.setContent {+ MaterialTheme {+ morphing = isNavMorphing()+ leaving = isNavLeaving()+ Column {+ Text("container", Modifier.sharedContainer("k1"))+ Text("content", Modifier.sharedContent("k2"))+ Text("textmorph", Modifier.sharedText("k3"))+ Text("crop", Modifier.sharedCrop("k4"))+ Text("expand", Modifier.expandFromLine())+ Text("drops", Modifier.dropsAway())+ Text("sinks", Modifier.sinksBelow())+ Box(Modifier.fillMaxSize().onFileDrop { })+ Text("now ${nowState().value}")+ }+ }+ }+ rule.onNodeWithText("container").assertIsDisplayed()+ rule.onNodeWithText("crop").assertIsDisplayed()+ assertEquals(false, morphing)+ assertEquals(false, leaving)+ }++ @Test fun sharedEditableTextNullAndKeyed() {+ rule.setContent {+ MaterialTheme {+ Column {+ SharedEditableText(key = null, value = "plain") { Text("InnerPlain") }+ SharedEditableText(key = "morph-key", value = "keyed") { Text("InnerKeyed") }+ }+ }+ }+ rule.onNodeWithText("InnerPlain").assertIsDisplayed()+ rule.onNodeWithText("InnerKeyed").assertIsDisplayed()+ rule.onNodeWithText("keyed").assertExists()+ }++ @Test fun gameHubHooksComposeAndClientNotInstalled() {+ var client: GameHubClient? = null+ val manager = ComposeAchievements(ctx, "compose${System.nanoTime()}_")+ rule.setContent {+ MaterialTheme {+ client = rememberGameHubClient("chess")+ Column {+ GameHubComposeHook(gameId = "chess", achievementsManager = manager)+ GameHubSessionHook(gameId = "sudoku", displayName = "Sudoku")+ Text("HooksHost")+ }+ }+ }+ rule.onNodeWithText("HooksHost").assertIsDisplayed()+ rule.waitForIdle()+ assertNotNull(client)+ assertFalse(client!!.isHubInstalled())+ }++ @Test fun gameHubHookWithoutManager() {+ rule.setContent {+ MaterialTheme {+ Column {+ GameHubComposeHook(gameId = "unknown_game_xyz", achievementsManager = null)+ Text("NoManagerHost")+ }+ }+ }+ rule.onNodeWithText("NoManagerHost").assertIsDisplayed()+ }++ @Test fun entryProviderScopeMatchesOnlyItsType() {+ val hit = EntryProviderScope<NavKey>(Screen("a"))+ hit.entry<Screen> { Text("unused") }+ assertNotNull(hit.result)+ val miss = EntryProviderScope<NavKey>(Screen("a"))+ miss.entry<Other> { Text("unused") }+ assertNull(miss.result)+ }++ @Test fun pageHelpersDeclareMotions() {+ assertEquals(NavMotion.Detail, navMotionIn(DetailPage()))+ assertEquals(NavMotion.Zoom, navMotionIn(ZoomPage()))+ assertEquals(NavMotion.Fullscreen, navMotionIn(FullscreenPage()))+ assertEquals(NavMotion.Sibling, navMotionIn(SiblingPage()))+ assertEquals(NavMotion.Morph, navMotionIn(MorphPage()))+ assertEquals(NavMotion.Detail, navMotionIn(null))+ assertEquals(NavMotion.Detail, navMotionIn(emptyMap()))+ assertEquals(NavMotion.Detail, navMotionIn(mapOf(NAV_MOTION_KEY to "not-a-motion")))+ assertTrue(DialogPage().isNotEmpty())+ assertTrue(ListDetailPage().isNotEmpty())+ }++ @Test fun nowStateProducesInstant() {+ var seen: String? = null+ rule.setContent { seen = nowState().value.toString() }+ rule.waitForIdle()+ assertTrue(seen != null && seen!!.contains("T"), "instant string: $seen")+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryFormatSdk32Test.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryFormatSdk32Test.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryFormatSdk32Test.ktnew file mode 100644index 0000000000..17922647e7--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryFormatSdk32Test.kt@@ -0,0 +1,35 @@+package com.vayunmathur.library.util++import java.util.Locale+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Format helpers on the pre-API-33 fallback path (LocaleData measurement system). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [32])+class LibraryFormatSdk32Test {++ @Test fun formatSpeedImperialAndMetricFallback() {+ val us = 10f.formatSpeed(Locale.US) // 10 m/s in mph+ assertTrue(us.contains("22.4"), us)+ val de = 10f.formatSpeed(Locale.GERMANY) // 10 m/s in km/h+ assertTrue(de.contains("36"), de)+ assertTrue(0f.formatSpeed(Locale.US).contains("0"), "zero speed")+ }++ @Test fun digitsAndCommasOnOlderSdk() {+ assertEquals("3.14", 3.14159.toStringDigits(2))+ assertEquals("-3.14", (-3.14159).toStringDigits(2))+ assertEquals("1,000,000", 1_000_000L.toStringCommas())+ }++ @Test fun localizedNamesOnOlderSdk() {+ assertEquals("January", localizedMonthNames(DateNameStyle.FULL, Locale.US).first())+ assertEquals(7, localeFirstDayOfWeek(Locale.US))+ assertEquals(1, localeFirstDayOfWeek(Locale.GERMANY))+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryGameHubTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryGameHubTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryGameHubTest.ktnew file mode 100644index 0000000000..6eedd9cf0f--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryGameHubTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.library.util++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.sdk.games.DailyStreak+import com.vayunmathur.sdk.games.GameHubClient+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * GameHubReporter/GameHubSessionReporter/DailyStreakReporter against a real+ * [GameHubClient] with no hub installed: every call fail-softs, which is the+ * behaviour games rely on, and the legacy->hub mapping still runs.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LibraryGameHubTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private class HubAchievements(context: Context, prefix: String) : AchievementsManager(+ context,+ """[+ {"id":"win_50_master","name":"Master","description":"d","targetProgress":50},+ {"id":"win_10_enthusiast","name":"Ten","description":"d","targetProgress":10},+ {"id":"first_win","name":"First","description":"d","targetProgress":1},+ {"id":"level_500","name":"L500","description":"d","targetProgress":500},+ {"id":"win_vs_ai_hard","name":"Hard","description":"d","targetProgress":1},+ {"id":"win_3","name":"Three","description":"d","targetProgress":3},+ {"id":"level_100","name":"L100","description":"d","targetProgress":100},+ {"id":"level_1_done","name":"L1","description":"d","targetProgress":1},+ {"id":"first_mate","name":"Mate","description":"d","targetProgress":1},+ {"id":"plain_quest","name":"Plain","description":"d","targetProgress":2}+ ]""",+ prefix,+ ) {+ override fun checkExistingAchievements() {}+ }++ @Test fun bindMapsAchievementsAndForwardsUnlocks() = runBlocking {+ val manager = HubAchievements(ctx, "hub${System.nanoTime()}_")+ manager.onProgressUpdated("first_win", 1)+ withTimeout(5000) { while (manager.newAchievement.value == null) delay(20) }+ assertEquals("first_win", manager.newAchievement.value!!.id)++ val client = GameHubClient(ctx, "chess")+ val handle = GameHubReporter.bind(ctx, "chess", manager, client)+ // The bind scope seeds defs/progress against the (absent) hub; give the+ // collectors a deterministic condition: the manager unlock flow below.+ manager.dismissNotification()+ manager.onAchievementUnlocked("win_3")+ withTimeout(5000) { while (manager.newAchievement.value?.id != "win_3") delay(20) }+ handle.cancel()+ handle.cancel() // cancelling a cancelled handle is safe+ }++ @Test fun bindWithCustomMetadata() = runBlocking {+ val manager = HubAchievements(ctx, "hub2${System.nanoTime()}_")+ val client = GameHubClient(ctx, "sudoku")+ val handle = GameHubReporter.bind(+ ctx, "sudoku", manager, client,+ com.vayunmathur.sdk.games.GameMetadata("sudoku", "Sudoku!", versionName = "1.0"),+ )+ // Seeding completes silently against the absent hub; wait until the+ // manager side can still service a progress write through the binder.+ manager.onProgressUpdated("plain_quest", 1)+ withTimeout(5000) {+ while (true) {+ val statuses = manager.getAchievementStatuses().first()+ if (statuses.any { it.achievement.id == "plain_quest" && it.progress == 1 }) break+ delay(20)+ }+ }+ handle.cancel()+ }++ @Test fun sessionReporterStartEndWithoutHub() {+ val reporter = GameHubSessionReporter(GameHubClient(ctx, "pipes"))+ reporter.end() // no session: early return+ reporter.start()+ reporter.start() // a session launch is already in flight / started+ reporter.end()+ reporter.end()+ }++ @Test fun dailyStreakReporterSwallowsMissingHub() = runBlocking {+ // No hub installed: report() must complete without throwing.+ DailyStreakReporter.report(ctx, "sudoku", DailyChallengeStore.Streak(3, 7), 20_000L)+ DailyStreakReporter.report(ctx, "sudoku", DailyChallengeStore.Streak(0, 0), 0L)+ }++ @Test fun hubClientQueriesWithoutHub() = runBlocking {+ val client = GameHubClient(ctx, "arrows")+ assertEquals(false, client.isHubInstalled())+ assertEquals(false, client.registerGame(com.vayunmathur.sdk.games.GameMetadata("arrows", "Arrows")))+ assertNull(client.startSession())+ assertEquals(false, client.endSession("nope"))+ assertEquals(false, client.unlockAchievement("first_win"))+ assertEquals(false, client.reportProgress("first_win", 2))+ assertEquals(false, client.reportDailyStreak(DailyStreak(1, 1, 1L)))+ client.registerAchievements(emptyList())+ client.syncAchievementProgress(emptyList())+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryMarkdown2Test.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryMarkdown2Test.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryMarkdown2Test.ktnew file mode 100644index 0000000000..191bd8f93f--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryMarkdown2Test.kt@@ -0,0 +1,168 @@+package com.vayunmathur.library.util++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextDecoration+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Deep markdown coverage: math/latex, fences, tasks, search highlight, hidden markers. */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](sdk = [34])+class LibraryMarkdown2Test {++ @Test fun headerLevelsGetDescendingSizes() {+ val h1 = parseMarkdown("# One")+ val h3 = parseMarkdown("### Three")+ val s1 = h1.spanStyles.first { it.item.fontWeight == FontWeight.Bold }+ val s3 = h3.spanStyles.first { it.item.fontWeight == FontWeight.Bold }+ assertTrue(s1.item.fontSize.value > s3.item.fontSize.value)+ assertTrue(h1.paragraphStyles.isNotEmpty())+ // Level beyond 6 hashes is not a header.+ val notHeader = parseMarkdown("####### Seven")+ assertFalse(notHeader.spanStyles.any { it.item.fontWeight == FontWeight.Bold && it.item.fontSize.value > 20f })+ }++ @Test fun hiddenMarkersKeepTextButHideSpans() {+ val hidden = parseMarkdown("**bold** and *ital*", showMarkers = false)+ assertEquals("**bold** and *ital*", hidden.text)+ // Transparent 0-size spans hide the markers.+ assertTrue(hidden.spanStyles.any { it.item.color == Color.Transparent })+ val shown = parseMarkdown("**bold**", showMarkers = true)+ assertFalse(shown.spanStyles.any { it.item.color == Color.Transparent && it.item.fontSize.value == 0f })+ }++ @Test fun taskListCheckedIsStruckThrough() {+ val md = parseMarkdown("- [x] done task\n- [ ] open task")+ assertTrue(md.text.contains("done task"))+ assertTrue(md.text.contains("open task"))+ assertTrue(md.spanStyles.any { it.item.textDecoration == TextDecoration.LineThrough })+ }++ @Test fun nestedAndNumberedLists() {+ val md = parseMarkdown("- a\n - b\n - c\n1) first\n2) second")+ assertTrue(md.text.contains("• a"))+ assertTrue(md.text.contains("first"))+ assertTrue(md.paragraphStyles.isNotEmpty(), "list indent paragraph styles expected")+ }++ @Test fun fencedCodeIsMonospaceAndInlineCodeSkipsFence() {+ val md = parseMarkdown("before\n```kotlin\nval x = 1\n```\nafter `code` end")+ assertTrue(md.text.contains("val x = 1"))+ assertTrue(md.spanStyles.any { it.item.fontFamily == FontFamily.Monospace })+ // Raw mode (no soft-wrap merging) is what lets the fence regex see the block.+ val fenced = parseMarkdown("```kotlin\nval x = 1\nval y = 2\n```", process = false, softWrap = false)+ assertTrue(fenced.text.contains("val x = 1"))+ assertTrue(+ fenced.spanStyles.any {+ it.item.fontFamily == FontFamily.Monospace && it.item.background != Color.Unspecified+ },+ "fence content should carry the code background",+ )+ }++ @Test fun blockMathFormatsFracSqrtAndGreekWhenHidden() {+ val md = parseMarkdown("$$\\frac{1}{2} + \\sqrt{4} + \\alpha$$", showMarkers = false)+ assertTrue(md.text.contains("((1)/(2))"), md.text)+ assertTrue(md.text.contains("√(4)"), md.text)+ assertTrue(md.text.contains("α"), md.text)+ assertTrue(md.spanStyles.any { it.item.fontFamily == FontFamily.Serif })+ assertTrue(md.paragraphStyles.isNotEmpty(), "block math centred paragraph expected")+ }++ @Test fun inlineMathAndSqrtN() {+ val md = parseMarkdown("value $\\sqrt[3]{8}$ end", showMarkers = false)+ assertTrue(md.text.contains("(8)^(1/3)"), md.text)+ val shown = parseMarkdown("value \$x^2\$ end", showMarkers = true)+ assertEquals("value \$x^2\$ end", shown.text)+ }++ @Test fun latexFormatCommandsStyleContent() {+ val bold = parseMarkdown("\\mathbf{word}")+ assertTrue(bold.spanStyles.any { it.item.fontWeight == FontWeight.Bold })+ val cancel = parseMarkdown("\\cancel{word}")+ assertTrue(cancel.spanStyles.any { it.item.textDecoration == TextDecoration.LineThrough })+ val under = parseMarkdown("\\underline{word}")+ assertTrue(under.spanStyles.any { it.item.textDecoration == TextDecoration.Underline })+ val mono = parseMarkdown("\\mathtt{word}")+ assertTrue(mono.spanStyles.any { it.item.fontFamily == FontFamily.Monospace })+ val italic = parseMarkdown("\\mathit{word}")+ assertTrue(italic.spanStyles.any { it.item.fontStyle == FontStyle.Italic })+ }++ @Test fun latexOperatorsAndNestedFrac() {+ val md = parseMarkdown("$$\\frac{\\frac{1}{2}}{3} \\times \\infty \\leq$$", showMarkers = false)+ assertTrue(md.text.contains("×"), md.text)+ assertTrue(md.text.contains("∞"), md.text)+ assertTrue(md.text.contains("≤"), md.text)+ val leftRight = parseMarkdown("$$\\left( x \\right)$$", showMarkers = false)+ assertFalse(leftRight.text.contains("\\left"), leftRight.text)+ }++ @Test fun searchHighlightMarksCurrentAndOthers() {+ val md = parseMarkdown("cat dog cat bird cat", searchQuery = "cat", searchIndex = 1)+ val backgrounds = md.spanStyles.mapNotNull { it.item.background.takeIf { b -> b != Color.Unspecified } }+ assertTrue(backgrounds.size >= 3, "expected 3 highlights, got $backgrounds")+ assertTrue(backgrounds.any { it == Color(0xFFFFA500) }, "current highlight orange")+ assertTrue(backgrounds.any { it == Color.Yellow })+ val none = parseMarkdown("hello", searchQuery = "zzz")+ assertFalse(none.spanStyles.any { it.item.background == Color.Yellow })+ val emptyQuery = parseMarkdown("hello", searchQuery = "")+ assertFalse(emptyQuery.spanStyles.any { it.item.background == Color.Yellow })+ }++ @Test fun linksCarryUrlAnnotation() {+ val md = parseMarkdown("go to [Example](https://example.org/path) now")+ val links = md.getLinkAnnotations(0, md.text.length)+ assertEquals(1, links.size)+ assertTrue(md.spanStyles.any { it.item.textDecoration == TextDecoration.Underline })+ }++ @Test fun strikethroughAndBlockquoteStyles() {+ val strike = parseMarkdown("~~gone~~ kept")+ assertTrue(strike.spanStyles.any { it.item.textDecoration == TextDecoration.LineThrough })+ val quote = parseMarkdown("> wise words\nplain")+ assertTrue(quote.spanStyles.any { it.item.fontStyle == FontStyle.Italic })+ }++ @Test fun softWrapCollapsesBlankRunsAndMerges() {+ val md = parseMarkdown("para one\nstill one\n\n\n\npara two")+ assertEquals("para one still one\npara two", md.text)+ val noSoft = parseMarkdown("a\nb", softWrap = false, process = false)+ assertEquals("a\nb", noSoft.text)+ val raw = parseMarkdown("# H\n- item", process = false, softWrap = false)+ assertEquals("# H\n- item", raw.text)+ }++ @Test fun underscoreBoldAndItalic() {+ val bold = parseMarkdown("__strong__ text")+ assertTrue(bold.spanStyles.any { it.item.fontWeight == FontWeight.Bold })+ val ital = parseMarkdown("_em_ text")+ assertTrue(ital.spanStyles.any { it.item.fontStyle == FontStyle.Italic })+ }++ @Test fun latexCommandSweepAndHeaderLevel6() {+ val md = parseMarkdown(+ "$$\\Gamma \\Delta \\rightarrow \\leftarrow \\Rightarrow \\sum \\int \\prod \\sin \\cos " ++ "\\forall \\exists \\in \\subset \\cup \\cap \\infty \\partial \\nabla " ++ "\\langle x \\rangle \\lceil y \\rceil \\quad z$$",+ showMarkers = false,+ )+ for (expected in listOf("Γ", "Δ", "→", "←", "⇒", "∑", "∫", "∏", "sin", "cos", "∀", "∃", "∈", "⊂", "∪", "∩", "∞", "∂", "∇", "⟨", "⟩", "⌈", "⌉")) {+ assertTrue(md.text.contains(expected), "missing $expected in ${md.text}")+ }+ val h6 = parseMarkdown("###### Deepest")+ assertTrue(h6.spanStyles.any { it.item.fontWeight == FontWeight.Bold })+ val upperTask = parseMarkdown("- [X] shipped")+ assertTrue(upperTask.spanStyles.any { it.item.textDecoration == TextDecoration.LineThrough })+ }++ @Test fun bulletVariantsNormalise() {+ val md = parseMarkdown("* star\n+ plus\n- dash")+ assertTrue(md.text.lines().all { it.trimStart().startsWith("•") || it.isBlank() }, md.text)+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryNavResultsTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryNavResultsTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryNavResultsTest.ktnew file mode 100644index 0000000000..9c3435866b--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryNavResultsTest.kt@@ -0,0 +1,113 @@+package com.vayunmathur.library.util++import android.content.Intent+import androidx.activity.ComponentActivity+import androidx.activity.compose.LocalActivity+import androidx.compose.foundation.layout.Column+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import kotlinx.coroutines.launch+import kotlinx.serialization.Serializable+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** NavResultRegistry/ResultEffect delivery and openSettingsIfRequested. */+@RunWith(RobolectricTestRunner::class)+class LibraryNavResultsTest {++ @get:Rule val rule = createComposeRule()++ @Serializable data class Page(val route: String) : NavKey++ @Test fun resultEffectDeliversOnlyMatchingKeyAndType() {+ val registry = NavResultRegistry()+ val received = mutableListOf<String>()+ var intSeen = -1+ rule.setContent {+ MaterialTheme {+ CompositionLocalProvider(LocalNavResultRegistry provides registry) {+ Column {+ ResultEffect<String>("greeting") { received += it }+ ResultEffect<Int>("count") { intSeen = it }+ Text("ResultsHost")+ }+ }+ }+ }+ rule.onNodeWithText("ResultsHost").assertIsDisplayed()+ val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default)+ scope.launch {+ registry.dispatchResult("other", "ignored")+ registry.dispatchResult("greeting", 42) // wrong type for greeting+ registry.dispatchResult("greeting", "hello")+ registry.dispatchResult("count", 7)+ }+ rule.waitUntil(5_000) { received.isNotEmpty() && intSeen != -1 }+ assertEquals(listOf("hello"), received)+ assertEquals(7, intSeen)+ }++ private fun activityWithAction(action: String): ComponentActivity =+ Robolectric.buildActivity(+ ComponentActivity::class.java,+ Intent(action),+ ).create().get()++ @Test fun openSettingsIfRequestedPushesSettingsAndConsumesIntent() {+ val stack = NavBackStack(arrayOf(Page("home")))+ val activity = activityWithAction(Intent.ACTION_APPLICATION_PREFERENCES)+ rule.setContent {+ MaterialTheme {+ CompositionLocalProvider(LocalActivity provides activity) {+ with(stack) { openSettingsIfRequested(Page("settings")) }+ Text("Current ${stack.last().route}")+ }+ }+ }+ rule.waitForIdle()+ assertEquals("settings", stack.last().route)+ assertEquals(Intent.ACTION_MAIN, activity.intent.action)+ rule.onNodeWithText("Current settings").assertIsDisplayed()+ }++ @Test fun openSettingsIfRequestedIgnoresNormalLaunch() {+ val stack = NavBackStack(arrayOf(Page("home")))+ val activity = activityWithAction(Intent.ACTION_MAIN)+ rule.setContent {+ MaterialTheme {+ CompositionLocalProvider(LocalActivity provides activity) {+ with(stack) { openSettingsIfRequested(Page("settings")) }+ Text("Current ${stack.last().route}")+ }+ }+ }+ rule.waitForIdle()+ assertEquals("home", stack.last().route)+ assertTrue(stack.backStack.size == 1)+ }++ @Test fun openSettingsIfRequestedAlreadyOnSettingsDoesNotDuplicate() {+ val stack = NavBackStack(arrayOf(Page("settings")))+ val activity = activityWithAction(Intent.ACTION_APPLICATION_PREFERENCES)+ rule.setContent {+ MaterialTheme {+ CompositionLocalProvider(LocalActivity provides activity) {+ with(stack) { openSettingsIfRequested(Page("settings")) }+ Text("Current ${stack.last().route}")+ }+ }+ }+ rule.waitForIdle()+ assertEquals(1, stack.backStack.size)+ assertEquals("settings", stack.last().route)+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryState2Test.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryState2Test.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryState2Test.ktnew file mode 100644index 0000000000..baddf8e878--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryState2Test.kt@@ -0,0 +1,240 @@+package com.vayunmathur.library.util++import android.content.Context+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import androidx.room3.Room+import androidx.room3.RoomDatabase+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlinx.coroutines.delay+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.milliseconds+import kotlin.time.Duration.Companion.seconds+import kotlinx.datetime.LocalTime+import kotlin.time.Instant++/** Converters, MatchingDao, LevelStats, DailyChallenge, Achievements, AppMessages. */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](sdk = [34])+class LibraryState2Test {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private class TestAchievements(context: Context, prefix: String) : AchievementsManager(+ context,+ """[{"id":"first_win","name":"First Win","description":"win once","targetProgress":3},+ {"id":"win_10","name":"Ten","description":"win ten","targetProgress":10,"isSecret":true}]""",+ prefix,+ ) {+ var checked = false+ override fun checkExistingAchievements() { checked = true }+ }++ private class TestLevelStats(context: Context, name: String) : LevelStatsRepository(context, name) {+ fun bump(key: String) = incrementCounter(key)+ fun count(key: String) = getCounter(key)+ }++ @Test fun defaultConvertersRoundTrip() {+ val c = DefaultConverters()+ val instant = Instant.fromEpochSeconds(1_700_000_000)+ assertEquals(instant, c.toInstant(c.fromInstant(instant)))+ assertNull(c.fromInstantNullable(null)); assertNull(c.toInstantNullable(null))+ assertEquals(instant, c.toInstantNullable(c.fromInstantNullable(instant)))+ assertEquals(listOf(1L, 2L), c.toList(c.fromList(listOf(1L, 2L))))+ assertNull(c.fromList(null)); assertNull(c.toList(null))+ assertEquals(listOf("a", "b"), c.toListS(c.fromListS(listOf("a", "b"))))+ assertEquals(1500L, c.fromDuration(1500.milliseconds))+ assertEquals(1500.milliseconds, c.toDuration(1500L))+ assertNull(c.fromDurationNullable(null)); assertNull(c.toDurationNullable(null))+ assertEquals(LocalTime(13, 30, 15), c.toLocalTime(c.fromLocalTime(LocalTime(13, 30, 15))))+ }++ @Test fun matchingDaoCrudAndDirections() = runBlocking {+ val db = Room.inMemoryDatabaseBuilder(ctx, LibraryState2TestDb::class.java).allowMainThreadQueries().build()+ try {+ val dao = db.matchingDao()+ val id = dao.upsert(ManyManyMatching(leftID = 1, rightID = 10, type = 7))+ assertTrue(id > 0)+ dao.upsert(listOf(ManyManyMatching(1, 11, 7), ManyManyMatching(2, 10, 7), ManyManyMatching(1, 10, 8)))+ assertEquals(listOf(10L, 11L), dao.getFromLeft(1, 7).sorted())+ assertEquals(listOf(1L, 2L), dao.getFromRight(10, 7).sorted())+ assertEquals(3, dao.flow().first().count { it.type == 7 })+ dao.deleteMatch(1, 10, 7)+ assertEquals(listOf(11L), dao.getFromLeft(1, 7))+ dao.deleteFromRight(10, 7)+ assertEquals(emptyList(), dao.getFromRight(10, 7))+ dao.deleteFromLeft(1, 7)+ assertEquals(emptyList(), dao.getFromLeft(1, 7))+ // Remaining row is type 8; deleteByType then clear.+ dao.deleteByType(8)+ assertTrue(dao.flow().first().isEmpty())+ val row = ManyManyMatching(5, 6, 1)+ dao.upsert(row)+ val stored = dao.flow().first().single()+ assertEquals(1, dao.delete(stored))+ closeCachedDatabase<LibraryState2TestDb>() // no cached db: must be a safe no-op+ databases[LibraryState2TestDb::class] = db+ closeCachedDatabase<LibraryState2TestDb>()+ assertFalse(databases.containsKey(LibraryState2TestDb::class))+ } finally {+ runCatching { db.close() }+ }+ }++ @Test fun levelStatsKeepsLowestAndRetainsOnly() {+ val repo = TestLevelStats(ctx, "test_levels_${System.nanoTime()}")+ assertEquals(emptyMap(), repo.getLevelStats())+ repo.updateBestScore("lvl1", 100)+ assertEquals(100, repo.getLevelStats()["lvl1"]?.bestScore)+ repo.updateBestScore("lvl1", 150) // worse (higher) is ignored+ assertEquals(100, repo.getLevelStats()["lvl1"]?.bestScore)+ repo.updateBestScore("lvl1", 80)+ assertEquals(80, repo.getLevelStats()["lvl1"]?.bestScore)+ repo.updateBestScore("lvl2", 50)+ repo.retainOnly(setOf("lvl2"))+ assertEquals(setOf("lvl2"), repo.getLevelStats().keys)+ repo.retainOnly(setOf("lvl2")) // no-op, same size+ assertEquals(50, repo.getLevelStats()["lvl2"]?.bestScore)+ assertEquals(LevelStats(50), repo.getLevelStats()["lvl2"])+ repo.bump("plays"); repo.bump("plays")+ assertEquals(2, repo.count("plays"))+ assertEquals(0, repo.count("never"))+ }++ @Test fun dailyChallengeStreakProgression() = runBlocking {+ val store = DailyChallengeStore(ctx, "dc${System.nanoTime()}")+ assertEquals(Long.MIN_VALUE, store.lastCompletedDay())+ assertEquals(0L, store.bestStreak())+ val day = store.todayEpochDay()+ assertTrue(day > 0)+ val first = store.recordDayCompleted(day)+ assertEquals(DailyChallengeStore.Streak(1, 1), first)+ val again = store.recordDayCompleted(day) // same day: no double count+ assertEquals(1L, again.current)+ val next = store.recordDayCompleted(day + 1)+ assertEquals(DailyChallengeStore.Streak(2, 2), next)+ val gap = store.recordDayCompleted(day + 5) // gap resets current, best stays+ assertEquals(DailyChallengeStore.Streak(1, 2), gap)+ assertEquals(2L, store.bestStreak())+ assertEquals(day + 5, store.lastCompletedDay())+ assertEquals(day + 5, store.lastCompletedDayFlow.first())+ assertEquals(2L, store.bestStreakFlow.first())+ // currentStreak flow: last day is not today/yesterday relative to real today -> lapsed 0.+ assertEquals(0L, store.currentStreak.first())+ }++ @Test fun dailyChallengeCurrentStreakToday() = runBlocking {+ val store = DailyChallengeStore(ctx, "dcnow${System.nanoTime()}")+ store.recordDayCompleted(store.todayEpochDay())+ assertEquals(1L, store.currentStreak.first())+ }++ private suspend fun await(timeoutMs: Long = 5000, cond: suspend () -> Boolean) {+ withTimeout(timeoutMs) { while (!cond()) delay(20) }+ }++ @Test fun achievementsUnlockProgressAndForget() = runBlocking {+ val mgr = TestAchievements(ctx, "ach${System.nanoTime()}_")+ assertEquals(2, mgr.achievements.size)+ assertEquals("first_win", mgr.achievements[0].id)+ assertTrue(mgr.achievements[1].isSecret)+ mgr.checkExistingAchievements(); assertTrue(mgr.checked)+ assertNull(mgr.newAchievement.value)++ mgr.onAchievementUnlocked("unknown_id") // no-op+ mgr.onProgressUpdated("unknown_id", 99)+ mgr.onProgressUpdated("first_win", 2) // below target 3+ await { mgr.getAchievementStatuses().first().first { it.achievement.id == "first_win" }.progress == 2 }+ var status = mgr.getAchievementStatuses().first().first { it.achievement.id == "first_win" }+ assertEquals(2, status.progress); assertFalse(status.isUnlocked)++ mgr.onProgressUpdated("first_win", 1) // lower progress does not regress+ delay(150)+ status = mgr.getAchievementStatuses().first().first { it.achievement.id == "first_win" }+ assertEquals(2, status.progress)++ mgr.onProgressUpdated("first_win", 3) // reaches target -> unlocks+ await { mgr.newAchievement.value?.id == "first_win" }+ await { mgr.getAchievementStatuses().first().first { it.achievement.id == "first_win" }.isUnlocked }+ mgr.dismissNotification()+ assertNull(mgr.newAchievement.value)++ mgr.forgetAll()+ await {+ val s = mgr.getAchievementStatuses().first().first { it.achievement.id == "first_win" }+ s.progress == 0 && !s.isUnlocked+ }+ }++ @Test fun achievementsDirectUnlockIsIdempotentNotification() = runBlocking {+ val mgr = TestAchievements(ctx, "ach2${System.nanoTime()}_")+ mgr.onAchievementUnlocked("win_10")+ await { mgr.newAchievement.value?.id == "win_10" }+ mgr.dismissNotification()+ mgr.onAchievementUnlocked("win_10") // already in set: no second notification+ delay(200)+ assertNull(mgr.newAchievement.value)+ }++ @Test fun appMessagesDedupAndActionBypass() = runBlocking {+ val received = java.util.concurrent.CopyOnWriteArrayList<AppMessages.Message>()+ val job = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default).launch {+ AppMessages.messages.collect { received += it }+ }+ try {+ // SharedFlow has no replay: posting before the collector subscribes+ // would drop the message, so warm up until one is observed.+ val warmup = "warmup-${System.nanoTime()}"+ var attempt = 0+ await {+ if (received.isEmpty()) AppMessages.show("$warmup-${attempt++}")+ received.isNotEmpty()+ }+ received.clear()+ val unique = "msg-${System.nanoTime()}"+ AppMessages.show(unique)+ AppMessages.show(unique) // deduped within window+ AppMessages.show(unique, actionLabel = "Retry") // action messages bypass dedup+ AppMessages.show("$unique-other", duration = AppMessages.Duration.Long)+ await { received.size >= 3 }+ assertEquals(unique, received[0].text)+ assertEquals("Retry", received[1].actionLabel)+ assertEquals(AppMessages.Duration.Long, received[2].duration)+ assertEquals(AppMessages.Duration.Short, received[0].duration)+ assertNull(received[0].onAction)+ } finally { job.cancel() }+ }++ @Test fun secureResultReceiverForwards() {+ var got: Pair<Int, Bundle?>? = null+ val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) { code, data -> got = code to data }+ val bundle = Bundle().apply { putString("k", "v") }+ receiver.send(42, bundle)+ org.robolectric.Shadows.shadowOf(Looper.getMainLooper()).idle()+ assertEquals(42, got?.first)+ assertEquals("v", got?.second?.getString("k"))+ }++ @Test fun achievementDataDefaultsAndEquality() {+ val a = Achievement("id1", "Name", "Desc")+ assertEquals(1, a.targetProgress); assertFalse(a.isSecret)+ val status = AchievementStatus(a, progress = 0, isUnlocked = false)+ assertEquals(a, status.achievement)+ assertEquals(Achievement("id1", "Name", "Desc"), a)+ }+}+[email protected](entities = [ManyManyMatching::class], version = 1, exportSchema = false)+abstract class LibraryState2TestDb : RoomDatabase() {+ abstract fun matchingDao(): MatchingDao+}