diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..73eadcc --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +name: CI + +on: + pull_request: + branches: [ master ] + push: + branches: [ master ] + +# Cancel superseded runs on the same branch/PR. +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Tests & coverage gate + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' # Runs Gradle/AGP; library still compiles to JVM 11. + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + # All tests run on the JVM — BaseDataStoreHelperTest runs under Robolectric via + # the AndroidJUnit4 delegating runner — so no emulator is needed. koverVerifyDebug + # enforces the coverage floor over com.duck.prefshelper.* (both helpers). + - name: Run tests and verify coverage + run: ./gradlew :app:testDebugUnitTest :app:koverXmlReportDebug :app:koverVerifyDebug + + - name: Upload Kover coverage report + if: always() + uses: actions/upload-artifact@v4 + with: + name: kover-report + path: app/build/reports/kover/ + if-no-files-found: ignore diff --git a/CLAUDE.md b/CLAUDE.md index 352b35e..8b114d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,14 +15,17 @@ LocalDateTime, LocalDate, LocalTime, and Enums. # Build the library ./gradlew :PrefsHelper:build -# Run unit tests -./gradlew :PrefsHelper:test +# Run all tests (both test classes live in :app/src/test and run on the JVM — +# BaseDataStoreHelperTest runs under Robolectric, so no device/emulator is needed) +./gradlew :app:testDebugUnitTest -# Run instrumented tests (requires connected device/emulator) -./gradlew :PrefsHelper:connectedAndroidTest +# Run a single test class +./gradlew :app:testDebugUnitTest --tests "com.duck.app.BaseDataStoreHelperTest" -# Run a single instrumented test class (--tests is rejected by connectedAndroidTest) -./gradlew :app:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.duck.app.BaseDataStoreHelperTest +# Coverage (Kover; aggregates :PrefsHelper into :app since the tests live in :app). +# Android module -> variant-suffixed tasks. No device needed. +./gradlew :app:koverHtmlReportDebug # HTML -> app/build/reports/kover/htmlDebug/index.html +./gradlew :app:koverVerifyDebug # fails below the coverage floor (minBound in app/build.gradle.kts) # Generate documentation ./gradlew :PrefsHelper:dokkaHtml @@ -47,7 +50,7 @@ The library provides two abstract base classes that consumers extend: - Wraps Jetpack `DataStore` with type-safe methods - Returns `Flow` for reactive reads, plus blocking `readXxxValue()` methods (2s timeout) -- Both suspend and async (fire-and-forget via `scope.launch`) write methods +- Both suspend and async write methods. The `writeXxxAsync` methods launch on `scope` and **return the `Job`**, so callers (and tests) can `.join()` to await completion instead of guessing with a delay. Delegate setters discard the `Job` (property setters return `Unit`), so they remain genuinely fire-and-forget. - Subclasses pass `Context` and preference name to constructor - Null values remove the key from storage - Preferred usage is the `*Pref` delegate + `*PrefFlow` alias pair (e.g. `var userId by intPref(KEY, defaultValue = -1)` paired with `val userIdFlow = intPrefFlow(KEY, defaultValue = -1)`). Delegate setters route through the existing `*Async` writes so callers don't need to build their own `CoroutineScope`. @@ -58,6 +61,8 @@ Both classes support: `String`, `Int`, `Long`, `Boolean`, `LocalDateTime`, `Loca - **Inline reified factories that access `protected` members**: an `inline fun ` that returns an anonymous object (e.g. a `ReadWriteProperty`) calling `protected` methods on `BaseDataStoreHelper` throws `IllegalAccessError` at runtime — the anonymous class is emitted inside the *subclass* at inline time, losing JVM-level protected access. Fix: split into a thin `inline` + `reified` wrapper that forwards to a non-inline `@PublishedApi internal` helper which owns the anonymous object. See `enumPref` / `enumPrefInternal` in `BaseDataStoreHelper.kt`. `BasePrefsHelper` is unaffected because its get/set accessors are `public`. +- **Tests are JVM-only (Robolectric), not instrumented**: both test classes live in `app/src/test`. `BaseDataStoreHelperTest` uses a real `DataStore` but runs on the JVM via Robolectric (`@RunWith(AndroidJUnit4::class)` delegates to `RobolectricTestRunner` off-device). This is deliberate: **Kover cannot instrument on-device tests**, so DataStore coverage would read ~0% if the tests were instrumented — running them under Robolectric makes the `koverVerifyDebug` floor meaningful across both helpers. Robolectric's SDK is pinned to 36 in `app/src/test/resources/robolectric.properties` because `targetSdk = 37` has no Robolectric image yet. + ## Project Structure - `PrefsHelper/` - Library module (published to JitPack) diff --git a/PrefsHelper/build.gradle.kts b/PrefsHelper/build.gradle.kts index 0cde5b1..a5fca34 100644 --- a/PrefsHelper/build.gradle.kts +++ b/PrefsHelper/build.gradle.kts @@ -1,14 +1,16 @@ +import com.android.build.api.dsl.LibraryExtension import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { alias(libs.plugins.android.library) alias(libs.plugins.dokka) + alias(libs.plugins.kover) `maven-publish` } group = "com.github.projectdelta6" -android { +configure { namespace = "com.duck.prefshelper" compileSdk = libs.versions.compileSdk.get().toInt() @@ -30,11 +32,6 @@ android { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } - kotlin { - compilerOptions { - jvmTarget.set(JvmTarget.JVM_11) - } - } publishing { singleVariant("release") { @@ -44,6 +41,12 @@ android { } } +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_11) + } +} + afterEvaluate { publishing { publications { diff --git a/PrefsHelper/src/main/java/com/duck/prefshelper/BaseDataStoreHelper.kt b/PrefsHelper/src/main/java/com/duck/prefshelper/BaseDataStoreHelper.kt index 55d3528..f06190a 100644 --- a/PrefsHelper/src/main/java/com/duck/prefshelper/BaseDataStoreHelper.kt +++ b/PrefsHelper/src/main/java/com/duck/prefshelper/BaseDataStoreHelper.kt @@ -16,6 +16,7 @@ import androidx.datastore.preferences.preferencesDataStore import com.duck.prefshelper.BaseDataStoreHelper.Companion.supervisorJob import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first @@ -24,6 +25,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import kotlin.time.Duration.Companion.seconds import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime @@ -121,8 +123,9 @@ abstract class BaseDataStoreHelper( * Generic method to delete value from the data store asynchronously. * * @param key The key to delete the value for + * @return The [Job] for the launched removal — call [Job.join] to await completion. */ - protected inline fun removeKeyAsync(key: Preferences.Key) = + protected inline fun removeKeyAsync(key: Preferences.Key): Job = scope.launch { removeKey(key) } /** @@ -139,8 +142,9 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ - protected inline fun writeValueAsync(key: Preferences.Key, value: T) = + protected inline fun writeValueAsync(key: Preferences.Key, value: T): Job = scope.launch { writeValue(key, value) } /** @@ -163,9 +167,10 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store or null to delete + * @return The [Job] for the launched write/removal — call [Job.join] to await completion. */ @JvmName("writeNullableValueAsync") - protected inline fun writeValueAsync(key: Preferences.Key, value: T?) = + protected inline fun writeValueAsync(key: Preferences.Key, value: T?): Job = if (value == null) removeKeyAsync(key) else writeValueAsync(key, value) /** @@ -205,7 +210,7 @@ abstract class BaseDataStoreHelper( */ protected inline fun readValueBlocking(key: Preferences.Key): T? = runBlocking(coroutineContext) { - withTimeoutOrNull(2000) { + withTimeoutOrNull(2.seconds) { dataStore.data.first()[key] } } @@ -257,8 +262,9 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ - protected fun writeIntAsync(key: String, value: Int?) = + protected fun writeIntAsync(key: String, value: Int?): Job = writeValueAsync(intPreferencesKey(key), value) /** @@ -308,8 +314,9 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ - protected fun writeDoubleAsync(key: String, value: Double?) = + protected fun writeDoubleAsync(key: String, value: Double?): Job = writeValueAsync(doublePreferencesKey(key), value) /** @@ -368,8 +375,9 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ - protected fun writeStringAsync(key: String, value: String?) = + protected fun writeStringAsync(key: String, value: String?): Job = writeValueAsync(stringPreferencesKey(key), value) /** @@ -428,8 +436,9 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ - protected fun writeLongAsync(key: String, value: Long?) = + protected fun writeLongAsync(key: String, value: Long?): Job = writeValueAsync(longPreferencesKey(key), value) /** @@ -488,8 +497,9 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ - protected fun writeBooleanAsync(key: String, value: Boolean?) = + protected fun writeBooleanAsync(key: String, value: Boolean?): Job = writeValueAsync(booleanPreferencesKey(key), value) /** @@ -547,9 +557,10 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ @RequiresApi(Build.VERSION_CODES.O) - protected fun writeLocalDateTimeAsync(key: String, value: LocalDateTime?) = + protected fun writeLocalDateTimeAsync(key: String, value: LocalDateTime?): Job = writeValueAsync(stringPreferencesKey(key), value?.toString()) /** @@ -607,9 +618,10 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ @RequiresApi(Build.VERSION_CODES.O) - protected fun writeLocalDateAsync(key: String, value: LocalDate?) = + protected fun writeLocalDateAsync(key: String, value: LocalDate?): Job = writeValueAsync(stringPreferencesKey(key), value?.toString()) /** @@ -667,9 +679,10 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ @RequiresApi(Build.VERSION_CODES.O) - protected fun writeLocalTimeAsync(key: String, value: LocalTime?) = + protected fun writeLocalTimeAsync(key: String, value: LocalTime?): Job = writeValueAsync(stringPreferencesKey(key), value?.toString()) /** @@ -726,8 +739,9 @@ abstract class BaseDataStoreHelper( * * @param key The key to store the value under * @param value The value to store + * @return The [Job] for the launched write — call [Job.join] to await completion. */ - protected fun writeEnumAsync(key: String, value: Enum<*>?) = + protected fun writeEnumAsync(key: String, value: Enum<*>?): Job = writeValueAsync(stringPreferencesKey(key), value?.name) /** diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 51fed03..d5bee8e 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,11 +1,13 @@ +import com.android.build.api.dsl.ApplicationExtension import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kover) } -android { +configure { namespace = "com.duck.app" compileSdk = libs.versions.compileSdk.get().toInt() @@ -30,15 +32,46 @@ android { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } - kotlin { - compilerOptions { - jvmTarget.set(JvmTarget.JVM_11) - } - } buildFeatures { compose = true } + + testOptions { + unitTests { + // Required for Robolectric: BaseDataStoreHelperTest runs on the JVM and + // needs the merged manifest + resources on the unit-test classpath. + isIncludeAndroidResources = true + } + } +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_11) + } +} + +kover { + reports { + // Coverage gate: `./gradlew :app:koverVerifyDebug` fails below this floor. + // Aggregated line coverage across com.duck.prefshelper.* (both helpers, now + // all JVM-tested via Robolectric). Set below current to catch regressions + // without tripping on minor refactors; raise as coverage improves. + verify { + rule { + minBound(70) + } + } + filters { + includes { + // Measure only the published library. The sample app (incl. the + // consumer com.duck.app.data.prefs.* classes, which the tests don't + // instantiate) is scaffolding, not the code under test. + classes("com.duck.prefshelper.*") + } + } + } } dependencies { @@ -54,13 +87,18 @@ dependencies { // implementation(libs.androidx.dataStore) implementation(project(":PrefsHelper")) + // Aggregate the library's coverage into this module's Kover report, + // since the tests that exercise PrefsHelper live here in :app. + kover(project(":PrefsHelper")) + + // Unit tests run on the JVM. BaseDataStoreHelperTest runs under Robolectric via the + // AndroidJUnit4 delegating runner, so DataStore coverage is visible to Kover (which + // cannot instrument on-device tests). No emulator required. testImplementation(libs.junit) testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) - androidTestImplementation(libs.androidx.test.ext.junit) - androidTestImplementation(libs.androidx.test.espresso.core) - androidTestImplementation(platform(libs.androidx.compose.bom)) - androidTestImplementation(libs.androidx.compose.ui.test.junit4) + testImplementation(libs.androidx.test.ext.junit) + testImplementation(libs.robolectric) + debugImplementation(libs.androidx.compose.ui.tooling) - debugImplementation(libs.androidx.compose.ui.test.manifest) } diff --git a/app/src/androidTest/java/com/duck/app/BaseDataStoreHelperTest.kt b/app/src/test/java/com/duck/app/BaseDataStoreHelperTest.kt similarity index 61% rename from app/src/androidTest/java/com/duck/app/BaseDataStoreHelperTest.kt rename to app/src/test/java/com/duck/app/BaseDataStoreHelperTest.kt index e9c170d..a2fca41 100644 --- a/app/src/androidTest/java/com/duck/app/BaseDataStoreHelperTest.kt +++ b/app/src/test/java/com/duck/app/BaseDataStoreHelperTest.kt @@ -8,8 +8,10 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.take +import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlin.time.Duration.Companion.milliseconds import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -38,6 +40,26 @@ class BaseDataStoreHelperTest { } } + /** + * DataStore async/delegate writes are fire-and-forget (`scope.launch`), so reading after a + * fixed [delay] is racy under device load — the write may not have hit disk yet. Poll [read] + * until it satisfies [predicate], or a generous timeout elapses, then return the latest value + * for assertion. Deterministic regardless of how busy the device is. + */ + private suspend fun awaitValue( + timeoutMs: Long = 5_000L, + predicate: (T) -> Boolean, + read: () -> T, + ): T { + val deadline = System.currentTimeMillis() + timeoutMs + var value = read() + while (!predicate(value) && System.currentTimeMillis() < deadline) { + delay(20.milliseconds) + value = read() + } + return value + } + @Test fun testWriteAndReadString() = runBlocking { dataStoreHelper.testWriteString("test_key", "test_value") @@ -244,13 +266,13 @@ class BaseDataStoreHelperTest { .collect { emissions.add(it) } } - delay(50) // Initial null emission + delay(50.milliseconds) // Initial null emission dataStoreHelper.testWriteString("multi_flow_key", "first") - delay(50) + delay(50.milliseconds) dataStoreHelper.testWriteString("multi_flow_key", "second") - delay(50) + delay(50.milliseconds) dataStoreHelper.testWriteString("multi_flow_key", "third") - delay(50) + delay(50.milliseconds) job.join() assertEquals(4, emissions.size) @@ -265,10 +287,10 @@ class BaseDataStoreHelperTest { val jobs = (1..20).map { index -> launch { dataStoreHelper.testWriteInt("concurrent_key", index) - delay(10) + delay(10.milliseconds) } } - jobs.forEach { it.join() } + jobs.joinAll() // Verify last write succeeded (any value 1-20 is acceptable) val result = dataStoreHelper.testReadIntValue("concurrent_key") @@ -278,41 +300,35 @@ class BaseDataStoreHelperTest { @Test fun testWriteStringAsync() = runBlocking { - dataStoreHelper.testWriteStringAsync("async_key", "async_value") - // Give async operation time to complete - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteStringAsync("async_key", "async_value").join() val value = dataStoreHelper.testReadStringValue("async_key") assertEquals("async_value", value) } @Test fun testWriteIntAsync() = runBlocking { - dataStoreHelper.testWriteIntAsync("async_key", 999) - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteIntAsync("async_key", 999).join() val value = dataStoreHelper.testReadIntValue("async_key") assertEquals(999, value) } @Test fun testWriteLongAsync() = runBlocking { - dataStoreHelper.testWriteLongAsync("async_key", 123123123L) - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteLongAsync("async_key", 123123123L).join() val value = dataStoreHelper.testReadLongValue("async_key") assertEquals(123123123L, value) } @Test fun testWriteDoubleAsync() = runBlocking { - dataStoreHelper.testWriteDoubleAsync("async_key", 9.99) - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteDoubleAsync("async_key", 9.99).join() val value = dataStoreHelper.testReadDoubleValue("async_key") assertEquals(9.99, value ?: 0.0, 0.01) } @Test fun testWriteBooleanAsync() = runBlocking { - dataStoreHelper.testWriteBooleanAsync("async_key", true) - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteBooleanAsync("async_key", true).join() val value = dataStoreHelper.testReadBooleanValue("async_key") assertTrue(value ?: false) } @@ -347,6 +363,66 @@ class BaseDataStoreHelperTest { assertEquals("fallback", value) } + @Test + fun testReadLongFlowWithDefault() = runBlocking { + val value = dataStoreHelper.testReadLongFlowWithDefault("nonexistent_key", 888L).first() + assertEquals(888L, value) + } + + @Test + fun testReadDoubleFlowWithDefault() = runBlocking { + val value = dataStoreHelper.testReadDoubleFlowWithDefault("nonexistent_key", 3.14).first() + assertEquals(3.14, value, 0.01) + } + + @Test + fun testReadBooleanFlowWithDefault() = runBlocking { + val value = dataStoreHelper.testReadBooleanFlowWithDefault("nonexistent_key", true).first() + assertTrue(value) + } + + @Test + fun testReadLocalDateTimeValueWithDefault() = runBlocking { + val default = java.time.LocalDateTime.of(2023, 11, 25, 10, 30, 45) + val value = dataStoreHelper.testReadLocalDateTimeValueWithDefault("nonexistent_key", default) + assertEquals(default, value) + } + + @Test + fun testReadLocalDateTimeFlowWithDefault() = runBlocking { + val default = java.time.LocalDateTime.of(2023, 11, 25, 10, 30, 45) + val value = dataStoreHelper.testReadLocalDateTimeFlowWithDefault("nonexistent_key", default).first() + assertEquals(default, value) + } + + @Test + fun testReadLocalDateValueWithDefault() = runBlocking { + val default = java.time.LocalDate.of(2023, 11, 25) + val value = dataStoreHelper.testReadLocalDateValueWithDefault("nonexistent_key", default) + assertEquals(default, value) + } + + @Test + fun testReadLocalDateFlowWithDefault() = runBlocking { + val default = java.time.LocalDate.of(2023, 11, 25) + val value = dataStoreHelper.testReadLocalDateFlowWithDefault("nonexistent_key", default).first() + assertEquals(default, value) + } + + @Test + fun testReadLocalTimeValueWithDefault() = runBlocking { + val default = java.time.LocalTime.of(14, 30, 45) + val value = dataStoreHelper.testReadLocalTimeValueWithDefault("nonexistent_key", default) + assertEquals(default, value) + } + + @Test + fun testReadLocalTimeFlowWithDefault() = runBlocking { + val default = java.time.LocalTime.of(14, 30, 45) + val value = dataStoreHelper.testReadLocalTimeFlowWithDefault("nonexistent_key", default).first() + assertEquals(default, value) + } + @Test fun testWriteAndReadLocalDateTime() = runBlocking { val dateTime = java.time.LocalDateTime.of(2023, 11, 25, 10, 30, 45) @@ -375,8 +451,7 @@ class BaseDataStoreHelperTest { @Test fun testWriteLocalDateTimeAsync() = runBlocking { val dateTime = java.time.LocalDateTime.of(2023, 12, 1, 8, 0, 0) - dataStoreHelper.testWriteLocalDateTimeAsync("datetime_key", dateTime) - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteLocalDateTimeAsync("datetime_key", dateTime).join() val value = dataStoreHelper.testReadLocalDateTimeValue("datetime_key") assertEquals(dateTime, value) } @@ -409,8 +484,7 @@ class BaseDataStoreHelperTest { @Test fun testWriteLocalDateAsync() = runBlocking { val date = java.time.LocalDate.of(2024, 1, 1) - dataStoreHelper.testWriteLocalDateAsync("date_key", date) - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteLocalDateAsync("date_key", date).join() val value = dataStoreHelper.testReadLocalDateValue("date_key") assertEquals(date, value) } @@ -443,8 +517,7 @@ class BaseDataStoreHelperTest { @Test fun testWriteLocalTimeAsync() = runBlocking { val time = java.time.LocalTime.of(9, 15, 0) - dataStoreHelper.testWriteLocalTimeAsync("time_key", time) - kotlinx.coroutines.delay(100) + dataStoreHelper.testWriteLocalTimeAsync("time_key", time).join() val value = dataStoreHelper.testReadLocalTimeValue("time_key") assertEquals(time, value) } @@ -453,29 +526,29 @@ class BaseDataStoreHelperTest { fun testWriteAndReadEnum() = runBlocking { // Test using property-based access (like NormalDataStore pattern) dataStoreHelper.testEnumProperty = TestEnum.VALUE_B - delay(100) - assertEquals(TestEnum.VALUE_B, dataStoreHelper.testEnumProperty) + val value = awaitValue(predicate = { it == TestEnum.VALUE_B }) { dataStoreHelper.testEnumProperty } + assertEquals(TestEnum.VALUE_B, value) } @Test fun testWriteNullEnum() = runBlocking { // Test null handling via direct method calls dataStoreHelper.testEnumProperty = TestEnum.VALUE_B - delay(100) - assertEquals(TestEnum.VALUE_B, dataStoreHelper.testEnumProperty) + assertEquals( + TestEnum.VALUE_B, + awaitValue(predicate = { it == TestEnum.VALUE_B }) { dataStoreHelper.testEnumProperty }, + ) dataStoreHelper.testEnumProperty = null - delay(100) - assertNull(dataStoreHelper.testEnumProperty) + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.testEnumProperty }) } @Test fun testReadEnumFlow() = runBlocking { // Test Flow-based enum reading via property dataStoreHelper.testEnumProperty = TestEnum.VALUE_C - delay(100) - val value = dataStoreHelper.testEnumPropertyFlow.first() - assertEquals(TestEnum.VALUE_C, value) + awaitValue(predicate = { it == TestEnum.VALUE_C }) { dataStoreHelper.testEnumProperty } + assertEquals(TestEnum.VALUE_C, dataStoreHelper.testEnumPropertyFlow.first()) } @Test @@ -504,8 +577,8 @@ class BaseDataStoreHelperTest { @Test fun testIntPrefDelegateRoundTripsValue() = runBlocking { dataStoreHelper.delegateInt = 42 - delay(100) - assertEquals(42, dataStoreHelper.delegateInt) + val value = awaitValue(predicate = { it == 42 }) { dataStoreHelper.delegateInt } + assertEquals(42, value) } @Test @@ -517,26 +590,24 @@ class BaseDataStoreHelperTest { @Test fun testNullableIntPrefDelegateRemovesKeyOnNull() = runBlocking { dataStoreHelper.delegateNullableInt = 7 - delay(100) - assertEquals(7, dataStoreHelper.delegateNullableInt) + assertEquals(7, awaitValue(predicate = { it == 7 }) { dataStoreHelper.delegateNullableInt }) dataStoreHelper.delegateNullableInt = null - delay(100) - assertNull(dataStoreHelper.delegateNullableInt) + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateNullableInt }) } @Test fun testIntPrefFlowEmitsDelegateWrites() = runBlocking { dataStoreHelper.delegateInt = 5 - delay(100) + awaitValue(predicate = { it == 5 }) { dataStoreHelper.delegateInt } assertEquals(5, dataStoreHelper.delegateIntFlow.first()) } @Test fun testEnumPrefDelegateRoundTrip() = runBlocking { dataStoreHelper.delegateEnum = TestEnum.VALUE_C - delay(100) - assertEquals(TestEnum.VALUE_C, dataStoreHelper.delegateEnum) + val value = awaitValue(predicate = { it == TestEnum.VALUE_C }) { dataStoreHelper.delegateEnum } + assertEquals(TestEnum.VALUE_C, value) } @Test @@ -545,6 +616,229 @@ class BaseDataStoreHelperTest { assertEquals(TestEnum.VALUE_A, dataStoreHelper.delegateEnum) } + // String delegate + @Test + fun testStringPrefDelegateReturnsDefaultWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertEquals("fallback", dataStoreHelper.delegateString) + } + + @Test + fun testStringPrefDelegateRoundTripsValue() = runBlocking { + dataStoreHelper.delegateString = "hello" + val value = awaitValue(predicate = { it == "hello" }) { dataStoreHelper.delegateString } + assertEquals("hello", value) + } + + @Test + fun testNullableStringPrefDelegateReturnsNullWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertNull(dataStoreHelper.delegateNullableString) + } + + @Test + fun testNullableStringPrefDelegateRemovesKeyOnNull() = runBlocking { + dataStoreHelper.delegateNullableString = "temp" + assertEquals("temp", awaitValue(predicate = { it == "temp" }) { dataStoreHelper.delegateNullableString }) + + dataStoreHelper.delegateNullableString = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateNullableString }) + } + + @Test + fun testStringPrefFlowEmitsDelegateWrites() = runBlocking { + dataStoreHelper.delegateString = "flowed" + awaitValue(predicate = { it == "flowed" }) { dataStoreHelper.delegateString } + assertEquals("flowed", dataStoreHelper.delegateStringFlow.first()) + } + + // Long delegate + @Test + fun testLongPrefDelegateReturnsDefaultWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertEquals(-1L, dataStoreHelper.delegateLong) + } + + @Test + fun testLongPrefDelegateRoundTripsValue() = runBlocking { + dataStoreHelper.delegateLong = 123456789L + val value = awaitValue(predicate = { it == 123456789L }) { dataStoreHelper.delegateLong } + assertEquals(123456789L, value) + } + + @Test + fun testLongPrefFlowEmitsDelegateWrites() = runBlocking { + dataStoreHelper.delegateLong = 42L + awaitValue(predicate = { it == 42L }) { dataStoreHelper.delegateLong } + assertEquals(42L, dataStoreHelper.delegateLongFlow.first()) + } + + // Double delegate + @Test + fun testDoublePrefDelegateReturnsDefaultWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertEquals(-1.0, dataStoreHelper.delegateDouble, 0.00001) + } + + @Test + fun testDoublePrefDelegateRoundTripsValue() = runBlocking { + dataStoreHelper.delegateDouble = 3.14159 + val value = awaitValue(predicate = { it == 3.14159 }) { dataStoreHelper.delegateDouble } + assertEquals(3.14159, value, 0.00001) + } + + @Test + fun testDoublePrefFlowEmitsDelegateWrites() = runBlocking { + dataStoreHelper.delegateDouble = 2.71828 + awaitValue(predicate = { it == 2.71828 }) { dataStoreHelper.delegateDouble } + assertEquals(2.71828, dataStoreHelper.delegateDoubleFlow.first(), 0.00001) + } + + // Boolean delegate + @Test + fun testBooleanPrefDelegateReturnsDefaultWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertEquals(false, dataStoreHelper.delegateBoolean) + } + + @Test + fun testBooleanPrefDelegateRoundTripsValue() = runBlocking { + dataStoreHelper.delegateBoolean = true + val value = awaitValue(predicate = { it }) { dataStoreHelper.delegateBoolean } + assertTrue(value) + } + + @Test + fun testBooleanPrefFlowEmitsDelegateWrites() = runBlocking { + dataStoreHelper.delegateBoolean = true + awaitValue(predicate = { it }) { dataStoreHelper.delegateBoolean } + assertEquals(true, dataStoreHelper.delegateBooleanFlow.first()) + } + + // Nullable Long delegate + @Test + fun testNullableLongPrefDelegateReturnsNullWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertNull(dataStoreHelper.delegateNullableLong) + } + + @Test + fun testNullableLongPrefDelegateRemovesKeyOnNull() = runBlocking { + dataStoreHelper.delegateNullableLong = 99L + assertEquals(99L, awaitValue(predicate = { it == 99L }) { dataStoreHelper.delegateNullableLong }) + + dataStoreHelper.delegateNullableLong = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateNullableLong }) + } + + // Nullable Double delegate + @Test + fun testNullableDoublePrefDelegateReturnsNullWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertNull(dataStoreHelper.delegateNullableDouble) + } + + @Test + fun testNullableDoublePrefDelegateRemovesKeyOnNull() = runBlocking { + dataStoreHelper.delegateNullableDouble = 1.5 + assertEquals(1.5, awaitValue(predicate = { it == 1.5 }) { dataStoreHelper.delegateNullableDouble } ?: 0.0, 0.00001) + + dataStoreHelper.delegateNullableDouble = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateNullableDouble }) + } + + // Nullable Boolean delegate + @Test + fun testNullableBooleanPrefDelegateReturnsNullWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertNull(dataStoreHelper.delegateNullableBoolean) + } + + @Test + fun testNullableBooleanPrefDelegateRemovesKeyOnNull() = runBlocking { + dataStoreHelper.delegateNullableBoolean = true + assertEquals(true, awaitValue(predicate = { it == true }) { dataStoreHelper.delegateNullableBoolean }) + + dataStoreHelper.delegateNullableBoolean = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateNullableBoolean }) + } + + // Nullable Enum delegate + @Test + fun testNullableEnumPrefDelegateReturnsNullWhenAbsent() = runBlocking { + dataStoreHelper.testClearPrefs() + assertNull(dataStoreHelper.delegateNullableEnum) + } + + @Test + fun testNullableEnumPrefDelegateRemovesKeyOnNull() = runBlocking { + dataStoreHelper.delegateNullableEnum = TestEnum.VALUE_B + assertEquals( + TestEnum.VALUE_B, + awaitValue(predicate = { it == TestEnum.VALUE_B }) { dataStoreHelper.delegateNullableEnum }, + ) + + dataStoreHelper.delegateNullableEnum = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateNullableEnum }) + } + + // LocalDateTime delegate + @Test + fun testLocalDateTimePrefDelegateRoundTripsValue() = runBlocking { + val dateTime = java.time.LocalDateTime.of(2023, 11, 25, 10, 30, 45) + dataStoreHelper.delegateLocalDateTime = dateTime + val value = awaitValue(predicate = { it == dateTime }) { dataStoreHelper.delegateLocalDateTime } + assertEquals(dateTime, value) + } + + @Test + fun testLocalDateTimePrefDelegateRemovesKeyOnNull() = runBlocking { + val dateTime = java.time.LocalDateTime.of(2023, 11, 25, 10, 30, 45) + dataStoreHelper.delegateLocalDateTime = dateTime + assertNotNull(awaitValue(predicate = { it == dateTime }) { dataStoreHelper.delegateLocalDateTime }) + + dataStoreHelper.delegateLocalDateTime = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateLocalDateTime }) + } + + // LocalDate delegate + @Test + fun testLocalDatePrefDelegateRoundTripsValue() = runBlocking { + val date = java.time.LocalDate.of(2023, 11, 25) + dataStoreHelper.delegateLocalDate = date + val value = awaitValue(predicate = { it == date }) { dataStoreHelper.delegateLocalDate } + assertEquals(date, value) + } + + @Test + fun testLocalDatePrefDelegateRemovesKeyOnNull() = runBlocking { + val date = java.time.LocalDate.of(2023, 11, 25) + dataStoreHelper.delegateLocalDate = date + assertNotNull(awaitValue(predicate = { it == date }) { dataStoreHelper.delegateLocalDate }) + + dataStoreHelper.delegateLocalDate = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateLocalDate }) + } + + // LocalTime delegate + @Test + fun testLocalTimePrefDelegateRoundTripsValue() = runBlocking { + val time = java.time.LocalTime.of(14, 30, 45) + dataStoreHelper.delegateLocalTime = time + val value = awaitValue(predicate = { it == time }) { dataStoreHelper.delegateLocalTime } + assertEquals(time, value) + } + + @Test + fun testLocalTimePrefDelegateRemovesKeyOnNull() = runBlocking { + val time = java.time.LocalTime.of(14, 30, 45) + dataStoreHelper.delegateLocalTime = time + assertNotNull(awaitValue(predicate = { it == time }) { dataStoreHelper.delegateLocalTime }) + + dataStoreHelper.delegateLocalTime = null + assertNull(awaitValue(predicate = { it == null }) { dataStoreHelper.delegateLocalTime }) + } + enum class TestEnum { VALUE_A, VALUE_B, VALUE_C } @@ -666,11 +960,45 @@ class BaseDataStoreHelperTest { val delegateIntFlow = intPrefFlow(KEY_DELEGATE_INT, defaultValue = -1) var delegateEnum by enumPref(KEY_DELEGATE_ENUM, default = TestEnum.VALUE_A) + var delegateString by stringPref(KEY_DELEGATE_STRING, defaultValue = "fallback") + var delegateNullableString by stringPref(KEY_DELEGATE_NULLABLE_STRING) + val delegateStringFlow = stringPrefFlow(KEY_DELEGATE_STRING, defaultValue = "fallback") + + var delegateLong by longPref(KEY_DELEGATE_LONG, defaultValue = -1L) + var delegateNullableLong by longPref(KEY_DELEGATE_NULLABLE_LONG) + val delegateLongFlow = longPrefFlow(KEY_DELEGATE_LONG, defaultValue = -1L) + + var delegateDouble by doublePref(KEY_DELEGATE_DOUBLE, defaultValue = -1.0) + var delegateNullableDouble by doublePref(KEY_DELEGATE_NULLABLE_DOUBLE) + val delegateDoubleFlow = doublePrefFlow(KEY_DELEGATE_DOUBLE, defaultValue = -1.0) + + var delegateBoolean by booleanPref(KEY_DELEGATE_BOOLEAN, defaultValue = false) + var delegateNullableBoolean by booleanPref(KEY_DELEGATE_NULLABLE_BOOLEAN) + val delegateBooleanFlow = booleanPrefFlow(KEY_DELEGATE_BOOLEAN, defaultValue = false) + + var delegateNullableEnum by enumPref(KEY_DELEGATE_NULLABLE_ENUM) + + var delegateLocalDateTime by localDateTimePref(KEY_DELEGATE_LDT) + var delegateLocalDate by localDatePref(KEY_DELEGATE_LD) + var delegateLocalTime by localTimePref(KEY_DELEGATE_LT) + companion object { private const val KEY_TEST_ENUM = "test_enum_key" private const val KEY_DELEGATE_INT = "delegate_int_key" private const val KEY_DELEGATE_NULLABLE_INT = "delegate_nullable_int_key" private const val KEY_DELEGATE_ENUM = "delegate_enum_key" + private const val KEY_DELEGATE_STRING = "delegate_string_key" + private const val KEY_DELEGATE_NULLABLE_STRING = "delegate_nullable_string_key" + private const val KEY_DELEGATE_LONG = "delegate_long_key" + private const val KEY_DELEGATE_NULLABLE_LONG = "delegate_nullable_long_key" + private const val KEY_DELEGATE_DOUBLE = "delegate_double_key" + private const val KEY_DELEGATE_NULLABLE_DOUBLE = "delegate_nullable_double_key" + private const val KEY_DELEGATE_BOOLEAN = "delegate_boolean_key" + private const val KEY_DELEGATE_NULLABLE_BOOLEAN = "delegate_nullable_boolean_key" + private const val KEY_DELEGATE_NULLABLE_ENUM = "delegate_nullable_enum_key" + private const val KEY_DELEGATE_LDT = "delegate_ldt_key" + private const val KEY_DELEGATE_LD = "delegate_ld_key" + private const val KEY_DELEGATE_LT = "delegate_lt_key" } suspend fun testClearPrefs() = clearPrefs() diff --git a/app/src/test/java/com/duck/app/BasePrefsHelperTest.kt b/app/src/test/java/com/duck/app/BasePrefsHelperTest.kt index 555ff4e..0dfbd04 100644 --- a/app/src/test/java/com/duck/app/BasePrefsHelperTest.kt +++ b/app/src/test/java/com/duck/app/BasePrefsHelperTest.kt @@ -4,6 +4,7 @@ import android.content.SharedPreferences import com.duck.prefshelper.BasePrefsHelper import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue @@ -404,6 +405,190 @@ class BasePrefsHelperTest { verify(mockEditor).apply() } + // Nullable String delegate + @Test + fun testNullableStringPrefReturnsNullWhenAbsent() { + `when`(mockSharedPreferences.contains("nullable_string_key")).thenReturn(false) + assertNull(prefsHelper.nullableString) + } + + @Test + fun testNullableStringPrefReturnsValueWhenPresent() { + `when`(mockSharedPreferences.contains("nullable_string_key")).thenReturn(true) + `when`(mockSharedPreferences.getString("nullable_string_key", null)).thenReturn("stored") + assertEquals("stored", prefsHelper.nullableString) + } + + @Test + fun testNullableStringPrefRemovesKeyOnNullAssignment() { + prefsHelper.nullableString = null + verify(mockEditor).remove("nullable_string_key") + verify(mockEditor).apply() + } + + // Long delegate + @Test + fun testLongPrefDelegateGet() { + `when`(mockSharedPreferences.getLong("long_key", 5L)).thenReturn(999L) + assertEquals(999L, prefsHelper.longValue) + } + + @Test + fun testLongPrefDelegateSet() { + prefsHelper.longValue = 4242L + verify(mockEditor).putLong("long_key", 4242L) + verify(mockEditor).apply() + } + + @Test + fun testNullableLongPrefReturnsNullWhenAbsent() { + `when`(mockSharedPreferences.contains("nullable_long_key")).thenReturn(false) + assertNull(prefsHelper.nullableLong) + } + + @Test + fun testNullableLongPrefReturnsValueWhenPresent() { + `when`(mockSharedPreferences.contains("nullable_long_key")).thenReturn(true) + `when`(mockSharedPreferences.getLong("nullable_long_key", 0L)).thenReturn(55L) + assertEquals(55L, prefsHelper.nullableLong) + } + + @Test + fun testNullableLongPrefRemovesKeyOnNullAssignment() { + prefsHelper.nullableLong = null + verify(mockEditor).remove("nullable_long_key") + verify(mockEditor).apply() + } + + // Boolean delegate + @Test + fun testBooleanPrefDelegateGet() { + `when`(mockSharedPreferences.getBoolean("bool_key", true)).thenReturn(false) + assertFalse(prefsHelper.boolValue) + } + + @Test + fun testBooleanPrefDelegateSet() { + prefsHelper.boolValue = false + verify(mockEditor).putBoolean("bool_key", false) + verify(mockEditor).apply() + } + + @Test + fun testNullableBooleanPrefReturnsNullWhenAbsent() { + `when`(mockSharedPreferences.contains("nullable_bool_key")).thenReturn(false) + assertNull(prefsHelper.nullableBool) + } + + @Test + fun testNullableBooleanPrefReturnsValueWhenPresent() { + `when`(mockSharedPreferences.contains("nullable_bool_key")).thenReturn(true) + `when`(mockSharedPreferences.getBoolean("nullable_bool_key", false)).thenReturn(true) + assertEquals(true, prefsHelper.nullableBool) + } + + @Test + fun testNullableBooleanPrefRemovesKeyOnNullAssignment() { + prefsHelper.nullableBool = null + verify(mockEditor).remove("nullable_bool_key") + verify(mockEditor).apply() + } + + // Date delegate + @Test + fun testDatePrefDelegateGet() { + `when`(mockSharedPreferences.getLong("date_delegate_key", -1L)).thenReturn(1234567890000L) + assertEquals(Date(1234567890000L), prefsHelper.dateValue) + } + + @Test + fun testDatePrefDelegateSet() { + prefsHelper.dateValue = Date(1234567890000L) + verify(mockEditor).putLong("date_delegate_key", 1234567890000L) + verify(mockEditor).apply() + } + + @Test + fun testDatePrefDelegateReturnsNullWhenNotSet() { + `when`(mockSharedPreferences.getLong("date_delegate_key", -1L)).thenReturn(-1L) + assertNull(prefsHelper.dateValue) + } + + // LocalDateTime delegate + @Test + fun testLocalDateTimePrefDelegateGet() { + val dateTime = LocalDateTime.of(2023, 11, 25, 10, 30, 45) + `when`(mockSharedPreferences.getLong("ldt_delegate_key", -1L)) + .thenReturn(dateTime.toEpochSecond(ZoneOffset.UTC)) + assertEquals(dateTime, prefsHelper.localDateTimeValue) + } + + @Test + fun testLocalDateTimePrefDelegateSet() { + val dateTime = LocalDateTime.of(2023, 11, 25, 10, 30, 45) + prefsHelper.localDateTimeValue = dateTime + verify(mockEditor).putLong("ldt_delegate_key", dateTime.toEpochSecond(ZoneOffset.UTC)) + verify(mockEditor).apply() + } + + // LocalDate delegate + @Test + fun testLocalDatePrefDelegateGet() { + val date = LocalDate.of(2023, 11, 25) + `when`(mockSharedPreferences.getLong("ld_delegate_key", -1L)).thenReturn(date.toEpochDay()) + assertEquals(date, prefsHelper.localDateValue) + } + + @Test + fun testLocalDatePrefDelegateSet() { + val date = LocalDate.of(2023, 11, 25) + prefsHelper.localDateValue = date + verify(mockEditor).putLong("ld_delegate_key", date.toEpochDay()) + verify(mockEditor).apply() + } + + // LocalTime delegate + @Test + fun testLocalTimePrefDelegateGet() { + val time = LocalTime.of(14, 30, 45) + `when`(mockSharedPreferences.getLong("lt_delegate_key", -1L)).thenReturn(time.toSecondOfDay().toLong()) + assertEquals(time, prefsHelper.localTimeValue) + } + + @Test + fun testLocalTimePrefDelegateSet() { + val time = LocalTime.of(14, 30, 45) + prefsHelper.localTimeValue = time + verify(mockEditor).putLong("lt_delegate_key", time.toSecondOfDay().toLong()) + verify(mockEditor).apply() + } + + // Nullable Enum delegate + @Test + fun testNullableEnumPrefDelegateReturnsNullWhenAbsent() { + `when`(mockSharedPreferences.getString("nullable_enum_key", "")).thenReturn("") + assertNull(prefsHelper.nullableEnumValue) + } + + @Test + fun testNullableEnumPrefDelegateReturnsValueWhenPresent() { + `when`(mockSharedPreferences.getString("nullable_enum_key", "")).thenReturn("VALUE_B") + assertEquals(TestEnum.VALUE_B, prefsHelper.nullableEnumValue) + } + + @Test + fun testNullableEnumPrefDelegateReturnsNullForInvalidValue() { + `when`(mockSharedPreferences.getString("nullable_enum_key", "")).thenReturn("NOT_A_VALUE") + assertNull(prefsHelper.nullableEnumValue) + } + + @Test + fun testNullableEnumPrefDelegateSetNull() { + prefsHelper.nullableEnumValue = null + verify(mockEditor).putString("nullable_enum_key", "") + verify(mockEditor).apply() + } + enum class TestEnum { VALUE_A, VALUE_B, VALUE_C } @@ -413,8 +598,18 @@ class BasePrefsHelperTest { get() = mockSharedPreferences var stringValue by stringPref("string_key", defaultValue = "fallback") + var nullableString by stringPref("nullable_string_key") var intValue by intPref("int_key", defaultValue = 10) var maybeInt by intPref("maybe_int") + var longValue by longPref("long_key", defaultValue = 5L) + var nullableLong by longPref("nullable_long_key") + var boolValue by booleanPref("bool_key", defaultValue = true) + var nullableBool by booleanPref("nullable_bool_key") + var dateValue by datePref("date_delegate_key") + var localDateTimeValue by localDateTimePref("ldt_delegate_key") + var localDateValue by localDatePref("ld_delegate_key") + var localTimeValue by localTimePref("lt_delegate_key") var enumValue by enumPref("enum_key", TestEnum.VALUE_A) + var nullableEnumValue by enumPref("nullable_enum_key") } } diff --git a/app/src/test/resources/robolectric.properties b/app/src/test/resources/robolectric.properties new file mode 100644 index 0000000..512cfae --- /dev/null +++ b/app/src/test/resources/robolectric.properties @@ -0,0 +1,4 @@ +# Robolectric runtime SDK. Pinned because the module's targetSdk (37) has no +# Robolectric android-all image yet; 36 (Android 16) is the newest Robolectric +# 4.16 ships and is closest to compileSdk/targetSdk. Bump when 37 is published. +sdk=36 diff --git a/build.gradle.kts b/build.gradle.kts index db325a3..63ad219 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,6 +4,7 @@ plugins { alias(libs.plugins.android.library) apply false alias(libs.plugins.kotlin.compose) apply false alias(libs.plugins.dokka) apply false + alias(libs.plugins.kover) apply false } tasks.wrapper { diff --git a/gradle.properties b/gradle.properties index bbcdae4..01d307e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -23,13 +23,7 @@ kotlin.code.style=official android.nonTransitiveRClass=true # Dokka v2 org.jetbrains.dokka.experimental.gradle.pluginMode=V2EnabledWithHelpers -android.defaults.buildfeatures.resvalues=true -android.sdk.defaultTargetSdkToCompileSdkIfUnset=false -android.enableAppCompileTimeRClass=false -android.usesSdkInManifest.disallowed=false android.uniquePackageNames=false android.dependency.useConstraints=true android.r8.strictFullModeForKeepRules=false -android.r8.optimizedResourceShrinking=false -android.newDsl=false #org.jetbrains.dokka.experimental.gradle.pluginMode=V2Enabled \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5cbfcb5..bd92e6e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,29 +1,37 @@ [versions] compileSdk = "37" targetSdk = "37" -gradle = "9.2.0" -kotlin = "2.3.21" +gradle = "9.2.1" +kotlin = "2.4.0" dokka = "2.2.0" +kover = "0.9.8" dataStore = "1.2.1" mockitoCore = "5.23.0" mockitoKotlin = "6.3.0" +robolectric = "4.16.1" +coreKtx = "1.19.0" +appcompat = "1.7.1" +lifecycleRuntime = "2.10.0" +activityCompose = "1.13.0" +composeBom = "2026.05.01" +testExtJunit = "1.3.0" +espressoCore = "3.7.0" +junit = "4.13.2" [libraries] -androidx-core-ktx = { module = "androidx.core:core-ktx", version = "1.18.0" } -androidx-appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } -androidx-lifecycle-runtime = { module = "androidx.lifecycle:lifecycle-runtime", version = "2.10.0" } -androidx-activity-compose = { module = "androidx.activity:activity-compose", version = "1.13.0" } -androidx-compose-bom = { module = "androidx.compose:compose-bom", version = "2026.04.01" } +androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" } +androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "appcompat" } +androidx-lifecycle-runtime = { module = "androidx.lifecycle:lifecycle-runtime", version.ref = "lifecycleRuntime" } +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } +androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" } androidx-compose-ui = { module = "androidx.compose.ui:ui" } androidx-compose-ui-graphics = { module = "androidx.compose.ui:ui-graphics" } androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" } androidx-compose-material3 = { module = "androidx.compose.material3:material3" } androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" } -androidx-compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4" } -androidx-compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" } -androidx-test-ext-junit = { module = "androidx.test.ext:junit", version = "1.3.0" } -androidx-test-espresso-core = { module = "androidx.test.espresso:espresso-core", version = "3.7.0" } -junit = { module = "junit:junit", version = "4.13.2" } +androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "testExtJunit" } +androidx-test-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "espressoCore" } +junit = { module = "junit:junit", version.ref = "junit" } androidx-dataStore = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "dataStore" } @@ -31,9 +39,11 @@ android-documentation-plugin = { module = "org.jetbrains.dokka:android-documenta mockito-core = { module = "org.mockito:mockito-core", version.ref = "mockitoCore" } mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockitoKotlin" } +robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" } [plugins] android-application = { id = "com.android.application", version.ref = "gradle" } android-library = { id = "com.android.library", version.ref = "gradle" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } -dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } \ No newline at end of file +dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } +kover = { id = "org.jetbrains.kotlinx.kover", version.ref = "kover" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c..b1b8ef5 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index b0e6cef..f193d72 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,9 @@ -#Thu Apr 24 13:42:00 BST 2025 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0..b9bb139 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,81 +15,114 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd3..24c62d5 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,19 +13,22 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,15 +43,15 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -56,34 +59,24 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL%