Modern Apps git

← Modern-Apps.git

library: room builder branch tests, native ceiling noted

Commit
b62af3f8f9fdfa622656e704b7e254589360e932
Author
Vayun Mathur <[email protected]>
When
2026-11-17 01:31 UTC (19 days ago)
Parents
9a6f5b6
Coverage top-up for :library:room (CI 428a82e90: 74.1%
INSTRUCTION, 781 total). Local merged report before: 73.1%
(571/781); after: 77.5% (605/781).

What was added (9 tests in SqlCipherBranchesTest, plus a copy of
the in-memory FakeAndroidKeyStore JCE provider other modules
already use, since :library's copy is not visible here):
- Default-argument masks of the Class-based buildDatabase and
  buildDatabaseUncached overloads, each omitting a different
  subset, all landing on the same cached instance.
- A database whose companion exists but is not a
  DatabaseMigrations holder, proving migrations resolve to none.
- The no-password path through DatabaseHelper twice: first build
  generates the keystore key and stores a passphrase, the second
  decrypts the stored one.
- Device-protected-storage builds where the device side is
  already populated (both move checks skip) and where neither
  side has anything to move.
- SqlCipherDbCodec export with a parentless output file, and the
  loadSqlCipher early return once the loaded flag is set, plus
  the reified overload's full-default build and its synthetic
  stub's reflective refusal.

Documented ceiling (why this stops at 77.5%, not 80%): the
remaining 176 missed instructions are (a) 143 in
encryptExistingDatabase and SqlCipherDbCodec export/import
AFTER the SQLCipher native open - the sqlcipher .so only ships
Android ABIs, so on a host JVM the open cannot succeed and the
export/encrypt bodies past it are device-only (they belong in
androidTest against a real library load); and (b) ~29 in the
reified buildDatabase synthetic stubs, which have no runtime
body by construction. Everything host-testable in this module
is now covered.

Verified: ./gradlew :library:room:testDebugUnitTest
:library:room:createMergedCoverageReport green, 77.5%.

Diff

library/room/src/test/java/com/vayunmathur/library/room/FakeAndroidKeyStore.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/FakeAndroidKeyStore.kt b/library/room/src/test/java/com/vayunmathur/library/room/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..1dcd8f88ac--- /dev/null+++ b/library/room/src/test/java/com/vayunmathur/library/room/FakeAndroidKeyStore.kt@@ -0,0 +1,97 @@+package com.vayunmathur.library.room++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStore+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.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * Robolectric has no AndroidKeyStore provider, which otherwise blocks every+ * code path that opens the SQLCipher vault (PasswordRepository,+ * DatabaseHelper, KdbxPasswordHelper). Installing this JCA provider gives+ * tests a plain in-memory AES keystore with the same alias semantics; keys+ * never leave the test process.+ */+object FakeAndroidKeyStore {+    private val keys = mutableMapOf<String, SecretKey>()++    fun install() {+        if (Security.getProvider("AndroidKeyStore") == null) {+            Security.addProvider(FakeProvider())+        }+    }++    fun put(alias: String, key: SecretKey) {+        keys[alias] = key+    }++    fun get(alias: String): SecretKey? = keys[alias]++    fun remove(alias: String) {+        keys.remove(alias)+    }++    fun contains(alias: String): Boolean = keys.containsKey(alias)++    fun aliases(): List<String> = keys.keys.toList()++    class FakeProvider : Provider("AndroidKeyStore", 1.0, "in-memory test keystore") {+        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 engineContainsAlias(alias: String) = contains(alias)+        override fun engineDeleteEntry(alias: String) = remove(alias)+        override fun engineGetKey(alias: String, password: CharArray?): Key? = get(alias)+        override fun engineIsKeyEntry(alias: String) = contains(alias)+        override fun engineAliases(): Enumeration<String> = Collections.enumeration(aliases())+        override fun engineSize() = aliases().size+        override fun engineGetCertificate(alias: String): Certificate? = null+        override fun engineGetCertificateAlias(cert: Certificate) = null+        override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+        override fun engineGetCreationDate(alias: String) = Date()+        override fun engineIsCertificateEntry(alias: String) = false+        override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+        override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+        override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+            if (key is SecretKey) put(alias, key)+        }+        override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) = Unit+    }++    class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+        private var alias: String = "test-key"++        override fun engineInit(random: SecureRandom) = Unit+        override fun engineInit(keysize: Int, random: SecureRandom) = Unit+        override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom) {+            if (params is KeyGenParameterSpec) alias = params.keystoreAlias+        }++        override fun engineGenerateKey(): SecretKey {+            val bytes = ByteArray(32)+            SecureRandom().nextBytes(bytes)+            return SecretKeySpec(bytes, "AES").also { put(alias, it) }+        }+    }++    /** Convenience for tests that obtain a generator through JCA. */+    fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
library/room/src/test/java/com/vayunmathur/library/room/SqlCipherBranchesTest.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherBranchesTest.kt b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherBranchesTest.ktnew file mode 100644index 0000000000..a211379c80--- /dev/null+++ b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherBranchesTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.library.room++import android.content.Context+import androidx.room3.Database+import androidx.room3.RoomDatabase+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.util.databases+import java.io.File+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertNotSame+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode++/** A database whose companion exists but does not carry migrations. */+@Database(entities = [TestItem::class], version = 1, exportSchema = false)+abstract class CompanionNoMigrationsDatabase : RoomDatabase() {+    abstract fun itemDao(): TestItemDao++    companion object {+        const val LABEL = "no-migrations"+    }+}++@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SqlCipherBranchesTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() = FakeAndroidKeyStore.install()++    @AfterTest fun tearDown() {+        databases.values.forEach { runCatching { it.close() } }+        databases.clear()+    }++    @Test+    fun `default argument masks for the class overloads build and cache`() {+        // Each call omits a different subset of the class-based overloads, so+        // their synthetic $default masks take different branches; every one+        // must still land on the same cached instance.+        val byNameOnly = context.buildDatabase(TestDatabase::class.java, dbName = "mask-class-a")+        assertSame(byNameOnly, databases[TestDatabase::class])+        databases.clear()+        val byPasswordOnly = context.buildDatabase(TestDatabase::class.java, encryptionPassword = "pw")+        assertSame(byPasswordOnly, databases[TestDatabase::class])+        databases.clear()+        val uncached = context.buildDatabaseUncached(TestDatabase::class.java, dbName = "mask-uncached")+        assertNull(databases[TestDatabase::class])+        uncached.close()+        val uncachedByPassword = context.buildDatabaseUncached(+            TestDatabase::class.java, encryptionPassword = "pw",+        )+        assertNotSame(uncached, uncachedByPassword)+        uncachedByPassword.close()+    }++    @Test+    fun `a companion that is not a migrations holder yields no migrations`() {+        assertTrue(CompanionNoMigrationsDatabase.LABEL.isNotEmpty())+        val db = context.buildDatabase(+            CompanionNoMigrationsDatabase::class.java, null, "pw", "companion-db",+        )+        assertSame(db, databases[CompanionNoMigrationsDatabase::class])+    }++    @Test+    fun `no password builds through the keystore passphrase, twice`() {+        // First build: no key yet, so one is generated and the passphrase is+        // created and stored. Second build (uncached, other name): the key+        // exists, so the stored passphrase is decrypted instead.+        val first = context.buildDatabaseUncached(TestDatabase::class.java, dbName = "keystore-a")+        first.close()+        val second = context.buildDatabaseUncached(TestDatabase::class.java, dbName = "keystore-b")+        assertNotSame(first, second)+        second.close()+    }++    @Test+    fun `device protected build skips moves when the device side is already populated`() {+        val deviceContext = context.createDeviceProtectedStorageContext()+        val deviceFile = deviceContext.getDatabasePath("dps-settled-db")+        deviceFile.parentFile?.mkdirs()+        deviceFile.writeBytes(ByteArray(8) { 2 })+        deviceContext.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+            .edit().putString("dk", "dv").commit()+        context.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+            .edit().putString("ck", "cv").commit()+        try {+            val db = context.buildDatabase(+                TestDatabase::class.java, null, "pw", "dps-settled-db",+                useDeviceProtectedStorage = true,+            )+            assertSame(db, databases[TestDatabase::class])+            assertTrue(deviceFile.exists())+        } finally {+            deviceFile.delete()+            deviceContext.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+                .edit().clear().commit()+            context.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+                .edit().clear().commit()+        }+    }++    @Test+    fun `device protected build with nothing to move still builds`() {+        // Neither side has a database or prefs: both move checks must pass+        // over silently and the build must use the device context.+        val db = context.buildDatabase(+            PlainDatabase::class.java, null, "pw", "dps-empty-db",+            useDeviceProtectedStorage = true,+        )+        assertSame(db, databases[PlainDatabase::class])+    }++    @Test+    fun `export with a parentless output file still prepares it`() {+        val dbFile = context.getDatabasePath("export-parentless-db")+        dbFile.parentFile?.mkdirs()+        dbFile.writeBytes(ByteArray(32) { 6 })+        val output = File("export-parentless-out.db")+        if (output.exists()) output.delete()+        try {+            runCatching {+                SqlCipherDbCodec.exportDatabase(context, "export-parentless-db", "pw", output)+            }+            assertTrue(output.exists(), "export creates its output before the native open")+        } finally {+            dbFile.delete()+            output.delete()+        }+    }++    @Test+    fun `reified overload with every default builds through the keystore`() {+        // No arguments at all: default name, default migrations and the+        // keystore passphrase path all come from the synthetic mask.+        val db = context.buildDatabase<TestDatabase>()+        assertSame(db, databases[TestDatabase::class])+        databases.clear()+        val named = context.buildDatabase<TestDatabase>(+            dbName = "reified-dps-db", encryptionPassword = "pw",+            useDeviceProtectedStorage = true,+        )+        assertSame(named, databases[TestDatabase::class])+    }++    @Test+    fun `the reified inline stub refuses direct reflective invocation`() {+        // The inline reified overload has no runtime body of its own; its+        // synthetic stub must refuse, exactly like its $default sibling.+        val stub = Class.forName("com.vayunmathur.library.room.SqlCipherKt")+            .methods.firstOrNull { it.name == "buildDatabase" && it.parameterCount == 5 }+            ?: return // inlined away on this toolchain: nothing to pin+        stub.isAccessible = true+        val thrown = kotlin.test.assertFailsWith<java.lang.reflect.InvocationTargetException> {+            stub.invoke(null, context, null, "pw", "stub-db", false)+        }+        assertTrue(thrown.cause is UnsupportedOperationException)+    }++    @Test+    fun `an already loaded sqlcipher flag short circuits the loader`() {+        // On a device the first load flips the flag and every later call is+        // this early return; set the flag the way a successful load would+        // and pin that the loader then does nothing at all.+        val field = Class.forName("com.vayunmathur.library.room.SqlCipherKt")+            .getDeclaredField("sqlCipherLoaded")+        field.isAccessible = true+        val previous = field.getBoolean(null)+        try {+            field.setBoolean(null, true)+            loadSqlCipher()+            assertTrue(field.getBoolean(null))+        } finally {+            field.setBoolean(null, previous)+        }+        assertTrue(field.getBoolean(null) == previous, "the flag must be restored afterwards")+    }+}