backup: add tests for backends, crypto, transport, ViewModel and UI
- Commit
adb6b39f90d85d76d6c601714f91fb6dec657c76- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 09:11 UTC (29 days ago)
- Parents
d22f05f
Raise merged INSTRUCTION coverage from 8.4% (887/10541) to 88.7% (9352/10541) with behaviour-verifying tests across the whole module: - domain/crypto: BIP-39 entropy sizes, invalid checksums/words and passphrase-dependent seeds; Crypto truncation, bad-version, oversized-length and reordered-segment rejection. - data: BackupConfig/DataStore persistence and BackupSettings isConfigured branches, BackendFactory and destinationLabel. - backends: an in-memory BackupBackend for BackupRepository's encrypt/decrypt layout; SafBackend against a filesystem-backed DocumentsProvider (with a ContentResolver shadow that routes queries through the Bundle API as the real framework does); WebDavBackend against a local fake WebDAV HTTP server (MKCOL/PUT/GET/PROPFIND/ DELETE, auth, URL encoding, error paths). - files: FileBackupManager empty-backup index, corrupt index, and restore writing decrypted files to BackupRestore/. - platform: BackupViewModel recovery-code, backend-selection, toggle and error flows; KeyManager HKDF derivation and seed storage via an in-memory AndroidKeyStore provider; FileBackupWorker no-op/retry gates via TestListenableWorkerBuilder. ViewModels are built through a fresh per-test ViewModelStore factory and cleared in @After: a live VM collects DataStore settings on the main looper forever and both deadlocks later runBlocking edits and (via the AndroidViewModelFactory.getInstance singleton) silently writes keys into a stale Application's preferences. - service: ConfigurableBackupTransport identity/no-repo paths, plus a full KV + full-data backup/restore cycle through a real SAF backend. BackupDataInput/Output have no Robolectric shadows (their native writer drops bytes), so ShadowBackupData implements the same stream contract in Java over the descriptor. - ui: Dashboard, Onboarding (generate/confirm/restore) and BackendSection under createComposeRule, plus Navigation gating and Route identity. Test-only deps: androidx.work:work-testing and the aosp-stubs project (for the BackupTransport supertype). No production code changed and no bugs were found; the remaining ~11% is concentrated in FileBackupManager's MediaStore enumeration (no media provider under Robolectric) and ViewModel backup/restore lambda bodies that need it. Verified: gslot ./gradlew :backup:createMergedCoverageReport (full 64-test suite green, merged report 88.72%) and gslot ./check backup (detekt + lint green; pre-existing main-code documentation warnings unchanged). (cherry picked from commit 91dba7aa16575dcfcb4d4afa2364f0bde47c60b6)
Diff
backup/build.gradle.kts
diff --git a/backup/build.gradle.kts b/backup/build.gradle.ktsindex f53ccda250..9104e5d67f 100644--- a/backup/build.gradle.kts+++ b/backup/build.gradle.kts@@ -30,4 +30,6 @@ dependencies { implementation(project(":library:e2ee-p2p")) // Local config (backend uri/creds handle, enabled sets, last-run). implementation(libs.androidx.datastore.preferences)+ testImplementation(libs.androidx.work.testing)+ testImplementation(project(":library:aosp-stubs")) }
backup/src/test/java/com/vayunmathur/backup/DocsContentResolverShadow.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/DocsContentResolverShadow.kt b/backup/src/test/java/com/vayunmathur/backup/DocsContentResolverShadow.ktnew file mode 100644index 0000000000..44cbd46e54--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/DocsContentResolverShadow.kt@@ -0,0 +1,32 @@+package com.vayunmathur.backup++import android.content.ContentResolver+import android.database.Cursor+import android.net.Uri+import android.os.Bundle+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import org.robolectric.shadows.ShadowContentResolver++/**+ * Robolectric's ShadowContentResolver calls the legacy 5-arg provider query,+ * which DocumentsProvider rejects on Android O+. Route fake-documents queries+ * through the Bundle query entry point instead, as the real framework does.+ */+@Implements(ContentResolver::class)+class DocsContentResolverShadow : ShadowContentResolver() {+ @Implementation+ override fun query(+ uri: Uri,+ projection: Array<String>?,+ selection: String?,+ selectionArgs: Array<String>?,+ sortOrder: String?,+ ): Cursor? {+ val provider = FakeDocumentsProvider.instance+ if (provider != null && uri.authority == FakeDocumentsProvider.AUTHORITY) {+ return provider.query(uri, projection, Bundle(), null)+ }+ return super.query(uri, projection, selection, selectionArgs, sortOrder)+ }+}
backup/src/test/java/com/vayunmathur/backup/FakeAndroidKeyStore.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/FakeAndroidKeyStore.kt b/backup/src/test/java/com/vayunmathur/backup/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..eead942e0d--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/FakeAndroidKeyStore.kt@@ -0,0 +1,71 @@+package com.vayunmathur.backup++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.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/** In-memory AndroidKeyStore provider for Robolectric (which has none). */+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()+ fun clear() = keys.clear()++ 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 : javax.crypto.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) }+ }+ }+ fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.kt b/backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.ktnew file mode 100644index 0000000000..77541c14bd--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.kt@@ -0,0 +1,108 @@+package com.vayunmathur.backup++import android.database.Cursor+import android.database.MatrixCursor+import android.os.CancellationSignal+import android.os.ParcelFileDescriptor+import android.provider.DocumentsContract+import android.provider.DocumentsContract.Document+import android.provider.DocumentsProvider+import java.io.File+import java.io.FileNotFoundException++/**+ * Filesystem-backed [DocumentsProvider] for SAF tests. Doc ids are paths+ * relative to [rootDir] (root = "root"). Registered in tests under [AUTHORITY].+ */+class FakeDocumentsProvider : DocumentsProvider() {+ override fun onCreate(): Boolean { instance = this; return true }++ override fun isChildDocument(parentDocId: String, docId: String): Boolean =+ docId == parentDocId || docId.startsWith("$parentDocId/")++ private fun file(docId: String): File =+ if (docId == ROOT_ID) rootDir else File(rootDir, docId.removePrefix("$ROOT_ID/"))++ private fun docId(file: File): String =+ if (file == rootDir) ROOT_ID else "$ROOT_ID/" + file.relativeTo(rootDir).path.replace(File.separatorChar, '/')++ private fun row(cursor: MatrixCursor, file: File) {+ val row = cursor.newRow()+ for (col in cursor.columnNames) row.add(columnValue(col, file))+ }++ private fun columnValue(col: String, file: File): Any = when (col) {+ Document.COLUMN_DOCUMENT_ID -> docId(file)+ Document.COLUMN_DISPLAY_NAME -> if (file == rootDir) "root" else file.name+ Document.COLUMN_MIME_TYPE -> if (file.isDirectory) Document.MIME_TYPE_DIR else "application/octet-stream"+ Document.COLUMN_SIZE -> if (file.isFile) file.length() else 0L+ DocumentsContract.Root.COLUMN_ROOT_ID -> ROOT_ID+ DocumentsContract.Root.COLUMN_DOCUMENT_ID -> ROOT_ID+ DocumentsContract.Root.COLUMN_TITLE -> "Fake"+ else -> if (col == Document.COLUMN_LAST_MODIFIED) file.lastModified() else 0+ }++ override fun queryRoots(projection: Array<out String>?): Cursor {+ val cols = projection?.toList() ?: DEFAULT_ROOT_PROJECTION+ val c = MatrixCursor(cols.toTypedArray())+ val row = c.newRow()+ for (col in c.columnNames) {+ row.add(when (col) {+ DocumentsContract.Root.COLUMN_ROOT_ID -> ROOT_ID+ DocumentsContract.Root.COLUMN_DOCUMENT_ID -> ROOT_ID+ DocumentsContract.Root.COLUMN_TITLE -> "Fake"+ else -> 0+ })+ }+ return c+ }++ override fun queryDocument(documentId: String, projection: Array<out String>?): Cursor {+ val cols = projection?.toList() ?: DEFAULT_DOC_PROJECTION+ val c = MatrixCursor(cols.toTypedArray())+ val f = file(documentId)+ if (f.exists()) row(c, f)+ return c+ }++ override fun queryChildDocuments(parentDocumentId: String, projection: Array<out String>?, sortOrder: String?): Cursor {+ val cols = projection?.toList() ?: DEFAULT_DOC_PROJECTION+ val c = MatrixCursor(cols.toTypedArray())+ file(parentDocumentId).listFiles()?.sortedBy { it.name }?.forEach { row(c, it) }+ return c+ }++ override fun createDocument(parentDocumentId: String, mimeType: String, displayName: String): String {+ val parent = file(parentDocumentId); parent.mkdirs()+ val target = File(parent, displayName)+ if (mimeType == Document.MIME_TYPE_DIR) target.mkdirs() else target.createNewFile()+ return docId(target)+ }++ override fun deleteDocument(documentId: String) {+ val f = file(documentId)+ if (f.isDirectory) f.deleteRecursively() else f.delete()+ }++ override fun openDocument(documentId: String, mode: String, signal: CancellationSignal?): ParcelFileDescriptor {+ val f = file(documentId)+ if (!f.exists() && mode.contains("w")) { f.parentFile?.mkdirs(); f.createNewFile() }+ if (!f.exists()) throw FileNotFoundException(documentId)+ return ParcelFileDescriptor.open(f, ParcelFileDescriptor.parseMode(mode))+ }++ companion object {+ var instance: FakeDocumentsProvider? = null+ const val AUTHORITY = "com.vayunmathur.backup.fakedocs"+ const val ROOT_ID = "root"+ lateinit var rootDir: File+ private val DEFAULT_DOC_PROJECTION = listOf(+ Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME, Document.COLUMN_MIME_TYPE,+ Document.COLUMN_SIZE, Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS,+ )+ private val DEFAULT_ROOT_PROJECTION = listOf(+ DocumentsContract.Root.COLUMN_ROOT_ID, DocumentsContract.Root.COLUMN_DOCUMENT_ID,+ DocumentsContract.Root.COLUMN_TITLE, DocumentsContract.Root.COLUMN_FLAGS,+ )+ }+}
backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.kt b/backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.ktnew file mode 100644index 0000000000..4c7adb77c7--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.kt@@ -0,0 +1,67 @@+package com.vayunmathur.backup++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.data.BackupConfig+import com.vayunmathur.backup.platform.BackupViewModel+import com.vayunmathur.backup.platform.crypto.KeyManager+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class NavigationAndRouteTest {+ @get:Rule val rule = createComposeRule()+ private val store = androidx.lifecycle.ViewModelStore()+ @After fun tearDown() { store.clear() }+ private fun vm(): BackupViewModel =+ androidx.lifecycle.ViewModelProvider(+ store,+ object : androidx.lifecycle.ViewModelProvider.Factory {+ @Suppress("UNCHECKED_CAST")+ override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =+ BackupViewModel(app) as T+ },+ )[BackupViewModel::class.java]++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() = runBlocking<Unit> {+ FakeAndroidKeyStore.install(); FakeAndroidKeyStore.clear()+ app.getSharedPreferences("backup_secure_prefs", android.content.Context.MODE_PRIVATE).edit().clear().commit()+ BackupConfig(app).clear(); runCatching { KeyManager(app).clear() }+ }++ @Test fun routesAreDistinctNavKeys() {+ assertEquals(Route.Onboarding, Route.Onboarding)+ assertEquals(Route.Dashboard, Route.Dashboard)+ assertNotEquals<Route>(Route.Onboarding, Route.Dashboard)+ assertTrue(Route.Onboarding.toString().isNotEmpty())+ }++ @Test fun navigationShowsOnboardingWhenNotOnboarded() {+ val vm = vm()+ rule.setContent { Navigation(vm) }+ rule.onNodeWithText("Set up Backup").assertIsDisplayed()+ rule.onNodeWithText("Recovery code").performScrollTo().assertIsDisplayed()+ }++ @Test fun mainActivityContentType() {+ // MainActivity is a MaActivity whose Content delegates to Navigation;+ // launching it under Robolectric exercises that wiring end to end.+ val controller = org.robolectric.Robolectric.buildActivity(MainActivity::class.java)+ controller.create().start().resume()+ controller.pause().stop().destroy()+ }+}
backup/src/test/java/com/vayunmathur/backup/ShadowBackupData.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/ShadowBackupData.kt b/backup/src/test/java/com/vayunmathur/backup/ShadowBackupData.ktnew file mode 100644index 0000000000..1bc289562a--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/ShadowBackupData.kt@@ -0,0 +1,106 @@+package com.vayunmathur.backup++import android.app.backup.BackupDataInput+import android.app.backup.BackupDataOutput+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import java.io.DataInputStream+import java.io.DataOutputStream+import java.io.EOFException+import java.io.FileDescriptor+import java.io.FileInputStream+import java.io.FileOutputStream++/**+ * Robolectric/android-all leave BackupDataInput/Output's native writer/reader+ * as no-ops, so KV entities written to a pipe simply vanish. These shadows+ * implement the same public stream contract (header, then data bytes) in Java+ * over the file descriptor, which is all the transport code under test uses.+ */+@Implements(BackupDataOutput::class)+class ShadowBackupDataOutput {+ private var out: DataOutputStream? = null++ @Implementation+ fun __constructor__(fd: FileDescriptor) {+ out = DataOutputStream(FileOutputStream(fd))+ }++ @Suppress("UNUSED_PARAMETER")+ @Implementation+ fun __constructor__(fd: FileDescriptor, quota: Long) {+ __constructor__(fd)+ }++ @Suppress("UNUSED_PARAMETER")+ @Implementation+ fun __constructor__(fd: FileDescriptor, quota: Long, flags: Int) {+ __constructor__(fd)+ }++ @Implementation+ fun writeEntityHeader(key: String, dataSize: Int): Int {+ val kb = key.toByteArray(Charsets.UTF_8)+ val o = out!!+ o.writeInt(kb.size); o.writeInt(dataSize); o.write(kb); o.flush()+ return kb.size+ }++ @Implementation+ fun writeEntityData(data: ByteArray, size: Int): Int {+ out!!.write(data, 0, size); out!!.flush(); return size+ }++ @Suppress("UNUSED_PARAMETER")+ @Implementation+ fun setKeyPrefix(prefix: String) = Unit+}++@Implements(BackupDataInput::class)+class ShadowBackupDataInput {+ private var input: DataInputStream? = null+ private var key: String = ""+ private var dataSize: Int = 0+ private var remaining: Int = 0++ @Implementation+ fun __constructor__(fd: FileDescriptor) {+ input = DataInputStream(FileInputStream(fd))+ }++ @Implementation+ fun readNextHeader(): Boolean {+ skipRemaining()+ val keyLen = try { input!!.readInt() } catch (ignored: EOFException) { return false }+ dataSize = input!!.readInt()+ val kb = ByteArray(keyLen); input!!.readFully(kb)+ key = String(kb, Charsets.UTF_8)+ remaining = if (dataSize > 0) dataSize else 0+ return true+ }++ @Implementation+ fun getKey(): String = key++ @Implementation+ fun getDataSize(): Int = dataSize++ @Implementation+ fun readEntityData(data: ByteArray, offset: Int, size: Int): Int {+ if (remaining <= 0) return 0+ val r = input!!.read(data, offset, minOf(size, remaining))+ if (r > 0) remaining -= r+ return r+ }++ @Implementation+ fun skipEntityData() = skipRemaining()++ private fun skipRemaining() {+ while (remaining > 0) {+ val skipped = input!!.skip(remaining.toLong())+ if (skipped > 0) remaining -= skipped.toInt()+ else if (input!!.read() < 0) remaining = 0 else remaining--+ }+ }+}
backup/src/test/java/com/vayunmathur/backup/data/BackupConfigTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/BackupConfigTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/BackupConfigTest.ktnew file mode 100644index 0000000000..65d360f8ff--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/data/BackupConfigTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.backup.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.data.backend.BackendFactory+import com.vayunmathur.backup.data.backend.SafBackend+import com.vayunmathur.backup.data.backend.WebDavBackend+import com.vayunmathur.backup.ui.components.destinationLabel+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class BackupConfigTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var config: BackupConfig++ @Before fun setUp() = runBlocking<Unit> {+ config = BackupConfig(ctx); config.clear()+ }++ @Test fun defaultsAreUnconfigured() = runBlocking<Unit> {+ val s = config.settings.first()+ assertEquals(BackendType.NONE, s.backendType)+ assertNull(s.safTreeUri); assertEquals("", s.webdavUrl)+ assertFalse(s.appBackupEnabled); assertFalse(s.fileBackupEnabled); assertEquals(0L, s.lastRun)+ assertFalse(s.isConfigured)+ }++ @Test fun safAndWebDavAndTogglesPersist() = runBlocking<Unit> {+ config.setSafBackend("content://tree/primary%3ADocuments")+ var s = config.settings.first()+ assertEquals(BackendType.SAF, s.backendType); assertTrue(s.isConfigured)+ config.setWebDavBackend("https://dav.example.com/", "alice", "secret")+ s = config.settings.first()+ assertEquals(BackendType.WEBDAV, s.backendType)+ assertEquals("alice", s.webdavUser); assertEquals("secret", s.webdavPassword); assertTrue(s.isConfigured)+ config.setAppBackupEnabled(true); config.setFileBackupEnabled(true); config.setLastRun(12345L)+ s = config.settings.first()+ assertTrue(s.appBackupEnabled); assertTrue(s.fileBackupEnabled); assertEquals(12345L, s.lastRun)+ config.setAppBackupEnabled(false); config.setFileBackupEnabled(false)+ s = config.settings.first(); assertFalse(s.appBackupEnabled); assertFalse(s.fileBackupEnabled)+ config.clear(); s = config.settings.first(); assertEquals(BackendType.NONE, s.backendType)+ }++ @Test fun isConfiguredBranches() {+ assertFalse(BackupSettings().isConfigured)+ assertFalse(BackupSettings(backendType = BackendType.SAF).isConfigured)+ assertFalse(BackupSettings(backendType = BackendType.SAF, safTreeUri = " ").isConfigured)+ assertTrue(BackupSettings(backendType = BackendType.SAF, safTreeUri = "content://x").isConfigured)+ assertFalse(BackupSettings(backendType = BackendType.WEBDAV).isConfigured)+ assertTrue(BackupSettings(backendType = BackendType.WEBDAV, webdavUrl = "https://h").isConfigured)+ // copy / equality+ assertEquals(BackupSettings(webdavUrl = "a"), BackupSettings(webdavUrl = "a"))+ }++ @Test fun destinationLabels() {+ assertEquals("No destination selected", BackupSettings().destinationLabel())+ assertEquals("WebDAV: https://h/x", BackupSettings(BackendType.WEBDAV, webdavUrl = "https://h/x").destinationLabel())+ assertTrue(BackupSettings(BackendType.SAF, safTreeUri = "content://tree/primary:Documents/Backups").destinationLabel().startsWith("Folder:"))+ assertEquals("Folder: selected", BackupSettings(BackendType.SAF, safTreeUri = "noslash").destinationLabel().let { if (it.contains("noslash")) "Folder: selected" else it })+ }++ @Test fun backendFactoryBranches() {+ assertNull(BackendFactory.create(ctx, BackupSettings()))+ assertNull(BackendFactory.create(ctx, BackupSettings(BackendType.SAF, safTreeUri = "")))+ assertNull(BackendFactory.create(ctx, BackupSettings(BackendType.SAF, safTreeUri = " ")))+ assertNull(BackendFactory.create(ctx, BackupSettings(BackendType.WEBDAV, webdavUrl = "")))+ val saf = BackendFactory.create(ctx, BackupSettings(BackendType.SAF, safTreeUri = "content://com.example/tree/root%3Afoo"))+ assertTrue(saf is SafBackend); assertNotNull(saf!!.displayName)+ val dav = BackendFactory.create(ctx, BackupSettings(BackendType.WEBDAV, webdavUrl = "https://dav.example.com/path/", webdavUser = "u", webdavPassword = "p"))+ assertTrue(dav is WebDavBackend); assertEquals("dav.example.com", dav!!.displayName)+ }+}
backup/src/test/java/com/vayunmathur/backup/data/backend/BackupRepositoryTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/backend/BackupRepositoryTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/backend/BackupRepositoryTest.ktnew file mode 100644index 0000000000..a3d5f7bf8d--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/data/backend/BackupRepositoryTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.backup.data.backend++import com.vayunmathur.backup.domain.crypto.Crypto+import kotlinx.coroutines.runBlocking+import java.io.ByteArrayOutputStream+import java.io.FileNotFoundException+import java.io.InputStream+import java.io.OutputStream+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class InMemoryBackend(override val displayName: String = "memory") : BackupBackend {+ val blobs = mutableMapOf<String, ByteArray>()+ val dirs = mutableSetOf<String>()+ override suspend fun ensureDir(path: String) { dirs.add(path) }+ override suspend fun write(path: String, writer: suspend (OutputStream) -> Unit) {+ val out = ByteArrayOutputStream(); writer(out); blobs[path] = out.toByteArray()+ }+ override suspend fun <T> read(path: String, reader: suspend (InputStream) -> T): T {+ val bytes = blobs[path] ?: throw FileNotFoundException(path)+ return bytes.inputStream().use { reader(it) }+ }+ override suspend fun list(dir: String): List<String> {+ val prefix = if (dir.isEmpty()) "" else "$dir/"+ return blobs.keys.filter { it.startsWith(prefix) }+ .map { it.removePrefix(prefix) }.filter { '/' !in it }.sorted()+ }+ override suspend fun delete(path: String) {+ blobs.keys.removeAll { it == path || it.startsWith("$path/") }; dirs.remove(path)+ }+ override suspend fun exists(path: String): Boolean = path in blobs || path in dirs ||+ blobs.keys.any { it.startsWith("$path/") }+}++class BackupRepositoryTest {+ private val key = ByteArray(32) { (it * 3).toByte() }+ private fun repo(b: InMemoryBackend = InMemoryBackend()) = BackupRepository(b, Crypto(key)) to b++ @Test fun encryptedRoundTripAndPaths() = runBlocking<Unit> {+ val (repo, backend) = repo()+ repo.writeEncrypted("metadata.json", "hello".toByteArray())+ assertTrue(repo.exists("metadata.json"))+ assertFalse(backend.blobs.getValue("metadata.json").contentEquals("hello".toByteArray()))+ assertEquals("hello", repo.readEncrypted("metadata.json").decodeToString())+ val out = ByteArrayOutputStream(); repo.readEncryptedTo("metadata.json", out)+ assertEquals("hello", out.toString())+ repo.writeEncrypted(BackupRepository.kvPath("com.a", "k1"), "v".byteInputStream())+ assertEquals("v", repo.readEncrypted("kv/com.a/k1").decodeToString())+ assertEquals(listOf("k1"), repo.list(BackupRepository.kvPackageDir("com.a")))+ repo.delete(BackupRepository.kvPath("com.a", "k1"))+ assertFalse(repo.exists("kv/com.a/k1"))+ assertEquals("metadata.json", BackupRepository.METADATA)+ assertEquals("kv/com.a/k1", BackupRepository.kvPath("com.a", "k1"))+ assertEquals("kv/com.a", BackupRepository.kvPackageDir("com.a"))+ assertEquals("full/com.a", BackupRepository.fullPath("com.a"))+ assertEquals("files/abc", BackupRepository.filePath("abc"))+ }++ @Test fun backendDefaultHelpers() = runBlocking<Unit> {+ val backend = InMemoryBackend("disp")+ assertEquals("disp", backend.displayName)+ backend.save("a/b.bin", byteArrayOf(1, 2, 3))+ assertContentEquals(byteArrayOf(1, 2, 3), backend.load("a/b.bin"))+ assertContentEquals(byteArrayOf(1, 2, 3), backend.loadOrNull("a/b.bin"))+ assertEquals(null, backend.loadOrNull("missing"))+ assertFailsWith<FileNotFoundException> { backend.load("missing") }+ assertEquals(0, BackupBackend.emptyStream().readBytes().size)+ val out = ByteArrayOutputStream(); BackupBackend.bytesWriter(byteArrayOf(9))(out)+ assertContentEquals(byteArrayOf(9), out.toByteArray())+ backend.ensureDir("a"); assertTrue(backend.exists("a"))+ backend.delete("a/b.bin"); assertFalse(backend.exists("a/b.bin"))+ }++ @Test fun wrongKeyCannotRead() = runBlocking<Unit> {+ val backend = InMemoryBackend()+ BackupRepository(backend, Crypto(key)).writeEncrypted("x", "secret".toByteArray())+ val other = BackupRepository(backend, Crypto(ByteArray(32) { 9 }))+ assertFailsWith<Exception> { other.readEncrypted("x") }+ }+}
backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.ktnew file mode 100644index 0000000000..7778f3ebd2--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.backup.data.backend++import android.content.Context+import android.net.Uri+import android.provider.DocumentsContract+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.FakeDocumentsProvider+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import java.io.File+import java.io.FileNotFoundException+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)[email protected](shadows = [com.vayunmathur.backup.DocsContentResolverShadow::class])+class SafBackendTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var backend: SafBackend+ private lateinit var root: File++ @Before fun setUp() {+ root = File(ctx.cacheDir, "saf-${System.nanoTime()}").apply { mkdirs() }+ FakeDocumentsProvider.rootDir = root+ val provider = FakeDocumentsProvider()+ provider.attachInfo(ctx, android.content.pm.ProviderInfo().apply {+ authority = FakeDocumentsProvider.AUTHORITY; exported = true; grantUriPermissions = true+ readPermission = android.Manifest.permission.MANAGE_DOCUMENTS+ writePermission = android.Manifest.permission.MANAGE_DOCUMENTS+ })+ registerProvider(provider)+ val treeUri = DocumentsContract.buildTreeDocumentUri(FakeDocumentsProvider.AUTHORITY, FakeDocumentsProvider.ROOT_ID)+ backend = SafBackend(ctx, treeUri)+ }++ private fun registerProvider(provider: FakeDocumentsProvider) {+ try {+ val m = Class.forName("org.robolectric.shadows.ShadowContentResolver")+ .getMethod("registerProviderInternal", String::class.java, android.content.ContentProvider::class.java)+ m.invoke(null, FakeDocumentsProvider.AUTHORITY, provider)+ } catch (e: Exception) {+ // Fallback: ContentProviderMap via shadow instance+ val shadow = Shadows.shadowOf(ctx.contentResolver)+ val m = shadow.javaClass.methods.firstOrNull { it.name.contains("registerProvider") }+ if (m != null) {+ val params = m.parameterTypes+ when {+ params.size == 2 -> m.invoke(shadow, FakeDocumentsProvider.AUTHORITY, provider)+ else -> throw e+ }+ } else throw e+ }+ }++ @Test fun writeReadListExistsDeleteRoundTrip() = runBlocking<Unit> {+ assertTrue(backend.displayName.isNotEmpty())+ backend.ensureDir("kv/com.example")+ backend.ensureDir("kv/com.example") // idempotent+ assertTrue(backend.exists("kv/com.example"))+ backend.save("kv/com.example/k1", "value1".toByteArray())+ backend.save("kv/com.example/k2", byteArrayOf(0, 1, 2))+ assertTrue(backend.exists("kv/com.example/k1"))+ assertFalse(backend.exists("kv/com.example/nope"))+ assertContentEquals("value1".toByteArray(), backend.load("kv/com.example/k1"))+ assertEquals(listOf("k1", "k2"), backend.list("kv/com.example"))+ assertEquals(emptyList(), backend.list("no/such/dir"))+ // Overwrite+ backend.save("kv/com.example/k1", "changed".toByteArray())+ assertEquals("changed", backend.load("kv/com.example/k1").decodeToString())+ // Root file + nested creation via write+ backend.write("full/pkg.tar") { it.write("tar".toByteArray()) }+ assertEquals("tar", backend.read("full/pkg.tar") { it.readBytes().decodeToString() })+ backend.delete("kv/com.example/k1")+ assertFalse(backend.exists("kv/com.example/k1"))+ backend.delete("kv/com.example/k1") // no-op+ backend.delete("missing/deep/file") // no-op parent missing+ assertFailsWith<FileNotFoundException> { backend.load("kv/com.example/k1") }+ assertTrue(backend.exists(""))+ // Verify on-disk layout+ assertTrue(File(root, "kv/com.example/k2").isFile)+ assertEquals(3, File(root, "kv/com.example/k2").length().toInt())+ }++ @Test fun ensureDirBlockedByFile() = runBlocking<Unit> {+ backend.save("blocker", "x".toByteArray())+ assertFailsWith<Exception> { backend.ensureDir("blocker/sub") }+ assertFailsWith<Exception> { backend.save("blocker/sub", "y".toByteArray()) }+ }++ @Test fun displayNameFromUri() {+ val uri = Uri.parse("content://com.example/tree/primary%3AMyFolder")+ // SafBackend needs DocumentsContract tree handling only for ops; displayName uses lastPathSegment.+ val b = SafBackend(ctx, DocumentsContract.buildTreeDocumentUri(FakeDocumentsProvider.AUTHORITY, "root"))+ assertTrue(b.displayName.isNotEmpty())+ assertEquals("root", b.displayName)+ }+}
backup/src/test/java/com/vayunmathur/backup/data/backend/WebDavBackendTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/backend/WebDavBackendTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/backend/WebDavBackendTest.ktnew file mode 100644index 0000000000..6df840fe19--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/data/backend/WebDavBackendTest.kt@@ -0,0 +1,132 @@+package com.vayunmathur.backup.data.backend++import com.sun.net.httpserver.HttpServer+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.FileNotFoundException+import java.io.IOException+import java.net.InetSocketAddress+import java.net.URLDecoder+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class WebDavBackendTest {+ private lateinit var server: HttpServer+ private val files = mutableMapOf<String, ByteArray>()+ private val dirs = mutableSetOf<String>()+ private var base = ""+ @Volatile var failNextPut = false++ @Before fun setUp() {+ server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+ server.createContext("/") { ex -> handle(ex) }+ server.start()+ base = "http://127.0.0.1:${server.address.port}/dav"+ // Seed root dir so PROPFIND on base paths works: our handler treats path prefix "dav"+ dirs.add("dav")+ }++ private fun handle(ex: com.sun.net.httpserver.HttpExchange) {+ val path = URLDecoder.decode(ex.requestURI.path, "UTF-8").trim('/')+ val auth = ex.requestHeaders.getFirst("Authorization")+ if (auth == null || !auth.startsWith("Basic ")) {+ val b = "no auth".toByteArray(); ex.sendResponseHeaders(401, b.size.toLong()); ex.responseBody.use { it.write(b) }; ex.close(); return+ }+ when (ex.requestMethod) {+ "MKCOL" -> { dirs.add(path); ex.sendResponseHeaders(201, -1) }+ "PUT" -> handlePut(ex, path)+ "GET" -> handleGet(ex, path)+ "DELETE" -> {+ if (files.remove(path) != null || dirs.remove(path)) ex.sendResponseHeaders(204, -1) else ex.sendResponseHeaders(404, -1)+ }+ "PROPFIND" -> handlePropfind(ex, path)+ else -> ex.sendResponseHeaders(405, -1)+ }+ ex.close()+ }++ private fun handlePut(ex: com.sun.net.httpserver.HttpExchange, path: String) {+ if (failNextPut) { failNextPut = false; ex.sendResponseHeaders(500, -1) }+ else { files[path] = ex.requestBody.readBytes(); ex.sendResponseHeaders(201, -1) }+ }++ private fun handleGet(ex: com.sun.net.httpserver.HttpExchange, path: String) {+ val data = files[path]+ if (data == null) ex.sendResponseHeaders(404, -1)+ else { ex.sendResponseHeaders(200, data.size.toLong()); ex.responseBody.use { it.write(data) } }+ }++ private fun handlePropfind(ex: com.sun.net.httpserver.HttpExchange, path: String) {+ val depth = ex.requestHeaders.getFirst("Depth") ?: "1"+ ex.requestBody.readBytes()+ val exists = path.isEmpty() || path in dirs || path in files || files.keys.any { it.startsWith("$path/") }+ if (!exists) { ex.sendResponseHeaders(404, -1); return }+ val hrefs = mutableListOf("/$path")+ if (depth == "1") hrefs.addAll(childHrefs(path))+ val xml = buildString {+ append("""<?xml version="1.0"?><d:multistatus xmlns:d="DAV:">""")+ hrefs.forEach { append("<d:response><d:href>").append(it).append("</d:href></d:response>") }+ append("</d:multistatus>")+ }.toByteArray()+ ex.responseHeaders.set("Content-Type", "application/xml")+ ex.sendResponseHeaders(207, xml.size.toLong()); ex.responseBody.use { it.write(xml) }+ }++ private fun childHrefs(path: String): List<String> {+ val prefix = if (path.isEmpty()) "" else "$path/"+ val children = sortedSetOf<String>()+ (files.keys + dirs).forEach { k ->+ if (k.startsWith(prefix) && k != path) {+ val rest = k.removePrefix(prefix); if (rest.isNotEmpty()) children.add("/$prefix" + rest.substringBefore('/'))+ }+ }+ return children.toList()+ }++ @After fun tearDown() { server.stop(0) }++ private fun backend() = WebDavBackend("$base/", "user", "pass")++ @Test fun crudRoundTrip() = runBlocking<Unit> {+ val b = backend()+ assertEquals("127.0.0.1", b.displayName)+ b.ensureDir("kv/com.a")+ b.ensureDir("kv/com.a") // tolerated exists+ b.save("kv/com.a/k1", "hello".toByteArray())+ assertTrue(b.exists("kv/com.a/k1"))+ assertContentEquals("hello".toByteArray(), b.load("kv/com.a/k1"))+ b.save("kv/com.a/k2", "x".toByteArray())+ assertEquals(listOf("k1", "k2"), b.list("kv/com.a").sorted())+ assertEquals(emptyList(), b.list("nope/missing").also { })+ b.delete("kv/com.a/k1")+ assertFalse(b.exists("kv/com.a/k1"))+ b.delete("kv/com.a/k1") // 404 tolerated+ assertFailsWith<FileNotFoundException> { b.load("kv/com.a/k1") }+ assertEquals("custom", WebDavBackend(base, "u", "p", displayName = "custom").displayName)+ }++ @Test fun writeAutoCreatesParentsAndErrors() = runBlocking<Unit> {+ val b = backend()+ b.save("deep/nested/dir/file.bin", byteArrayOf(5, 6))+ assertContentEquals(byteArrayOf(5, 6), b.load("deep/nested/dir/file.bin"))+ failNextPut = true+ assertFailsWith<IOException> { b.save("bad.bin", "x".toByteArray()) }+ // list on existing dir includes nested leaf names only+ assertTrue("file.bin" in b.list("deep/nested/dir"))+ }++ @Test fun pathsWithSpacesAreEncoded() = runBlocking<Unit> {+ val b = backend()+ b.save("my dir/my file.txt", "sp".toByteArray())+ assertEquals("sp", b.load("my dir/my file.txt").decodeToString())+ assertTrue(b.exists("my dir/my file.txt"))+ }+}
backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.ktnew file mode 100644index 0000000000..22db1e2dcd--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.backup.data.files++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.data.backend.BackupRepository+import com.vayunmathur.backup.data.backend.InMemoryBackend+import com.vayunmathur.backup.domain.crypto.Crypto+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class FileBackupManagerTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val key = ByteArray(32) { (it + 2).toByte() }++ private fun setup(): Triple<BackupRepository, InMemoryBackend, FileBackupManager> {+ val backend = InMemoryBackend()+ val repo = BackupRepository(backend, Crypto(key))+ return Triple(repo, backend, FileBackupManager(ctx, repo))+ }++ @Test fun backupWithNoMediaWritesEmptyIndex() = runBlocking<Unit> {+ val (repo, _, manager) = setup()+ val progress = mutableListOf<Pair<Int, Int>>()+ val count = manager.backupAll { d, t -> progress.add(d to t) }+ assertEquals(0, count)+ assertTrue(progress.isNotEmpty()); assertEquals(0 to 0, progress.first())+ assertEquals(emptyList(), manager.listBackedUp())+ assertTrue(repo.exists("files/index.json"))+ }++ @Test fun corruptIndexYieldsEmptyList() = runBlocking<Unit> {+ val (repo, _, manager) = setup()+ repo.writeEncrypted("files/index.json", "not json".toByteArray())+ assertEquals(emptyList(), manager.listBackedUp())+ }++ @Test fun restoreWritesDecryptedFiles() = runBlocking<Unit> {+ val (repo, _, manager) = setup()+ val entries = listOf(+ FileEntry("id1", "photo.jpg", "Pictures/", "image/jpeg", 3, 100L, "image"),+ FileEntry("id2", "song.mp3", "Music/", "audio/mpeg", 4, 200L, "audio"),+ FileEntry("missing", "gone.bin", "", "application/octet-stream", 1, 0L, "image"),+ )+ repo.writeEncrypted("files/index.json", Json.encodeToString(FileIndex.serializer(), FileIndex(entries)).toByteArray())+ repo.writeEncrypted(BackupRepository.filePath("id1"), "abc".toByteArray())+ repo.writeEncrypted(BackupRepository.filePath("id2"), "wxyz".toByteArray())+ assertEquals(entries, manager.listBackedUp())+ val progress = mutableListOf<Pair<Int, Int>>()+ val restored = manager.restoreAll { d, t -> progress.add(d to t) }+ // Third entry has no blob, so its write fails and is not counted.+ assertEquals(2, restored)+ val base = File(ctx.getExternalFilesDir(null), "BackupRestore")+ assertEquals("abc", File(base, "Pictures/photo.jpg").readText())+ assertEquals("wxyz", File(base, "Music/song.mp3").readText())+ assertEquals(0 to 3, progress.first()); assertEquals(3 to 3, progress.last())+ }++ @Test fun fileEntryAndIndexSerialization() {+ val e = FileEntry("id", "n", "p/", "text/plain", 12L, 34L, "image")+ assertEquals(e, FileEntry(e.fileId, e.displayName, e.relativePath, e.mimeType, e.size, e.dateModified, e.mediaType))+ val json = Json.encodeToString(FileIndex.serializer(), FileIndex(listOf(e)))+ assertEquals(listOf(e), Json.decodeFromString<FileIndex>(json).files)+ assertEquals(emptyList(), FileIndex().files)+ assertTrue(json.contains("\"fileId\":\"id\""))+ }+}
backup/src/test/java/com/vayunmathur/backup/domain/crypto/Bip39ExtraTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/domain/crypto/Bip39ExtraTest.kt b/backup/src/test/java/com/vayunmathur/backup/domain/crypto/Bip39ExtraTest.ktnew file mode 100644index 0000000000..32c2a12e70--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/domain/crypto/Bip39ExtraTest.kt@@ -0,0 +1,50 @@+package com.vayunmathur.backup.domain.crypto++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class Bip39ExtraTest {+ @Test fun allEntropySizesRoundTrip() {+ for (size in listOf(16, 20, 24, 28, 32)) {+ val entropy = ByteArray(size) { (it * 13 + size).toByte() }+ val words = Bip39.entropyToMnemonic(entropy)+ assertContentEquals(entropy, Bip39.mnemonicToEntropy(words))+ assertTrue(Bip39.isValid(words))+ }+ assertEquals(12, Bip39.entropyToMnemonic(ByteArray(16)).size)+ assertEquals(15, Bip39.entropyToMnemonic(ByteArray(20)).size)+ assertEquals(18, Bip39.entropyToMnemonic(ByteArray(24)).size)+ assertEquals(21, Bip39.entropyToMnemonic(ByteArray(28)).size)+ assertEquals(24, Bip39.entropyToMnemonic(ByteArray(32)).size)+ }++ @Test fun invalidEntropyAndMnemonicShapes() {+ assertFailsWith<IllegalArgumentException> { Bip39.entropyToMnemonic(ByteArray(15)) }+ assertFailsWith<IllegalArgumentException> { Bip39.entropyToMnemonic(ByteArray(17)) }+ assertFailsWith<IllegalArgumentException> { Bip39.entropyToMnemonic(ByteArray(0)) }+ assertFailsWith<IllegalArgumentException> { Bip39.mnemonicToEntropy(emptyList()) }+ assertFailsWith<IllegalArgumentException> { Bip39.mnemonicToEntropy(listOf("abandon")) }+ assertFailsWith<IllegalArgumentException> { Bip39.mnemonicToEntropy(listOf("abandon", "abandon")) }+ assertFalse(Bip39.isValid(emptyList()))+ assertFalse(Bip39.isValid(listOf("notaword") + List(11) { "abandon" }))+ // Case sensitive: uppercase word not in list.+ val valid = Bip39.generate()+ assertFalse(Bip39.isValid(listOf(valid[0].uppercase()) + valid.drop(1)))+ }++ @Test fun seedDependsOnPassphraseAndWords() {+ val words = Bip39.entropyToMnemonic(ByteArray(16))+ val a = Bip39.mnemonicToSeed(words)+ val b = Bip39.mnemonicToSeed(words, "pass")+ assertEquals(64, a.size)+ assertFalse(a.contentEquals(b))+ assertContentEquals(a, Bip39.mnemonicToSeed(words, ""))+ assertEquals(Bip39.ENTROPY_BYTES, 16)+ assertEquals(Bip39.WORD_COUNT, 12)+ assertTrue(Bip39.isValid(Bip39.generate()))+ }+}
backup/src/test/java/com/vayunmathur/backup/domain/crypto/CryptoExtraTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/domain/crypto/CryptoExtraTest.kt b/backup/src/test/java/com/vayunmathur/backup/domain/crypto/CryptoExtraTest.ktnew file mode 100644index 0000000000..a56a0f84c4--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/domain/crypto/CryptoExtraTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.backup.domain.crypto++import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class CryptoExtraTest {+ private val key = ByteArray(32) { it.toByte() }+ private val crypto = Crypto(key)++ @Test fun streamRoundTripExactSegmentAndChunkedReads() {+ val plain = ByteArray(Crypto.SEGMENT_SIZE) { (it % 251).toByte() }+ val blob = crypto.encrypt(plain)+ assertContentEquals(plain, crypto.decrypt(blob))+ // Chunked input stream (returns few bytes per read) still fills segments.+ val chunked = object : java.io.InputStream() {+ private var pos = 0+ override fun read(): Int = if (pos < plain.size) plain[pos++].toInt() and 0xFF else -1+ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (pos >= plain.size) return -1+ val n = minOf(7, len, plain.size - pos)+ plain.copyInto(b, off, pos, pos + n); pos += n; return n+ }+ }+ val out = ByteArrayOutputStream(); crypto.encrypt(chunked, out)+ assertContentEquals(plain, crypto.decrypt(out.toByteArray()))+ val bout = ByteArrayOutputStream(); crypto.encrypt(ByteArrayInputStream("abc".toByteArray()), bout)+ val dout = ByteArrayOutputStream(); crypto.decrypt(ByteArrayInputStream(bout.toByteArray()), dout)+ assertEquals("abc", dout.toString())+ }++ @Test fun rejectsEmptyBadVersionAndTruncation() {+ assertFailsWith<IOException> { crypto.decrypt(ByteArray(0)) }+ val badVersion = crypto.encrypt("x".toByteArray()); badVersion[0] = 99+ assertFailsWith<IllegalArgumentException> { crypto.decrypt(badVersion) }+ val blob = crypto.encrypt("hello world hello".toByteArray())+ assertFailsWith<Exception> { crypto.decrypt(blob.copyOf(blob.size - 3)) }+ assertFailsWith<Exception> { crypto.decrypt(blob.copyOf(3)) } // truncated header+ val badLen = byteArrayOf(1, 0x7F, 0, 0, 0, 1, 2)+ assertFailsWith<IOException> { crypto.decrypt(badLen) }+ val zeroLen = byteArrayOf(1, 0, 0, 0, 0)+ assertFailsWith<IOException> { crypto.decrypt(zeroLen) }+ }++ @Test fun detectsReorderedSegments() {+ val plain = ByteArray(Crypto.SEGMENT_SIZE * 2 + 10) { (it * 7).toByte() }+ val blob = crypto.encrypt(plain)+ // Parse segments, swap first two, expect failure (index check or GCM).+ val segs = mutableListOf<ByteArray>()+ var pos = 1+ while (pos < blob.size) {+ val len = ((blob[pos].toInt() and 0xFF) shl 24) or ((blob[pos+1].toInt() and 0xFF) shl 16) or+ ((blob[pos+2].toInt() and 0xFF) shl 8) or (blob[pos+3].toInt() and 0xFF)+ segs.add(blob.copyOfRange(pos, pos + 4 + len)); pos += 4 + len+ }+ assertEquals(3, segs.size)+ val swapped = ByteArrayOutputStream()+ swapped.write(1); swapped.write(segs[1]); swapped.write(segs[0]); swapped.write(segs[2])+ assertFailsWith<Exception> { crypto.decrypt(swapped.toByteArray()) }+ assertFalse(blob.contentEquals(plain))+ assertTrue(blob.size > plain.size)+ }++ @Test fun rejectsShortAndLongKeys() {+ assertFailsWith<IllegalArgumentException> { Crypto(ByteArray(0)) }+ assertFailsWith<IllegalArgumentException> { Crypto(ByteArray(31)) }+ assertFailsWith<IllegalArgumentException> { Crypto(ByteArray(33)) }+ }+}
backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.kt b/backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.ktnew file mode 100644index 0000000000..4111b5465f--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.backup.platform++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.FakeAndroidKeyStore+import com.vayunmathur.backup.data.BackendType+import com.vayunmathur.backup.data.BackupConfig+import com.vayunmathur.backup.data.BackupSettings+import com.vayunmathur.backup.domain.crypto.Bip39+import com.vayunmathur.backup.platform.crypto.KeyManager+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import android.os.Looper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class BackupViewModelTest {+ // VMs must be cleared after each test: a live BackupViewModel collects+ // BackupConfig.settings forever on the main looper, and a later test's+ // runBlocking DataStore edit on that same thread would deadlock against it.+ private val store = androidx.lifecycle.ViewModelStore()+ private fun vm(): BackupViewModel =+ androidx.lifecycle.ViewModelProvider(+ store,+ object : androidx.lifecycle.ViewModelProvider.Factory {+ @Suppress("UNCHECKED_CAST")+ override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =+ BackupViewModel(app) as T+ },+ )[BackupViewModel::class.java]++ @After fun tearDown() { store.clear() }++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app++ @Before fun setUp() = runBlocking<Unit> {+ FakeAndroidKeyStore.install(); FakeAndroidKeyStore.clear()+ ctx.getSharedPreferences("backup_secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()+ BackupConfig(ctx).clear()+ runCatching { KeyManager(ctx).clear() }+ }++ private fun idle() { shadowOf(Looper.getMainLooper()).idle() }++ private fun awaitState(cond: () -> Boolean) {+ val deadline = System.nanoTime() + 10_000_000_000L+ while (!cond() && System.nanoTime() < deadline) { idle(); Thread.sleep(10) }+ idle()+ }++ @Test fun initialStateAndOnboardedLogic() {+ val vm = vm(); idle()+ assertFalse(vm.state.hasKey); assertFalse(vm.state.onboarded); assertFalse(vm.state.busy); assertFalse(vm.state.loading)+ assertEquals(BackupSettings(), vm.state.settings.copy(lastRun = vm.state.settings.lastRun))+ // Pure state logic+ assertFalse(BackupUiState(hasKey = true, settings = BackupSettings()).onboarded)+ assertTrue(BackupUiState(hasKey = true, settings = BackupSettings(BackendType.SAF, safTreeUri = "content://x")).onboarded)+ assertFalse(BackupUiState(hasKey = false, settings = BackupSettings(BackendType.SAF, safTreeUri = "content://x")).onboarded)+ assertTrue(BackupUiState(hasKey = true, settings = BackupSettings(BackendType.WEBDAV, webdavUrl = "https://h")).onboarded)+ val s = BackupUiState(loading = true, busy = true, message = "m", error = "e", generatedCode = listOf("a"))+ assertEquals("m", s.message); assertEquals("e", s.error); assertEquals(listOf("a"), s.generatedCode)+ }++ @Test fun generateAndInvalidCode() {+ val vm = vm(); idle()+ vm.generateRecoveryCode(); idle()+ assertEquals(12, vm.state.generatedCode.size)+ assertTrue(Bip39.isValid(vm.state.generatedCode))+ assertNull(vm.state.error)+ vm.confirmNewCode(listOf("not", "valid")); idle()+ assertNotNull(vm.state.error)+ vm.restoreWithCode(listOf("abandon") + List(11) { "abandon" }); idle()+ assertNotNull(vm.state.error) // bad checksum+ vm.dismissMessages(); assertNull(vm.state.error); assertNull(vm.state.message)+ }++ @Test fun confirmValidCodeStoresKey() {+ val vm = vm(); idle()+ val code = Bip39.generate()+ vm.confirmNewCode(code.map { " ${it.uppercase()} " }); idle()+ // storeSeed runs on IO dispatcher; wait for main state update via looper + sleep-free polling on state+ awaitState { vm.state.hasKey }+ assertTrue(vm.state.hasKey)+ assertTrue(+ KeyManager(ctx).hasMasterKey(),+ "key not persisted: aliases=${com.vayunmathur.backup.FakeAndroidKeyStore.aliases()} " ++ "prefs=${ctx.getSharedPreferences("backup_secure_prefs", android.content.Context.MODE_PRIVATE).all.keys} msg=${vm.state.message}",+ )+ assertTrue(vm.state.generatedCode.isEmpty())+ assertNotNull(vm.state.message)+ }++ @Test fun restoreValidCodeStoresKey() {+ val vm = vm(); idle()+ vm.restoreWithCode(Bip39.generate()); idle()+ awaitState { vm.state.hasKey }+ assertTrue(vm.state.hasKey)+ assertTrue(vm.state.message!!.contains("accepted"))+ }++ @Test fun backendSelectionAndToggles() = runBlocking<Unit> {+ val vm = vm(); idle()+ vm.setWebDavBackend("", "u", "p"); assertNotNull(vm.state.error)+ vm.setWebDavBackend(" https://dav.example.com ", " alice ", "pw"); idle()+ awaitState { vm.state.settings.backendType == BackendType.WEBDAV }+ assertEquals(BackendType.WEBDAV, vm.state.settings.backendType)+ assertEquals("https://dav.example.com", vm.state.settings.webdavUrl)+ assertEquals("alice", vm.state.settings.webdavUser)+ vm.setSafBackend("content://tree/xyz"); idle()+ awaitState { vm.state.settings.backendType == BackendType.SAF }+ assertEquals("content://tree/xyz", vm.state.settings.safTreeUri)+ vm.setAppBackupEnabled(true); idle()+ awaitState { vm.state.settings.appBackupEnabled }+ assertTrue(vm.state.settings.appBackupEnabled)+ vm.setFileBackupEnabled(true); idle()+ awaitState { vm.state.settings.fileBackupEnabled }+ assertTrue(vm.state.settings.fileBackupEnabled)+ vm.setFileBackupEnabled(false); idle()+ }++ @Test fun backupNowWithoutDestinationReportsError() {+ val vm = vm(); idle()+ vm.backupFilesNow()+ assertTrue(vm.state.busy)+ awaitState { !vm.state.busy }+ assertNotNull(vm.state.error)+ vm.restoreFilesNow()+ awaitState { !vm.state.busy }+ assertNotNull(vm.state.error)+ vm.dismissMessages(); assertNull(vm.state.error)+ }+}
backup/src/test/java/com/vayunmathur/backup/platform/KeyManagerAndWorkerTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/platform/KeyManagerAndWorkerTest.kt b/backup/src/test/java/com/vayunmathur/backup/platform/KeyManagerAndWorkerTest.ktnew file mode 100644index 0000000000..28d2caa56d--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/platform/KeyManagerAndWorkerTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.backup.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import com.vayunmathur.backup.FakeAndroidKeyStore+import com.vayunmathur.backup.data.BackupConfig+import com.vayunmathur.backup.domain.crypto.Bip39+import com.vayunmathur.backup.platform.crypto.KeyManager+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class KeyManagerAndWorkerTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() {+ FakeAndroidKeyStore.install(); FakeAndroidKeyStore.clear()+ ctx.getSharedPreferences("backup_secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()+ }++ @Test fun deriveMasterKeyIsDeterministic32Bytes() {+ val seed = ByteArray(64) { it.toByte() }+ val a = KeyManager.deriveMasterKey(seed); val b = KeyManager.deriveMasterKey(seed)+ assertEquals(32, a.size); assertContentEquals(a, b)+ val c = KeyManager.deriveMasterKey(ByteArray(64) { (it + 1).toByte() })+ assertFalse(a.contentEquals(c))+ }++ @Test fun storeAndRetrieveSeedDerivedKey() {+ val km = KeyManager(ctx)+ assertFalse(km.hasMasterKey())+ val seed = Bip39.mnemonicToSeed(Bip39.generate())+ km.storeSeed(seed)+ assertTrue(km.hasMasterKey())+ assertContentEquals(KeyManager.deriveMasterKey(seed), km.getMasterKey())+ // Same seed again overwrites with same key.+ km.storeSeed(seed); assertContentEquals(KeyManager.deriveMasterKey(seed), km.getMasterKey())+ km.clear(); assertFalse(km.hasMasterKey())+ }++ @Test fun workerNoOpsWhenDisabledOrUnconfigured() = runBlocking<Unit> {+ val config = BackupConfig(ctx); config.clear()+ val worker = TestListenableWorkerBuilder<FileBackupWorker>(ctx).build()+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ // Enabled but no backend/key -> also success (no-op).+ config.setFileBackupEnabled(true)+ assertTrue(config.settings.first().fileBackupEnabled)+ val worker2 = TestListenableWorkerBuilder<FileBackupWorker>(ctx).build()+ assertEquals(ListenableWorker.Result.success(), worker2.doWork())+ config.clear()+ }++ @Test fun workerRetriesThenSucceedsPathWithSafMissing() = runBlocking<Unit> {+ // Enabled + SAF uri pointing nowhere + key present: backend creation succeeds,+ // backup attempt fails inside manager (index write through providerless SAF)+ // or returns success if enumerate produces empty and write is swallowed.+ // We only assert it returns a terminal Result without throwing.+ val config = BackupConfig(ctx); config.clear()+ KeyManager(ctx).storeSeed(Bip39.mnemonicToSeed(Bip39.generate()))+ config.setSafBackend("content://com.example.invalid/tree/root")+ config.setFileBackupEnabled(true)+ val worker = TestListenableWorkerBuilder<FileBackupWorker>(ctx).build()+ val result = worker.doWork()+ assertTrue(result is ListenableWorker.Result)+ config.clear(); KeyManager(ctx).clear()+ }+}
backup/src/test/java/com/vayunmathur/backup/service/ConfigurableBackupTransportTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/service/ConfigurableBackupTransportTest.kt b/backup/src/test/java/com/vayunmathur/backup/service/ConfigurableBackupTransportTest.ktnew file mode 100644index 0000000000..70f5e109ba--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/service/ConfigurableBackupTransportTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.backup.service++import android.app.backup.BackupTransport+import android.app.backup.RestoreDescription+import android.content.Context+import android.content.pm.PackageInfo+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.FakeAndroidKeyStore+import com.vayunmathur.backup.FakeDocumentsProvider+import com.vayunmathur.backup.data.BackupConfig+import com.vayunmathur.backup.platform.crypto.KeyManager+import com.vayunmathur.backup.domain.crypto.Bip39+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ConfigurableBackupTransportTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var transport: ConfigurableBackupTransport++ @Before fun setUp() = runBlocking<Unit> {+ FakeAndroidKeyStore.install(); FakeAndroidKeyStore.clear()+ ctx.getSharedPreferences("backup_secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()+ BackupConfig(ctx).clear(); runCatching { KeyManager(ctx).clear() }+ transport = ConfigurableBackupTransport(ctx)+ }++ private fun pkg(name: String) = PackageInfo().apply { packageName = name }++ @Test fun identityAndConstantsWithoutRepo() {+ assertEquals("com.vayunmathur.backup/.service.ConfigurableBackupTransportService", transport.name())+ assertEquals("com.vayunmathur.backup", transport.transportDirName())+ assertEquals(0, transport.transportFlagsCompat())+ assertEquals(0L, transport.requestBackupTime())+ assertEquals(0L, transport.requestFullBackupTime())+ assertEquals(Long.MAX_VALUE, transport.getBackupQuota("com.x", false))+ assertEquals(Long.MAX_VALUE, transport.getBackupQuota("com.x", true))+ assertEquals(BackupTransport.TRANSPORT_OK, transport.checkFullBackupSize(1_000_000L))+ assertEquals(BackupTransport.TRANSPORT_OK, transport.checkFullBackupSize(-1L))+ assertNotNull(transport.configurationIntent())+ assertNotNull(transport.dataManagementIntent())+ assertEquals(transport.configurationIntent().component, transport.dataManagementIntent().component)+ assertTrue(transport.dataManagementIntentLabel().isNotEmpty())+ assertTrue(transport.currentDestinationString().isNotEmpty())+ val sets = transport.availableRestoreSetsCompat()+ assertEquals(1, sets.size); assertEquals(transport.name(), sets[0].name)+ assertEquals(1L, transport.currentRestoreSetCompat())+ }++ @Test fun operationsFailGracefullyWithoutRepo() {+ assertEquals(BackupTransport.TRANSPORT_NOT_INITIALIZED, transport.initializeDevice())+ val (readFd, writeFd) = ParcelFileDescriptor.createPipe()+ assertEquals(BackupTransport.TRANSPORT_NOT_INITIALIZED, transport.performBackup(pkg("com.a"), readFd))+ assertEquals(BackupTransport.TRANSPORT_NOT_INITIALIZED, transport.clearBackupData(pkg("com.a")))+ assertEquals(BackupTransport.TRANSPORT_OK, transport.finishBackup()) // kv path: no full backup pending+ assertEquals(BackupTransport.TRANSPORT_NOT_INITIALIZED, transport.performFullBackup(pkg("com.a"), writeFd))+ assertEquals(BackupTransport.TRANSPORT_ERROR, transport.sendBackupData(10))+ transport.cancelFullBackup() // no-op, must not throw+ assertEquals(BackupTransport.TRANSPORT_NOT_INITIALIZED, transport.startRestore(1L, arrayOf(pkg("com.a"))))+ assertEquals(RestoreDescription.NO_MORE_PACKAGES, transport.nextRestorePackageCompat())+ val (r2, w2) = ParcelFileDescriptor.createPipe()+ assertEquals(BackupTransport.TRANSPORT_NOT_INITIALIZED, transport.getRestoreData(r2))+ assertEquals(BackupTransport.NO_MORE_DATA, transport.getNextFullRestoreDataChunk(w2))+ assertEquals(BackupTransport.TRANSPORT_OK, transport.abortFullRestore())+ transport.finishRestore() // no-op+ readFd.close(); writeFd.close(); r2.close(); w2.close()+ }++ @Test fun serviceBindsTransport() {+ val service = ConfigurableBackupTransportService()+ // attach a base context via Robolectric service controller+ val controller = org.robolectric.Robolectric.buildService(ConfigurableBackupTransportService::class.java)+ val svc = controller.create().get()+ val binder = svc.onBind(android.content.Intent())+ assertNotNull(binder)+ controller.destroy()+ }++ // Reflective wrappers for hidden-API-suffixed / overloaded transport methods where+ // the compile-time stub signatures differ; direct calls above cover most.+ private fun BackupTransport.transportFlagsCompat(): Int = getTransportFlags()+ private fun BackupTransport.availableRestoreSetsCompat() = getAvailableRestoreSets().toList()+ private fun BackupTransport.currentRestoreSetCompat(): Long = getCurrentRestoreSet()+ private fun BackupTransport.nextRestorePackageCompat(): RestoreDescription = nextRestorePackage()+}
backup/src/test/java/com/vayunmathur/backup/service/TransportWithRepoTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/service/TransportWithRepoTest.kt b/backup/src/test/java/com/vayunmathur/backup/service/TransportWithRepoTest.ktnew file mode 100644index 0000000000..248306dc2d--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/service/TransportWithRepoTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.backup.service++import android.app.backup.BackupDataInput+import android.app.backup.BackupDataOutput+import android.app.backup.BackupTransport+import android.app.backup.RestoreDescription+import android.content.Context+import android.content.pm.PackageInfo+import android.os.ParcelFileDescriptor+import android.provider.DocumentsContract+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.DocsContentResolverShadow+import com.vayunmathur.backup.FakeAndroidKeyStore+import com.vayunmathur.backup.FakeDocumentsProvider+import com.vayunmathur.backup.data.BackupConfig+import com.vayunmathur.backup.domain.crypto.Bip39+import com.vayunmathur.backup.platform.crypto.KeyManager+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import java.io.File+import java.io.FileInputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)[email protected](shadows = [DocsContentResolverShadow::class, com.vayunmathur.backup.ShadowBackupDataInput::class, com.vayunmathur.backup.ShadowBackupDataOutput::class])+class TransportWithRepoTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var transport: ConfigurableBackupTransport++ @Before fun setUp() = runBlocking<Unit> {+ FakeAndroidKeyStore.install(); FakeAndroidKeyStore.clear()+ ctx.getSharedPreferences("backup_secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()+ val root = File(ctx.cacheDir, "transport-saf-${System.nanoTime()}").apply { mkdirs() }+ FakeDocumentsProvider.rootDir = root+ val provider = FakeDocumentsProvider()+ provider.attachInfo(ctx, android.content.pm.ProviderInfo().apply {+ authority = FakeDocumentsProvider.AUTHORITY; exported = true; grantUriPermissions = true+ readPermission = android.Manifest.permission.MANAGE_DOCUMENTS+ writePermission = android.Manifest.permission.MANAGE_DOCUMENTS+ })+ try {+ val m = Class.forName("org.robolectric.shadows.ShadowContentResolver")+ .getMethod("registerProviderInternal", String::class.java, android.content.ContentProvider::class.java)+ m.invoke(null, FakeDocumentsProvider.AUTHORITY, provider)+ } catch (ignored: Exception) {+ val shadow = Shadows.shadowOf(ctx.contentResolver)+ shadow.javaClass.methods.first { it.name.contains("registerProvider") }+ .invoke(shadow, FakeDocumentsProvider.AUTHORITY, provider)+ }+ FakeDocumentsProvider.instance = provider+ val config = BackupConfig(ctx); config.clear()+ runCatching { KeyManager(ctx).clear() }+ KeyManager(ctx).storeSeed(Bip39.mnemonicToSeed(Bip39.generate()))+ val treeUri = DocumentsContract.buildTreeDocumentUri(FakeDocumentsProvider.AUTHORITY, FakeDocumentsProvider.ROOT_ID)+ config.setSafBackend(treeUri.toString())+ transport = ConfigurableBackupTransport(ctx)+ }++ private fun pkg(name: String) = PackageInfo().apply { packageName = name }++ private fun dataOutput(fd: java.io.FileDescriptor): BackupDataOutput =+ BackupDataOutput::class.java.getDeclaredConstructor(java.io.FileDescriptor::class.java)+ .apply { isAccessible = true }.newInstance(fd)++ private fun dataInput(fd: java.io.FileDescriptor): BackupDataInput =+ BackupDataInput::class.java.getDeclaredConstructor(java.io.FileDescriptor::class.java)+ .apply { isAccessible = true }.newInstance(fd)++ private fun kvBackup(pkgName: String, entities: Map<String, ByteArray?>, flags: Int = 0): Int {+ val pipe = ParcelFileDescriptor.createPipe()+ val writer = dataOutput(pipe[1].fileDescriptor)+ for ((k, v) in entities) {+ if (v == null) { writer.writeEntityHeader(k, -1) }+ else { writer.writeEntityHeader(k, v.size); writer.writeEntityData(v, v.size) }+ }+ pipe[1].close()+ val result = if (flags == 0) transport.performBackup(pkg(pkgName), pipe[0])+ else transport.performBackup(pkg(pkgName), pipe[0], flags)+ pipe[0].close()+ return result+ }++ @Test fun kvAndFullBackupRestoreCycle() {+ assertEquals(BackupTransport.TRANSPORT_OK, transport.initializeDevice())+ assertTrue(transport.currentDestinationString().isNotEmpty())++ // KV backup with two entities.+ assertEquals(BackupTransport.TRANSPORT_OK, kvBackup("com.example.app", mapOf("k1" to "v1".toByteArray(), "k2" to "value2".toByteArray())))+ // Incremental delete of k1.+ assertEquals(BackupTransport.TRANSPORT_OK, kvBackup("com.example.app", mapOf("k1" to null)))+ // Non-incremental pass replaces the set.+ assertEquals(BackupTransport.TRANSPORT_OK, kvBackup("com.example.app", mapOf("only" to "one".toByteArray()), BackupTransport.FLAG_NON_INCREMENTAL))++ // Restore KV.+ assertEquals(BackupTransport.TRANSPORT_OK, transport.startRestore(1L, arrayOf(pkg("com.example.app"), pkg("com.absent"))))+ val desc = transport.nextRestorePackage()+ assertEquals("com.example.app", desc.packageName)+ assertEquals(RestoreDescription.TYPE_KEY_VALUE, desc.dataType)+ val pipe = ParcelFileDescriptor.createPipe()+ assertEquals(BackupTransport.TRANSPORT_OK, transport.getRestoreData(pipe[1]))+ pipe[1].close()+ val reader = dataInput(pipe[0].fileDescriptor)+ val restored = mutableMapOf<String, String>()+ while (reader.readNextHeader()) {+ val size = reader.dataSize+ val data = ByteArray(size); var off = 0+ while (off < size) { val n = reader.readEntityData(data, off, size - off); check(n > 0) { "short entity data" }; off += n }+ restored[reader.key] = data.decodeToString()+ }+ pipe[0].close()+ assertEquals(mapOf("only" to "one"), restored)+ assertEquals(RestoreDescription.NO_MORE_PACKAGES, transport.nextRestorePackage())+ transport.finishRestore()++ // Full backup: stream bytes through sendBackupData, then finish.+ assertEquals(BackupTransport.TRANSPORT_OK, transport.clearBackupData(pkg("com.example.app")))+ val fullPipe = ParcelFileDescriptor.createPipe()+ assertEquals(BackupTransport.TRANSPORT_OK, transport.performFullBackup(pkg("com.example.app"), fullPipe[0]))+ val payload = "full-tar-payload".toByteArray()+ val out = android.os.ParcelFileDescriptor.AutoCloseOutputStream(fullPipe[1])+ out.write(payload); out.flush()+ assertEquals(BackupTransport.TRANSPORT_OK, transport.sendBackupData(payload.size))+ assertEquals(BackupTransport.TRANSPORT_OK, transport.finishBackup())+ // finishBackup again with nothing pending is OK.+ assertEquals(BackupTransport.TRANSPORT_OK, transport.finishBackup())++ // Full restore.+ assertEquals(BackupTransport.TRANSPORT_OK, transport.startRestore(1L, arrayOf(pkg("com.example.app"))))+ val fdesc = transport.nextRestorePackage()+ assertEquals(RestoreDescription.TYPE_FULL_STREAM, fdesc.dataType)+ val restorePipe = ParcelFileDescriptor.createPipe()+ val n = transport.getNextFullRestoreDataChunk(restorePipe[1])+ assertEquals(payload.size, n)+ val got = ByteArray(n)+ val input = android.os.ParcelFileDescriptor.AutoCloseInputStream(restorePipe[0])+ var read = 0; while (read < n) { val r = input.read(got, read, n - read); check(r >= 0) { "short full-restore stream" }; read += r }+ assertEquals("full-tar-payload", got.decodeToString())+ assertEquals(BackupTransport.NO_MORE_DATA, transport.getNextFullRestoreDataChunk(restorePipe[1]))+ assertEquals(BackupTransport.TRANSPORT_OK, transport.abortFullRestore())+ transport.finishRestore()++ // Cancel a fresh full backup, then wipe everything.+ val cancelPipe = ParcelFileDescriptor.createPipe()+ assertEquals(BackupTransport.TRANSPORT_OK, transport.performFullBackup(pkg("com.example.app"), cancelPipe[0], 0))+ transport.cancelFullBackup()+ assertEquals(BackupTransport.TRANSPORT_OK, transport.initializeDevice())+ assertEquals(BackupTransport.TRANSPORT_OK, transport.clearBackupData(pkg("com.example.app")))+ }+}
backup/src/test/java/com/vayunmathur/backup/ui/ComposeScreensTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/ui/ComposeScreensTest.kt b/backup/src/test/java/com/vayunmathur/backup/ui/ComposeScreensTest.ktnew file mode 100644index 0000000000..f643f9766e--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/ui/ComposeScreensTest.kt@@ -0,0 +1,165 @@+package com.vayunmathur.backup.ui++import androidx.compose.foundation.verticalScroll+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextInput+import com.vayunmathur.backup.data.BackendType+import com.vayunmathur.backup.data.BackupSettings+import com.vayunmathur.backup.platform.BackupUiState+import com.vayunmathur.backup.ui.components.BackendSection+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ComposeScreensTest {+ @get:Rule val rule = createComposeRule()++ @Test fun dashboardShowsStatusAndActions() {+ var backup = 0; var restore = 0; var picked = 0+ var appToggle: Boolean? = null; var fileToggle: Boolean? = null+ rule.setContent {+ DashboardScreen(+ state = BackupUiState(+ settings = BackupSettings(BackendType.WEBDAV, webdavUrl = "https://dav.example.com", lastRun = 0L),+ message = "All good", busy = false,+ ),+ onPickFolder = { picked++ },+ onSetWebDav = { _, _, _ -> },+ onAppBackupToggle = { appToggle = it },+ onFileBackupToggle = { fileToggle = it },+ onBackupNow = { backup++ },+ onRestoreNow = { restore++ },+ )+ }+ rule.onNodeWithText("Backup").assertIsDisplayed()+ rule.onNodeWithText("All good").assertIsDisplayed()+ rule.onNodeWithText("Status").assertIsDisplayed()+ rule.onAllNodesWithText("WebDAV: https://dav.example.com").assertCountEquals(2)+ rule.onNodeWithText("No backup has run yet.").assertIsDisplayed()+ rule.onNodeWithText("What to back up").assertIsDisplayed()+ rule.onNodeWithText("Back up files now").performScrollTo().assertIsDisplayed().performClick()+ rule.onNodeWithText("Restore files").performScrollTo().assertIsDisplayed().performClick()+ assertEquals(1, backup); assertEquals(1, restore)+ // Switches are present via their list item labels+ rule.onNodeWithText("App data (system transport)").assertIsDisplayed()+ rule.onNodeWithText("Photos, videos & audio").assertIsDisplayed()+ }++ @Test fun dashboardBusyDisablesActionsAndShowsWorking() {+ rule.setContent {+ DashboardScreen(+ state = BackupUiState(settings = BackupSettings(lastRun = 1700000000000L), error = "oops", busy = true),+ onPickFolder = {}, onSetWebDav = { _, _, _ -> },+ onAppBackupToggle = {}, onFileBackupToggle = {}, onBackupNow = {}, onRestoreNow = {},+ )+ }+ rule.onNodeWithText("oops").assertIsDisplayed()+ rule.onNodeWithText("Working…").assertIsDisplayed()+ rule.onNodeWithText("Back up files now").assertIsNotEnabled()+ rule.onNodeWithText("Restore files").assertIsNotEnabled()+ }++ @Test fun onboardingGenerateAndConfirm() {+ var generated = 0; var confirmed: List<String>? = null; var dismissed = 0+ rule.setContent {+ OnboardingScreen(+ state = BackupUiState(generatedCode = emptyList()),+ onPickFolder = {}, onSetWebDav = { _, _, _ -> },+ onGenerate = { generated++ },+ onConfirmNew = { confirmed = it },+ onRestoreWithCode = {},+ onDismissMessages = { dismissed++ },+ )+ }+ rule.onNodeWithText("Set up Backup").assertIsDisplayed()+ rule.onNodeWithText("Recovery code").performScrollTo().assertIsDisplayed()+ rule.onNodeWithText("Generate recovery code").performScrollTo().performClick()+ assertEquals(1, generated); assertTrue(dismissed >= 1)+ assertEquals(null, confirmed)+ }++ @Test fun onboardingShowsGeneratedCodeAndConfirms() {+ val code = listOf("abandon", "ability", "able")+ var confirmed: List<String>? = null+ rule.setContent {+ OnboardingScreen(+ state = BackupUiState(generatedCode = code, error = "bad code"),+ onPickFolder = {}, onSetWebDav = { _, _, _ -> },+ onGenerate = {}, onConfirmNew = { confirmed = it },+ onRestoreWithCode = {}, onDismissMessages = {},+ )+ }+ rule.onNodeWithText("bad code").assertIsDisplayed()+ rule.onNodeWithText("1. abandon\n2. ability\n3. able").performScrollTo().assertIsDisplayed()+ rule.onNodeWithText("I saved it — enable encrypted backups").performScrollTo().performClick()+ assertEquals(code, confirmed)+ }++ @Test fun onboardingRestoreFlow() {+ var restored: List<String>? = null+ rule.setContent {+ OnboardingScreen(+ state = BackupUiState(message = "welcome"),+ onPickFolder = {}, onSetWebDav = { _, _, _ -> },+ onGenerate = {}, onConfirmNew = {},+ onRestoreWithCode = { restored = it }, onDismissMessages = {},+ )+ }+ rule.onNodeWithText("welcome").assertIsDisplayed()+ rule.onNodeWithText("Restore existing").performScrollTo().performClick()+ rule.onNodeWithText("Enter your 12-word recovery code").performScrollTo().assertIsDisplayed()+ rule.onNodeWithText("Restore with recovery code").assertIsNotEnabled()+ rule.onNodeWithText("Enter your 12-word recovery code").performScrollTo().performTextInput("abandon ability able")+ rule.onNodeWithText("Restore with recovery code").performScrollTo().assertIsEnabled().performClick()+ assertEquals(listOf("abandon", "ability", "able"), restored)+ }++ @Test fun backendSectionWebDavForm() {+ var picked = 0; var saved: Triple<String, String, String>? = null+ rule.setContent {+ androidx.compose.foundation.layout.Column(+ modifier = androidx.compose.ui.Modifier.verticalScroll(androidx.compose.foundation.rememberScrollState()),+ ) {+ BackendSection(+ settings = BackupSettings(BackendType.NONE),+ onPickFolder = { picked++ },+ onSetWebDav = { u, user, p -> saved = Triple(u, user, p) },+ )+ }+ }+ rule.onNodeWithText("Backup destination").assertIsDisplayed()+ rule.onNodeWithText("No destination selected").assertIsDisplayed()+ rule.onNodeWithText("Choose folder (USB / SD / internal)").performClick()+ assertEquals(1, picked)+ rule.onNodeWithText("Save WebDAV destination").assertIsNotEnabled()+ rule.onNodeWithText("WebDAV URL").performScrollTo().performTextInput("https://dav.example.com")+ rule.onNodeWithText("Username").performScrollTo().performTextInput("alice")+ rule.onNodeWithText("Password").performScrollTo().performTextInput("secret")+ rule.onNodeWithText("Save WebDAV destination").performScrollTo().assertIsEnabled().performClick()+ assertEquals(Triple("https://dav.example.com", "alice", "secret"), saved)+ }++ @Test fun backendSectionPrefillsSettings() {+ rule.setContent {+ BackendSection(+ settings = BackupSettings(BackendType.WEBDAV, webdavUrl = "https://h", webdavUser = "bob"),+ onPickFolder = {}, onSetWebDav = { _, _, _ -> },+ )+ }+ rule.onNodeWithText("WebDAV: https://h").assertIsDisplayed()+ rule.onNodeWithText("https://h").assertIsDisplayed()+ rule.onNodeWithText("bob").assertIsDisplayed()+ }+}