feat(timers): the timers tab, and the pill that finally has something to show

Multiple concurrent timers with labels, presets, add, pause, reset and +1 min.
The setup panel is inline on an empty tab, so the first timer costs no
navigation.

The live pill has been waiting since M4 for something that could start a
timer. It now goes through the engine rather than the repository, because a
scheduler registration and a foreground service have to move with the state —
its own contract is unchanged.

Three new architecture rules keep it that way: no screen may name the
scheduler, the service or AlarmManager, and a second MediaPlayer anywhere
outside the ring path fails the build.
This commit is contained in:
makiolaj committed 2026-09-12 16:48:36 +02:00
1 parent 7f9219e929
commit b67142a727
24 files changed
+2733 -12

No files matched your search

@@ -0,0 +1,105 @@
package de.jeanlucmakiola.clockula.testing
import de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.clockula.data.timers.TimerRepository
import de.jeanlucmakiola.clockula.data.timers.TimerRingStateStore
import de.jeanlucmakiola.clockula.timer.AlarmRingStatus
import de.jeanlucmakiola.clockula.timer.TimerEngine
import de.jeanlucmakiola.clockula.timer.TimerScheduler
import de.jeanlucmakiola.clockula.timer.TimerServiceHandle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import de.jeanlucmakiola.floret.prefs.PrefStore
import kotlin.time.Duration
import kotlin.time.Instant
/**
* The expiry slot, held as **the value it currently holds** rather than as a
* call log: a test then asserts what AlarmManager would be holding, which is
* the thing that wakes the device (M3's shape, M6 D30).
*/
class FakeTimerScheduler : TimerScheduler {
var expiryAt: Duration? = null
private set
private val log = mutableListOf<Duration?>()
/** Every transition, in order — null for a cancel. */
val scheduled: List<Duration?> get() = log.toList()
override fun scheduleExpiry(at: Duration) {
expiryAt = at
log += at
}
override fun cancelExpiry() {
expiryAt = null
log += null
}
}
/** The foreground service's up/down transitions, in order — the order is the contract (D6). */
class FakeTimerServiceHandle : TimerServiceHandle {
var active: Boolean = false
private set
private val log = mutableListOf<Boolean>()
val transitions: List<Boolean> get() = log.toList()
override fun sync(active: Boolean) {
this.active = active
log += active
}
}
/** "Is an alarm ringing", as a settable boolean whose flow re-emits (D9). */
class FakeAlarmRingStatus(ringing: Boolean = false) : AlarmRingStatus {
private val state = MutableStateFlow(ringing)
var ringing: Boolean
get() = state.value
set(value) {
state.value = value
}
override fun isRinging(): Flow<Boolean> = state
override suspend fun currentlyRinging(): Boolean = state.value
}
/**
* A real [de.jeanlucmakiola.clockula.timer.TimerEngine] over a caller-supplied
* repository and an in-memory store — the pill's arrangement (D25), where the
* repository is the one whose call log the older cases assert on.
*/
class TimerEngineSeams(
val timers: TimerRepository,
now: Instant = T0,
uptime: Duration = Duration.ZERO,
) {
val store: PrefStore = PrefStore(InMemoryPreferencesDataStore())
val settings: SettingsPrefs = SettingsPrefs(store)
val ringState: TimerRingStateStore = TimerRingStateStore(store)
val scheduler: FakeTimerScheduler = FakeTimerScheduler()
val service: FakeTimerServiceHandle = FakeTimerServiceHandle()
val alarmRing: FakeAlarmRingStatus = FakeAlarmRingStatus()
val rebootRepair: RecordingRebootRepair = RecordingRebootRepair()
val wallClock: FakeWallClock = FakeWallClock(now)
val elapsed: FakeElapsedRealtimeClock = FakeElapsedRealtimeClock(uptime)
val engine: TimerEngine = TimerEngine(
timers = timers,
settings = settings,
ringState = ringState,
scheduler = scheduler,
service = service,
alarmRing = alarmRing,
rebootRepair = rebootRepair,
elapsed = elapsed,
wall = wallClock,
)
}
@@ -0,0 +1,128 @@
package de.jeanlucmakiola.clockula.testing
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import de.jeanlucmakiola.clockula.data.prefs.BootStateStore
import de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.clockula.data.timers.TimerMapper
import de.jeanlucmakiola.clockula.data.timers.TimerRepository
import de.jeanlucmakiola.clockula.data.timers.TimerRepositoryImpl
import de.jeanlucmakiola.clockula.data.timers.TimerRingStateStore
import de.jeanlucmakiola.clockula.domain.Timer
import de.jeanlucmakiola.clockula.system.RebootRepair
import de.jeanlucmakiola.clockula.timer.TimerEngine
import de.jeanlucmakiola.floret.prefs.PrefStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.Job
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import java.nio.file.Path
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
/**
* The **real** [TimerEngine] over the fake DAO, the three fake seams and a real
* DataStore under a `@TempDir` — `AlarmEngineHarness`'s arrangement, for the
* other engine. The reboot gate is the real [RebootRepair] over the real
* repository, so "the second call of a boot does not repair again" is the
* production gate and not a fake's counter.
*/
class TimerEngineHarness(
tempDir: Path,
storeScope: CoroutineScope,
now: Instant = T0,
uptime: Duration = 1_000.seconds,
val timerDao: FakeTimerDao = FakeTimerDao(),
) {
val wallClock: FakeWallClock = FakeWallClock(now)
val elapsed: FakeElapsedRealtimeClock = FakeElapsedRealtimeClock(uptime)
val scheduler: FakeTimerScheduler = FakeTimerScheduler()
val service: FakeTimerServiceHandle = FakeTimerServiceHandle()
val alarmRing: FakeAlarmRingStatus = FakeAlarmRingStatus()
val bootIds: FakeBootIdProvider = FakeBootIdProvider()
val ticker: FakeTicker = FakeTicker()
val stateDao: FakeAlarmStateDao = FakeAlarmStateDao()
val alarmScheduler: FakeAlarmScheduler = FakeAlarmScheduler()
val ringCoordinator: FakeRingCoordinator = FakeRingCoordinator()
/**
* Counted, so "the session anchor was persisted **once** across three reads"
* is assertable without reaching into the store (D15). Nothing else in an
* engine pass writes a preference, so a count here is the anchor's.
*/
val dataStore: CountingPreferencesDataStore = CountingPreferencesDataStore(
PreferenceDataStoreFactory.create(
scope = storeScope,
produceFile = { tempDir.resolve("clockula_prefs_test.preferences_pb").toFile() },
),
)
val store: PrefStore = PrefStore(dataStore)
val settings: SettingsPrefs = SettingsPrefs(store)
val ringState: TimerRingStateStore = TimerRingStateStore(store)
val timers: TimerRepository = TimerRepositoryImpl(timerDao, elapsed, wallClock)
val stopwatch: RecordingStopwatchRepository = RecordingStopwatchRepository()
val rebootRepair: RebootRepair = RebootRepair(
bootIds = bootIds,
bootState = BootStateStore(store),
timers = timers,
stopwatch = stopwatch,
)
val engine: TimerEngine = TimerEngine(
timers = timers,
settings = settings,
ringState = ringState,
scheduler = scheduler,
service = service,
alarmRing = alarmRing,
rebootRepair = rebootRepair,
elapsed = elapsed,
wall = wallClock,
)
/** Inserts a timer straight into storage, bypassing the engine. */
suspend fun given(timer: Timer): Timer {
timerDao.insert(TimerMapper.toEntity(timer))
return timer
}
/** What the table holds for [id] right now, read through the mapper. */
suspend fun stored(id: Long): Timer? = timers.find(id)
}
/** A [DataStore] that counts the transactions taken against it. */
class CountingPreferencesDataStore(
private val delegate: DataStore<Preferences>,
) : DataStore<Preferences> {
var writes: Int = 0
private set
override val data: Flow<Preferences> get() = delegate.data
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences {
writes++
return delegate.updateData(transform)
}
}
/** The harness on `runTest`'s own scheduler, so nothing waits on a real clock. */
fun TestScope.timerEngineHarness(
tempDir: Path,
now: Instant = T0,
uptime: Duration = 1_000.seconds,
timerDao: FakeTimerDao = FakeTimerDao(),
): TimerEngineHarness = TimerEngineHarness(
tempDir = tempDir,
storeScope = CoroutineScope(UnconfinedTestDispatcher(testScheduler) + Job()),
now = now,
uptime = uptime,
timerDao = timerDao,
)
@@ -0,0 +1,387 @@
package de.jeanlucmakiola.clockula.ui.timers
import androidx.lifecycle.SavedStateHandle
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.clockula.domain.Ringtones
import de.jeanlucmakiola.clockula.domain.TimerState
import de.jeanlucmakiola.clockula.domain.timer.TimerMode
import de.jeanlucmakiola.clockula.testing.FakeRingtoneCatalog
import de.jeanlucmakiola.clockula.testing.FakeRingtonePreviewer
import de.jeanlucmakiola.clockula.testing.MainDispatcherExtension
import de.jeanlucmakiola.clockula.testing.PreviewEvent
import de.jeanlucmakiola.clockula.testing.T0
import de.jeanlucmakiola.clockula.testing.TimerEngineHarness
import de.jeanlucmakiola.clockula.testing.expiredTimer
import de.jeanlucmakiola.clockula.testing.idleTimer
import de.jeanlucmakiola.clockula.testing.pausedTimer
import de.jeanlucmakiola.clockula.testing.runningTimerWith
import de.jeanlucmakiola.clockula.testing.timerEngineHarness
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
/**
* §5.13 — 19 cases. The timer editor writes as the user goes, exactly as the
* alarm editor does (M5 D22/D24), and it owns exactly one override: the
* ringtone, through M5's picker (D27). Deleting goes through the engine, so a
* *ringing* timer cannot be deleted into a stuck ring (D2).
*/
class TimerEditorViewModelTest {
@JvmField
@RegisterExtension
val main = MainDispatcherExtension()
private val catalog = FakeRingtoneCatalog()
private val previewer = FakeRingtonePreviewer()
private val uptime: Duration = 1_000.seconds
private fun TestScope.editor(harness: TimerEngineHarness, timerId: Long = 1L) =
TimerEditorViewModel(
savedStateHandle = SavedStateHandle(mapOf(TimerRoutes.ARG_TIMER_ID to timerId)),
timers = harness.timers,
engine = harness.engine,
settings = harness.settings,
ringtones = catalog,
preview = previewer,
appScope = this,
)
private fun TimerEditorViewModel.editing(): TimerEditorUiState.Editing =
state.value as TimerEditorUiState.Editing
/** §5.13 #1 */
@Test
fun `an id no timer has is already gone`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
val viewModel = editor(harness, timerId = 404L)
advanceUntilIdle()
assertThat(viewModel.state.value).isEqualTo(TimerEditorUiState.Gone)
}
/** §5.13 #2 */
@Test
fun `rapid typing stores the last keystroke, in order`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L, label = ""))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onLabelTyped("P")
viewModel.onLabelTyped("Pa")
viewModel.onLabelTyped("Pas")
viewModel.onLabelTyped("Pasta")
advanceUntilIdle()
assertThat(harness.timerDao.stored.single().label).isEqualTo("Pasta")
}
/** §5.13 #3 */
@Test
fun `leaving the editor does not lose the last keystroke`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L, label = ""))
val viewModel = editor(harness)
viewModel.onLabelTyped("Pasta")
viewModel.onCleared()
advanceUntilIdle()
assertThat(harness.timerDao.stored.single().label).isEqualTo("Pasta")
}
/** §5.13 #4 */
@Test
fun `only an idle timer's length may be edited`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val rows = listOf(
idleTimer(id = 1L),
runningTimerWith(id = 1L, left = 4.minutes, elapsedNow = uptime, wallNow = T0),
pausedTimer(id = 1L, remaining = 2.minutes),
expiredTimer(id = 1L),
)
val answers = rows.map { row ->
val harness = timerEngineHarness(tempDir.resolve(row.state.name).also { it.toFile().mkdirs() })
harness.given(row)
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.editing().mode to viewModel.editing().canEditDuration
}
assertThat(answers).containsExactly(
TimerMode.IDLE to true,
TimerMode.RUNNING to false,
TimerMode.PAUSED to false,
TimerMode.EXPIRED to false,
).inOrder()
}
/** §5.13 #5 */
@Test
fun `committing a duration on an idle timer moves its remaining with it`(
@TempDir tempDir: Path,
) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L, duration = 5.minutes))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onDurationCommitted(90.seconds)
advanceUntilIdle()
val stored = harness.stored(1L)!!
assertThat(stored.duration to stored.remaining).isEqualTo(90.seconds to 90.seconds)
}
/** §5.13 #6 */
@Test
fun `committing a duration on a running timer changes nothing`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(runningTimerWith(id = 1L, left = 4.minutes, elapsedNow = uptime, wallNow = T0))
val viewModel = editor(harness)
advanceUntilIdle()
val before = harness.timerDao.stored
viewModel.onDurationCommitted(90.seconds)
advanceUntilIdle()
assertThat(harness.timerDao.stored).isEqualTo(before)
}
/** §5.13 #7 */
@Test
fun `a timer with no sound of its own inherits the app default`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.settings.setTimerRingtoneUri("content://media/2")
harness.given(idleTimer(id = 1L, ringtoneUri = null))
val viewModel = editor(harness)
advanceUntilIdle()
val ringtone = viewModel.editing().ringtone
assertThat(ringtone.inherited to ringtone.effectiveUri)
.isEqualTo(true to "content://media/2")
}
/** §5.13 #8 */
@Test
fun `a sound, then the app default, then silence all store what they say`(
@TempDir tempDir: Path,
) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L))
val viewModel = editor(harness)
advanceUntilIdle()
val stored = listOf("content://media/1", null, Ringtones.SILENT_URI).map { choice ->
viewModel.onRingtoneChosen(choice)
advanceUntilIdle()
harness.stored(1L)!!.ringtoneUri
}
assertThat(stored).containsExactly("content://media/1", null, Ringtones.SILENT_URI).inOrder()
}
/** §5.13 #9 */
@Test
fun `an unreadable sound is reported, never rewritten`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
catalog.unplayable = setOf("content://media/1")
harness.given(idleTimer(id = 1L, ringtoneUri = "content://media/1"))
val viewModel = editor(harness)
advanceUntilIdle()
assertThat(
viewModel.editing().ringtone.unavailable to harness.stored(1L)!!.ringtoneUri,
).isEqualTo(true to "content://media/1")
}
/** §5.13 #10 */
@Test
fun `typing waits on no provider round-trip`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L, label = "P", ringtoneUri = "content://media/1"))
val viewModel = editor(harness)
advanceUntilIdle()
check(viewModel.editing().ringtone.title == "Argon")
val queriesAfterLoad = catalog.metadataCalls
repeat(12) { viewModel.onLabelTyped("P".repeat(it + 1)) }
advanceUntilIdle()
assertThat(catalog.metadataCalls).isEqualTo(queriesAfterLoad)
}
/** §5.13 #11 */
@Test
fun `opening the picker loads the device's tones once`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onOpenRingtonePicker()
advanceUntilIdle()
assertThat(catalog.alarmTonesCalls).isEqualTo(1)
}
/** §5.13 #12 */
@Test
fun `closing the picker stops the preview`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onPreview("content://media/1")
advanceUntilIdle()
viewModel.onCloseRingtonePicker()
advanceUntilIdle()
assertThat(previewer.events.last()).isEqualTo(PreviewEvent.Stopped)
}
/** §5.13 #13 */
@Test
fun `leaving the editor stops the preview`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onPreview("content://media/1")
advanceUntilIdle()
viewModel.onCleared()
advanceUntilIdle()
assertThat(previewer.events.last()).isEqualTo(PreviewEvent.Stopped)
}
/** §5.13 #14 */
@Test
fun `a second preview stops the first before it plays`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onPreview("content://media/1")
advanceUntilIdle()
viewModel.onPreview("content://media/2")
advanceUntilIdle()
assertThat(previewer.events).containsExactly(
PreviewEvent.Played("content://media/1"),
PreviewEvent.Stopped,
PreviewEvent.Played("content://media/2"),
).inOrder()
}
/** §5.13 #15 */
@Test
fun `previewing nothing or silence only stops`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(idleTimer(id = 1L))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onPreview(null)
viewModel.onPreview(Ringtones.SILENT_URI)
advanceUntilIdle()
assertThat(previewer.events.filterIsInstance<PreviewEvent.Played>()).isEmpty()
assertThat(previewer.events).isNotEmpty()
}
/** §5.13 #16 */
@Test
fun `deleting takes the timer, the state and the ring session with it`(
@TempDir tempDir: Path,
) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(expiredTimer(id = 1L))
harness.ringState.set(T0 - 30.seconds)
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onDelete()
advanceUntilIdle()
assertThat(harness.timerDao.stored).isEmpty()
assertThat(viewModel.state.value to harness.ringState.current())
.isEqualTo(TimerEditorUiState.Gone to null)
}
/** §5.13 #17 */
@Test
fun `deleting a running timer cancels its expiry slot`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
harness.given(runningTimerWith(id = 1L, left = 4.minutes, elapsedNow = uptime, wallNow = T0))
harness.engine.resync()
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onDelete()
advanceUntilIdle()
assertThat(harness.scheduler.expiryAt).isNull()
}
/** §5.13 #18 */
@Test
fun `a grant that cannot be made persistent is disclosed, not refused`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir)
catalog.canPersist = false
harness.given(idleTimer(id = 1L))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onDocumentPicked("content://docs/a")
advanceUntilIdle()
assertThat(
harness.stored(1L)!!.ringtoneUri to viewModel.editing().ringtone.accessMayLapse,
).isEqualTo("content://docs/a" to true)
}
/** §5.13 #19 */
@Test
fun `a keystroke racing the expiry write loses neither`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val harness = timerEngineHarness(tempDir)
harness.given(runningTimerWith(id = 1L, left = 1.seconds, elapsedNow = uptime - 1.minutes))
val viewModel = editor(harness)
advanceUntilIdle()
viewModel.onLabelTyped("Pasta")
harness.engine.onExpiryDue()
advanceUntilIdle()
val stored = harness.stored(1L)!!
assertThat(stored.label to stored.state).isEqualTo("Pasta" to TimerState.EXPIRED)
}
}
@@ -0,0 +1,138 @@
package de.jeanlucmakiola.clockula.ui.timers
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.clockula.domain.Timer
import de.jeanlucmakiola.clockula.domain.timer.TimerMode
import de.jeanlucmakiola.clockula.testing.T0
import de.jeanlucmakiola.clockula.testing.expiredTimer
import de.jeanlucmakiola.clockula.testing.idleTimer
import de.jeanlucmakiola.clockula.testing.pausedTimer
import de.jeanlucmakiola.clockula.testing.runningTimerWith
import org.junit.jupiter.api.Test
import kotlin.time.Duration
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
/**
* §5.11 — 11 cases. The tab is a list in **storage order**, never in subject
* order (D22): an expired timer does not jump to the top, because a row that
* moves under a thumb is worse than a row the user has to look for.
*/
class TimerListRowsTest {
private val now: Duration = 1_000.seconds
private val wall: Instant = T0
private fun rows(
timers: List<Timer>,
elapsedRealtime: Duration = now,
wallClock: Instant = wall,
): List<TimerRowState> = TimerListRows.from(timers, elapsedRealtime, wallClock)
/** §5.11 #1 */
@Test
fun `no timers is no rows`() {
assertThat(rows(emptyList())).isEmpty()
}
/** §5.11 #2 */
@Test
fun `the rows come back in storage order`() {
val result = rows(
listOf(
pausedTimer(id = 1L, sortOrder = 2),
runningTimerWith(id = 2L, left = 1.minutes, elapsedNow = now, sortOrder = 0),
idleTimer(id = 3L, sortOrder = 1),
),
)
assertThat(result.map { it.id }).containsExactly(2L, 3L, 1L).inOrder()
}
/** §5.11 #3 */
@Test
fun `an expired timer does not jump to the top`() {
val result = rows(
listOf(
runningTimerWith(id = 1L, left = 1.minutes, elapsedNow = now, sortOrder = 0),
expiredTimer(id = 2L, sortOrder = 2),
),
)
assertThat(result.map { it.id to it.mode })
.containsExactly(1L to TimerMode.RUNNING, 2L to TimerMode.EXPIRED)
.inOrder()
}
/** §5.11 #4 */
@Test
fun `an idle timer reads its configured length, full`() {
val row = rows(listOf(idleTimer(duration = 5.minutes))).single()
assertThat(row.remaining to row.progress).isEqualTo(5.minutes to 1f)
}
/** §5.11 #5 */
@Test
fun `a running timer halfway through is half full`() {
val timer = runningTimerWith(left = 150.seconds, elapsedNow = now, duration = 5.minutes)
assertThat(rows(listOf(timer)).single().progress).isEqualTo(0.5f)
}
/** §5.11 #6 */
@Test
fun `a paused timer reads its banked remainder`() {
val timer = pausedTimer(remaining = 60.seconds, duration = 5.minutes)
val row = rows(listOf(timer)).single()
assertThat(row.remaining to row.progress).isEqualTo(60.seconds to 0.2f)
}
/** §5.11 #7 */
@Test
fun `an expired timer reads empty`() {
val row = rows(listOf(expiredTimer(duration = 5.minutes))).single()
assertThat(row.remaining to row.progress).isEqualTo(Duration.ZERO to 0f)
}
/** §5.11 #8 */
@Test
fun `a zero-length timer divides by nothing`() {
val row = rows(listOf(idleTimer(duration = Duration.ZERO))).single()
assertThat(row.progress).isEqualTo(0f)
}
/** §5.11 #9 */
@Test
fun `a timer with more left than its length is clamped full`() {
val timer = runningTimerWith(left = 10.minutes, elapsedNow = now, duration = 5.minutes)
assertThat(rows(listOf(timer)).single().progress).isEqualTo(1f)
}
/** §5.11 #10 */
@Test
fun `a blank label stays blank, because the composable owns the fallback`() {
val row = rows(listOf(idleTimer(label = ""))).single()
assertThat(row.label).isEmpty()
}
/** §5.11 #11 */
@Test
fun `three hours of clock jump each way changes no readout`() {
val timers = listOf(runningTimerWith(left = 150.seconds, elapsedNow = now, wallNow = wall))
val before = rows(timers)
val forward = rows(timers, wallClock = wall + 3.hours)
val backward = rows(timers, wallClock = wall - 3.hours)
assertThat(listOf(forward, backward)).containsExactly(before, before)
}
}
@@ -0,0 +1,32 @@
package de.jeanlucmakiola.clockula.ui.timers
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
/**
* §5.16 — 3 cases. The editor is a sibling route in the same flat `NavHost`, so
* M4's navigation policy already answers what the tab bar shows and who owns
* back; those two properties are §5.15's.
*/
class TimerRoutesTest {
/** §5.16 #1 */
@Test
fun `the editor route carries the timer's id`() {
assertThat(TimerRoutes.editor(7L)).isEqualTo("timers/edit/7")
}
/** §5.16 #2 */
@Test
fun `the pattern's placeholder is the declared argument name`() {
assertThat(TimerRoutes.EDITOR_PATTERN).contains("{" + TimerRoutes.ARG_TIMER_ID + "}")
}
/** §5.16 #3 */
@Test
fun `a negative id is a route, not a crash`() {
val prefix = TimerRoutes.EDITOR_PATTERN.substringBefore("{")
assertThat(TimerRoutes.editor(-1L)).isEqualTo(prefix + "-1")
}
}
@@ -0,0 +1,246 @@
package de.jeanlucmakiola.clockula.ui.timers
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.clockula.data.timers.TimerEntity
import de.jeanlucmakiola.clockula.domain.TimerState
import de.jeanlucmakiola.clockula.testing.FakeTimerDao
import de.jeanlucmakiola.clockula.testing.T0
import de.jeanlucmakiola.clockula.testing.TimerEngineHarness
import de.jeanlucmakiola.clockula.testing.expiredTimer
import de.jeanlucmakiola.clockula.testing.idleTimer
import de.jeanlucmakiola.clockula.testing.runningTimerWith
import de.jeanlucmakiola.clockula.testing.timerEngineHarness
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import de.jeanlucmakiola.clockula.testing.MainDispatcherExtension
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
/**
* §5.12 — 12 cases over the real repository and a real `TimerEngine`. The six
* verbs go through the engine, not the repository, which is what keeps the
* expiry slot and the service moving with the state (D2) — and the expiry slot
* is how a test proves the call took that route.
*/
class TimersViewModelTest {
@JvmField
@RegisterExtension
val main = MainDispatcherExtension()
private val uptime: Duration = 1_000.seconds
private val dao = SubscriptionCountingTimerDao()
private fun TestScope.viewModel(harness: TimerEngineHarness) = TimersViewModel(
timers = harness.timers,
engine = harness.engine,
settings = harness.settings,
source = TimerListSource(harness.timers, harness.elapsed, harness.wallClock, harness.ticker),
).also { viewModel -> backgroundScope.launch { viewModel.state.collect {} } }
private fun TimersUiState.loaded(): TimersUiState.Loaded = this as TimersUiState.Loaded
/** §5.12 #1 */
@Test
fun `the list starts out loading, not empty`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val harness = timerEngineHarness(tempDir, timerDao = dao)
val viewModel = viewModel(harness)
assertThat(viewModel.state.value).isEqualTo(TimersUiState.Loading)
}
/** §5.12 #2 */
@Test
fun `a timer stored underneath the list appears in it`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
val viewModel = viewModel(harness)
advanceUntilIdle()
harness.given(idleTimer(id = 1L, label = "Pasta"))
advanceUntilIdle()
assertThat(viewModel.state.value.loaded().rows.map { it.id }).containsExactly(1L)
}
/** §5.12 #3 */
@Test
fun `starting a new timer creates it, runs it and registers its deadline`(
@TempDir tempDir: Path,
) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onStartNew(90.seconds)
advanceUntilIdle()
val stored = harness.stored(dao.stored.single().id)!!
assertThat(listOf(stored.state, stored.duration, harness.scheduler.expiryAt))
.containsExactly(TimerState.RUNNING, 90.seconds, uptime + 90.seconds)
.inOrder()
}
/** §5.12 #4 */
@Test
fun `a double-tapped start creates one timer`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val harness = timerEngineHarness(tempDir, timerDao = dao)
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onStartNew(90.seconds)
viewModel.onStartNew(90.seconds)
advanceUntilIdle()
assertThat(dao.stored).hasSize(1)
}
/** §5.12 #5 */
@Test
fun `a duration outside the allowed range creates nothing`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onStartNew(500.milliseconds)
advanceUntilIdle()
assertThat(dao.stored).isEmpty()
}
/** §5.12 #6 */
@Test
fun `pausing from the list cancels the expiry slot`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
harness.given(runningTimerWith(id = 1L, left = 4.minutes, elapsedNow = uptime, wallNow = T0))
harness.engine.resync()
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onPause(1L)
advanceUntilIdle()
assertThat(harness.scheduler.expiryAt).isNull()
}
/** §5.12 #7 */
@Test
fun `deleting a sounding timer closes the ring session`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
harness.given(expiredTimer(id = 1L))
harness.ringState.set(T0 - 30.seconds)
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onDelete(1L)
advanceUntilIdle()
assertThat(harness.ringState.current()).isNull()
}
/** §5.12 #8 */
@Test
fun `the stored presets are part of the loaded state`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
harness.settings.setTimerPresets(listOf(2.minutes, 20.minutes))
val viewModel = viewModel(harness)
advanceUntilIdle()
assertThat(viewModel.state.value.loaded().presets)
.containsExactly(2.minutes, 20.minutes)
.inOrder()
}
/** §5.12 #9 */
@Test
fun `saving a preset keeps the set ascending`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
harness.settings.setTimerPresets(listOf(1.minutes, 5.minutes))
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onSavePreset(3.minutes)
advanceUntilIdle()
assertThat(viewModel.state.value.loaded().presets)
.containsExactly(1.minutes, 3.minutes, 5.minutes)
.inOrder()
}
/** §5.12 #10 */
@Test
fun `saving a preset that is already there changes nothing`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
harness.settings.setTimerPresets(listOf(1.minutes, 5.minutes))
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onSavePreset(5.minutes)
advanceUntilIdle()
assertThat(viewModel.state.value.loaded().presets)
.containsExactly(1.minutes, 5.minutes)
.inOrder()
}
/** §5.12 #11 */
@Test
fun `removing a preset leaves the rest`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
harness.settings.setTimerPresets(listOf(1.minutes, 5.minutes, 10.minutes))
val viewModel = viewModel(harness)
advanceUntilIdle()
viewModel.onRemovePreset(5.minutes)
advanceUntilIdle()
assertThat(viewModel.state.value.loaded().presets)
.containsExactly(1.minutes, 10.minutes)
.inOrder()
}
/** §5.12 #12 */
@Test
fun `two collectors subscribe the repository once`(@TempDir tempDir: Path) =
runTest(main.dispatcher) {
val harness = timerEngineHarness(tempDir, timerDao = dao)
val viewModel = viewModel(harness)
advanceUntilIdle()
backgroundScope.launch { viewModel.state.collect {} }
advanceUntilIdle()
assertThat(dao.subscriptions).isEqualTo(1)
}
/** Counts the collectors the observing flow actually acquires. */
private class SubscriptionCountingTimerDao : FakeTimerDao() {
var subscriptions: Int = 0
private set
override fun observeAll(): Flow<List<TimerEntity>> =
super.observeAll().onStart { subscriptions++ }
}
}