Release v2.25.0 (#545)
Renovate / renovate (push) Successful in 1m13s
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 18m44s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m0s

This commit is contained in:
Jean-Luc Makiola committed 2026-11-26 15:20:08 +01:00
1 parent a42b12d65d
commit 56a687169e
194 files changed
+15612 -2617

No files matched your search

@@ -5,12 +5,17 @@ import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.calendar.SyncActivity
import de.jeanlucmakiola.calendula.data.calendar.SyncRequester
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
@@ -43,7 +48,58 @@ fun testRepository(
io: CoroutineDispatcher,
prefs: CalendarPrefs = testPrefs(dir),
settings: SettingsPrefs = testSettings(dir),
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io)
syncRequester: SyncRequester = RecordingSyncRequester(),
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester)
/**
* Records every sync request; [accepts] false models the system refusing all,
* [refusedTypes] refusing those account types, [adapterTypes] the installed
* calendar sync adapters (null: a fixed set covering the test accounts),
* [hiddenTypes] account types the app can't address by name.
*/
class RecordingSyncRequester(
var accepts: Boolean = true,
var adapterTypes: Set<String>? = null,
var refusedTypes: Set<String> = emptySet(),
var hiddenTypes: Set<String> = emptySet(),
) : SyncRequester {
data class Request(val account: SyncAccount, val userInitiated: Boolean)
val requests = mutableListOf<Request>()
override fun adapterAccountTypes(): Set<String> =
adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL")
override fun addressableAccounts(types: Set<String>): Set<SyncAccount>? {
visibilityError?.let { throw it }
return if (hiddenTypes.isEmpty()) {
null
} else {
knownAccounts.filterTo(mutableSetOf()) { it.type in types && it.type !in hiddenTypes }
}
}
/** Thrown by [addressableAccounts] when set. */
var visibilityError: Exception? = null
/** The accounts on the "device", for [addressableAccounts]. */
var knownAccounts: Set<SyncAccount> = emptySet()
override fun requestSync(account: SyncAccount, userInitiated: Boolean) {
if (!accepts || account.type in refusedTypes) throw SecurityException("refused")
requests += Request(account, userInitiated)
}
/** Each account's sync state; null stands for a system that won't say. */
var activity: (SyncAccount) -> SyncActivity? = { SyncActivity.Idle }
/** Emit to tell waiters the sync state changed. */
val activityChanges = MutableSharedFlow<Unit>(extraBufferCapacity = 8)
override fun syncActivity(account: SyncAccount): SyncActivity? = activity(account)
override fun syncActivityChanges(): Flow<Unit> = activityChanges
}
/** Installs [dispatcher] as `Dispatchers.Main` around each test. */
@OptIn(ExperimentalCoroutinesApi::class)
@@ -0,0 +1,30 @@
package de.jeanlucmakiola.calendula.data.backup
import androidx.work.ExistingWorkPolicy
import androidx.work.WorkInfo.State.BLOCKED
import androidx.work.WorkInfo.State.CANCELLED
import androidx.work.WorkInfo.State.ENQUEUED
import androidx.work.WorkInfo.State.RUNNING
import androidx.work.WorkInfo.State.SUCCEEDED
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class ChangeRunPolicyTest {
@Test
fun `a run that hasn't started yet covers the change`() {
assertThat(changeRunPolicy(listOf(ENQUEUED))).isNull()
assertThat(changeRunPolicy(listOf(RUNNING, BLOCKED))).isNull()
}
@Test
fun `a run already going gets the next one queued behind it`() {
assertThat(changeRunPolicy(listOf(RUNNING))).isEqualTo(ExistingWorkPolicy.APPEND_OR_REPLACE)
}
@Test
fun `with nothing pending a fresh run starts`() {
assertThat(changeRunPolicy(emptyList())).isEqualTo(ExistingWorkPolicy.REPLACE)
assertThat(changeRunPolicy(listOf(SUCCEEDED, CANCELLED))).isEqualTo(ExistingWorkPolicy.REPLACE)
}
}
@@ -0,0 +1,45 @@
package de.jeanlucmakiola.calendula.data.backup
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.ReminderStateKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.floret.prefs.Pref
import org.junit.jupiter.api.Test
/**
* Every key of the settings store is either backed up or deliberately left
* out. A new key fails here until [SettingsBackupSchema] says which.
*/
class SettingsBackupSchemaTest {
private val schema = SettingsBackupSchema
private fun keysOf(holder: Any): List<String> = holder.javaClass.declaredFields
.filter { java.lang.reflect.Modifier.isStatic(it.modifiers) && it.name != "INSTANCE" }
.flatMap { field ->
field.isAccessible = true
when (val value = field.get(null)) {
is Pref<*> -> listOf(value.name)
is Map<*, *> -> value.values.filterIsInstance<Pref<*>>().map { it.name }
else -> emptyList()
}
}
@Test
fun `every stored key is classified`() {
val stored = (keysOf(SettingsKeys) + keysOf(CalendarPrefKeys) + keysOf(ReminderStateKeys)).toSet()
val classified = (schema.plain + schema.perCalendar + schema.excluded).map { it.name }
assertThat(stored).isNotEmpty()
assertThat(classified).containsAtLeastElementsIn(stored)
assertThat(stored).containsAtLeastElementsIn(classified)
}
@Test
fun `no key is classified twice`() {
val classified = (schema.plain + schema.perCalendar + schema.excluded).map { it.name }
assertThat(classified).containsNoDuplicates()
}
}
@@ -0,0 +1,441 @@
package de.jeanlucmakiola.calendula.data.backup
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.mutablePreferencesOf
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.appname.LauncherName
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.floret.prefs.get
import de.jeanlucmakiola.floret.prefs.set
import org.junit.jupiter.api.Test
class SettingsBackupTest {
private fun calendar(id: Long, name: String, account: String = "me@example.org", managed: Boolean = false) =
CalendarSource(
id = id,
displayName = name,
accountName = account,
accountType = "com.google",
color = 0,
isVisibleInSystem = true,
isManaged = managed,
)
private val work = calendar(1, "Work")
private val home = calendar(2, "Home")
private val birthdays = calendar(3, "Birthdays", account = "Calendula", managed = true)
private fun environment(
calendars: List<CalendarSource>? = listOf(work, home, birthdays),
managed: List<ManagedCalendarRow> = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)),
contacts: Boolean = true,
fonts: Set<FontRole> = emptySet(),
folder: Boolean = false,
languages: List<String> = listOf("de", "en-US", "fr"),
) = ImportEnvironment(calendars, managed, contacts, fonts, folder, languages)
private fun roundTrip(source: MutablePreferences, calendars: List<CalendarSource> = listOf(work, home, birthdays)): SettingsBackup {
val backup = buildSettingsBackup(
snapshot = source,
calendars = calendars,
managed = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)),
language = LanguageChoice("de"),
launcherName = LauncherName.CALENDAR,
)
val decoded = decodeSettingsBackup(encodeSettingsBackup(backup, 1_700_000_000_000, "2.25.0"))
return (decoded as BackupResult.Success).value
}
private fun import(backup: SettingsBackup, current: MutablePreferences, env: ImportEnvironment = environment()) =
planSettingsImport(backup, current, env).also { it.applyTo(current) }
@Test
fun `plain settings survive the round trip`() {
val source = mutablePreferencesOf()
source[SettingsKeys.themeMode] = ThemeMode.BLACK
source[SettingsKeys.multiDayCount] = 5
source[SettingsKeys.defaultView] = CalendarView.Month
source[SettingsKeys.defaultReminderMinutes] = listOf(10, 60)
val target = mutablePreferencesOf()
import(roundTrip(source), target)
assertThat(target[SettingsKeys.themeMode]).isEqualTo(ThemeMode.BLACK)
assertThat(target[SettingsKeys.multiDayCount]).isEqualTo(5)
assertThat(target[SettingsKeys.defaultView]).isEqualTo(CalendarView.Month)
assertThat(target[SettingsKeys.defaultReminderMinutes]).containsExactly(10, 60).inOrder()
}
@Test
fun `a setting the file leaves at its default resets here`() {
val target = mutablePreferencesOf()
target[SettingsKeys.showWeekNumbers] = true
import(roundTrip(mutablePreferencesOf()), target)
assertThat(target[SettingsKeys.showWeekNumbers]).isFalse()
}
@Test
fun `device state is neither exported nor touched`() {
val source = mutablePreferencesOf()
source[SettingsKeys.autoBackupFolderUri] = "content://tree/backup"
source[SettingsKeys.recentTimeZones] = listOf("Europe/Berlin")
val target = mutablePreferencesOf()
target[SettingsKeys.autoBackupLastRun] = 42L
val backup = roundTrip(source)
import(backup, target)
assertThat(backup.prefs.keys.map { it.name }).doesNotContain("auto_backup_folder_uri")
assertThat(target[SettingsKeys.autoBackupFolderUri]).isNull()
assertThat(target[SettingsKeys.autoBackupLastRun]).isEqualTo(42L)
}
@Test
fun `per-calendar settings follow the calendar to its new id`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
source[CalendarPrefKeys.lastUsedCalendarId] = 2L
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
source[SettingsKeys.perCalendarReminderOverride] = mapOf(2L to emptyList())
val moved = listOf(calendar(11, "Work"), calendar(12, "Home"))
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target, environment(calendars = moved, managed = emptyList()))
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).containsExactly(11L)
assertThat(target[CalendarPrefKeys.lastUsedCalendarId]).isEqualTo(12L)
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(11L, 30)
assertThat(target[SettingsKeys.perCalendarReminderOverride]).containsExactly(12L, emptyList<Int>())
assertThat(plan.calendars).hasSize(2)
}
@Test
fun `a calendar missing here is reported, and its old id is not reused`() {
val source = mutablePreferencesOf()
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
val target = mutablePreferencesOf()
target[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 45)
val plan = import(roundTrip(source), target, environment(calendars = listOf(calendar(1, "Other"))))
assertThat(target[SettingsKeys.perCalendarEventDuration]).isEmpty()
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org"))
}
@Test
fun `two calendars with the same name and account match neither`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target, environment(calendars = listOf(calendar(5, "Work"), calendar(6, "Work"))))
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true))
}
@Test
fun `every per-calendar key travels with its calendar`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
source[CalendarPrefKeys.lastUsedCalendarId] = 1L
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
source[SettingsKeys.perCalendarReminderOverride] = mapOf(1L to listOf(5))
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(1L to listOf(0))
source[SettingsKeys.perCalendarHiddenViews] = mapOf(1L to setOf(CalendarView.Month, CalendarView.Week))
source[SettingsKeys.mutedReminderCalendarIds] = setOf(1L)
source[SettingsKeys.reminderAlertStyles] = mapOf(1L to ReminderAlertStyle.FullScreenRing)
source[SettingsKeys.perCalendarFixedTimeReminderOverride] = mapOf(1L to FixedTimeReminder(2, 1_200))
source[SettingsKeys.digestExcludedCalendarIds] = setOf(1L)
source[SettingsKeys.autoBackupIncluded] = setOf(1L)
source[SettingsKeys.autoBackupExcluded] = setOf(1L)
val target = mutablePreferencesOf()
import(roundTrip(source), target, environment(calendars = listOf(calendar(9, "Work")), managed = emptyList()))
// One assertion per key in the schema: a new per-calendar key fails here until it is carried.
// Both auto-backup keys are set at the source so each is checked; one calendar sits in only one.
SettingsBackupSchema.perCalendar.filter { it != SettingsKeys.autoBackupExcluded }.forEach { pref ->
assertThat(target.asMap().keys.map { it.name }).contains(pref.name)
}
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(9L, listOf(0))
assertThat(target[SettingsKeys.perCalendarHiddenViews]).containsExactly(9L, setOf(CalendarView.Month, CalendarView.Week))
assertThat(target[SettingsKeys.mutedReminderCalendarIds]).containsExactly(9L)
assertThat(target[SettingsKeys.reminderAlertStyles]).containsExactly(9L, ReminderAlertStyle.FullScreenRing)
assertThat(target[SettingsKeys.perCalendarFixedTimeReminderOverride]).containsExactly(9L, FixedTimeReminder(2, 1_200))
assertThat(target[SettingsKeys.digestExcludedCalendarIds]).containsExactly(9L)
assertThat(target[SettingsKeys.autoBackupIncluded]).containsExactly(9L)
}
@Test
fun `an off set-time override and an excluded backup calendar survive the round trip`() {
val source = mutablePreferencesOf()
source[SettingsKeys.perCalendarFixedTimeReminderOverride] = mapOf(1L to null)
source[SettingsKeys.autoBackupExcluded] = setOf(1L)
val target = mutablePreferencesOf()
import(roundTrip(source), target, environment(calendars = listOf(calendar(9, "Work")), managed = emptyList()))
assertThat(target[SettingsKeys.perCalendarFixedTimeReminderOverride].fixedTimeOverrideFor(9L))
.isEqualTo(FixedTimeOverride.Off)
assertThat(target[SettingsKeys.autoBackupExcluded]).containsExactly(9L)
assertThat(target[SettingsKeys.autoBackupIncluded]).isEmpty()
}
@Test
fun `a mirror type the import switches off is left out`() {
val source = mutablePreferencesOf()
source[SettingsKeys.specialDatesEnabled] = true
source[SettingsKeys.specialDateTypeEnabled.getValue(SpecialDateType.Birthday)] = false
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L)
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target)
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
assertThat(plan.pendingSpecialDates).isEmpty()
assertThat(plan.skipped).isEmpty()
}
@Test
fun `an out-of-range calendar length is clamped, not refused`() {
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","event_duration_minutes":5000}]}"""
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
val target = mutablePreferencesOf()
import(backup, target)
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(1L, 1440)
}
@Test
fun `unreadable calendars leave the per-calendar settings alone`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
val target = mutablePreferencesOf()
target[SettingsKeys.perCalendarEventDuration] = mapOf(4L to 45)
val plan = import(roundTrip(source), target, environment(calendars = null))
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(4L, 45)
assertThat(plan.skipped).containsExactly(SkippedSetting.CalendarsUnavailable)
}
@Test
fun `mirror calendars are left out when the import turns the mirror off`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L)
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target)
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
assertThat(plan.pendingSpecialDates).isEmpty()
assertThat(plan.skipped).isEmpty()
}
@Test
fun `a stale id in the prefs is dropped on export`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L, 99L)
assertThat(roundTrip(source).calendars.map { it.calendar.displayName }).containsExactly("Work")
}
@Test
fun `a mirror calendar is matched by its date type`() {
val source = mutablePreferencesOf()
source[SettingsKeys.specialDatesEnabled] = true
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0, 10080))
val target = mutablePreferencesOf()
val renamed = listOf(calendar(7, "Geburtstage", account = "Calendula", managed = true))
import(roundTrip(source), target, environment(calendars = renamed, managed = listOf(ManagedCalendarRow(7, SpecialDateType.Birthday))))
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(7L, listOf(0, 10080))
}
@Test
fun `a mirror calendar that doesn't exist yet waits for the sync`() {
val source = mutablePreferencesOf()
source[SettingsKeys.specialDatesEnabled] = true
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0))
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target, environment(managed = emptyList()))
plan.pendingSpecialDates.forEach { target.addCalendarSettings(8L, it) }
assertThat(plan.skipped).isEmpty()
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(8L, listOf(0))
}
@Test
fun `a custom font without its file keeps the current font`() {
val source = mutablePreferencesOf()
source[SettingsKeys.brandFont] = FONT_CUSTOM_TOKEN
source[SettingsKeys.plainFont] = FONT_CUSTOM_TOKEN
val target = mutablePreferencesOf()
target[SettingsKeys.brandFont] = "lora"
val plan = import(roundTrip(source), target, environment(fonts = setOf(FontRole.PLAIN)))
assertThat(target[SettingsKeys.brandFont]).isEqualTo("lora")
assertThat(target[SettingsKeys.plainFont]).isEqualTo(FONT_CUSTOM_TOKEN)
assertThat(plan.skipped).containsExactly(SkippedSetting.CustomFont(FontRole.BRAND))
}
@Test
fun `contact dates without the permission stay as they are`() {
val source = mutablePreferencesOf()
source[SettingsKeys.specialDatesEnabled] = true
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target, environment(contacts = false))
assertThat(target[SettingsKeys.specialDatesEnabled]).isFalse()
assertThat(plan.skipped).contains(SkippedSetting.SpecialDates)
}
@Test
fun `automatic backup without a folder here stays off, its interval comes along`() {
val source = mutablePreferencesOf()
source[SettingsKeys.autoBackupEnabled] = true
source[SettingsKeys.autoBackupIntervalMinutes] = 120L
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target)
assertThat(target[SettingsKeys.autoBackupEnabled]).isFalse()
assertThat(target[SettingsKeys.autoBackupIntervalMinutes]).isEqualTo(120L)
assertThat(plan.skipped).contains(SkippedSetting.AutoBackupFolder)
}
@Test
fun `automatic backup keeps going where a folder is already set`() {
val source = mutablePreferencesOf()
source[SettingsKeys.autoBackupEnabled] = true
val target = mutablePreferencesOf()
import(roundTrip(source), target, environment(folder = true))
assertThat(target[SettingsKeys.autoBackupEnabled]).isTrue()
}
@Test
fun `the language resolves against what this build ships`() {
val backup = roundTrip(mutablePreferencesOf())
assertThat(planSettingsImport(backup.copy(language = LanguageChoice("en-US")), mutablePreferencesOf(), environment()).language)
.isEqualTo(LanguageChoice("en-US"))
assertThat(planSettingsImport(backup.copy(language = LanguageChoice(null)), mutablePreferencesOf(), environment()).language)
.isEqualTo(LanguageChoice(null))
val missing = planSettingsImport(backup.copy(language = LanguageChoice("ja")), mutablePreferencesOf(), environment())
assertThat(missing.language).isNull()
assertThat(missing.skipped).containsExactly(SkippedSetting.Language("ja"))
}
@Test
fun `app-level choices travel along`() {
val backup = roundTrip(mutablePreferencesOf())
assertThat(backup.language).isEqualTo(LanguageChoice("de"))
assertThat(backup.launcherName).isEqualTo(LauncherName.CALENDAR)
}
@Test
fun `unknown fields from a later build are ignored`() {
val text = """
{"format":"calendula-settings","version":1,"exportedAt":1,"future":{"x":1},
"settings":{"multi_day_count":4,"some_new_key":true},
"calendars":[{"account_name":"a","account_type":"t","display_name":"d","colour":"red"}],
"app":{"launcher_name":"SOMETHING_NEW"}}
""".trimIndent()
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
assertThat(backup.prefs.values).containsExactly(4)
assertThat(backup.calendars).hasSize(1)
assertThat(backup.launcherName).isNull()
assertThat(backup.language).isNull()
}
@Test
fun `a malformed known field rejects the whole file`() {
listOf(
"""{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{"multi_day_count":"4"}}""",
"""{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[{"account_name":"a"}]}""",
"""{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[{"account_name":"a","account_type":"t","display_name":"d","reminders":["x"]}]}""",
).forEach { text ->
val result = decodeSettingsBackup(text) as BackupResult.Failure
assertThat(result.problem).isEqualTo(BackupProblem.INVALID_DATA)
}
}
@Test
fun `a file without its settings section is refused`() {
val result = decodeSettingsBackup("""{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[]}""")
assertThat((result as BackupResult.Failure).problem).isEqualTo(BackupProblem.INVALID_DATA)
}
@Test
fun `an import without per-calendar settings leaves no empty keys behind`() {
val target = mutablePreferencesOf()
target[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
import(roundTrip(mutablePreferencesOf()), target)
SettingsBackupSchema.perCalendar.forEach { pref ->
assertThat(target.asMap().keys.map { it.name }).doesNotContain(pref.name)
}
}
@Test
fun `two file entries naming the same calendar are both skipped`() {
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","hidden":true},
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","event_duration_minutes":90}]}"""
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
val target = mutablePreferencesOf()
val plan = import(backup, target)
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true))
}
@Test
fun `reminder lists are cleaned the way the setters store them`() {
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
{"account_name":"a","account_type":"t","display_name":"d","reminders":[60,-5,30,30]}]}"""
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
assertThat(backup.calendars.single().reminders).containsExactly(30, 60).inOrder()
}
@Test
fun `a newer schema is refused`() {
val result = decodeSettingsBackup("""{"format":"calendula-settings","version":2,"exportedAt":1}""")
assertThat((result as BackupResult.Failure).problem).isEqualTo(BackupProblem.NEWER_VERSION)
}
}
@@ -48,11 +48,29 @@ class AllDayReminderEncodingTest {
assertThat(actualFire(raw, summer)).isEqualTo(intendedFire(summer, 0, nineAm))
}
@Test
fun `whole-day lead times match the encoder and keep the default sentinel`() {
assertThat(wholeDayLeadTimes(listOf(2_880, 10, 1_500, 0, MINUTES_DEFAULT)))
.containsExactly(MINUTES_DEFAULT, 0, 1_440, 2_880).inOrder()
for (minutes in listOf(10, 1_500, -30)) {
assertThat(toProviderAllDayMinutes(minutes, summer, berlin, nineAm))
.isEqualTo(toProviderAllDayMinutes(wholeDayLeadMinutes(minutes), summer, berlin, nineAm))
}
}
@Test
fun `three weeks before fires at 9am local across a DST change`() {
val afterDst = LocalDate.of(2026, 4, 10) // CEST; three weeks earlier is CET
val raw = toProviderAllDayMinutes(3 * 10_080, afterDst, berlin, nineAm)
assertThat(actualFire(raw, afterDst)).isEqualTo(intendedFire(afterDst, 21, nineAm))
assertThat(fromProviderAllDayMinutes(raw, afterDst, berlin, nineAm)).isEqualTo(3 * 10_080)
}
@Test
fun `round-trips for whole-day lead times across both seasons`() {
for (date in listOf(summer, winter)) {
for (time in listOf(0, nineAm, 20 * 60)) {
for (semantic in listOf(0, 1_440, 2_880, 10_080)) {
for (semantic in listOf(0, 1_440, 2_880, 4_320, 5_760, 7_200, 10_080, 20_160, 30_240)) {
val raw = toProviderAllDayMinutes(semantic, date, berlin, time)
assertThat(fromProviderAllDayMinutes(raw, date, berlin, time))
.isEqualTo(semantic)
@@ -8,6 +8,13 @@ import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.SearchCandidate
import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.ics.CalendarRows
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
import de.jeanlucmakiola.calendula.domain.ics.IcsParser
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
import de.jeanlucmakiola.calendula.domain.ics.OverrideRow
import de.jeanlucmakiola.calendula.domain.ics.MasterRow
import de.jeanlucmakiola.calendula.testEvent
import de.jeanlucmakiola.calendula.testPrefs
import de.jeanlucmakiola.calendula.testRepository
@@ -946,19 +953,153 @@ class CalendarRepositoryImplTest {
repo.exportEvents(calendarIds = setOf(1L, 4L))
assertThat(fake.lastExportableEventsCalendarIds).containsExactly(1L, 4L)
assertThat(fake.lastCalendarRowsIds).containsExactly(1L, 4L)
}
@Test
fun `exportEvents defaults to null so every eligible calendar is exported`(
fun `exportEvents reads synced calendars when asked for them`(
@TempDir tempDir: Path,
) = runTest {
val fake = FakeCalendarDataSource()
val repo = testRepository(fake, tempDir, Dispatchers.Unconfined)
repo.exportEvents()
repo.exportEvents(calendarIds = setOf(2L))
assertThat(fake.lastExportableEventsCalendarIds).isNull()
assertThat(fake.lastCalendarRowsIds).containsExactly(2L)
}
@Test
fun `copyEvents reports progress and skips what an earlier run copied`(
@TempDir tempDir: Path,
) = runTest {
fun icsEvent(uid: String) = IcsEvent(
uid = uid,
summary = uid,
start = Instant.fromEpochMilliseconds(1_000_000_000L),
end = Instant.fromEpochMilliseconds(1_000_003_600L),
isAllDay = false,
zoneId = "UTC",
)
val fake = FakeCalendarDataSource().apply {
existingUidsResult = setOf("a")
calendarRowsResult = CalendarRows(
series = listOf(MasterRow(1, 1, null, icsEvent("a")), MasterRow(2, 1, null, icsEvent("b"))),
overrides = emptyList(),
)
}
val repo = testRepository(fake, tempDir, Dispatchers.Unconfined)
val progress = mutableListOf<Pair<Int, Int>>()
val summary = repo.copyEvents(sourceCalendarId = 1L, targetCalendarId = 3L) { done, total ->
progress += done to total
}
assertThat(summary.imported).isEqualTo(1)
assertThat(summary.skippedDuplicate).isEqualTo(1)
assertThat(fake.importedEvents.map { it.first.uid to it.second }).containsExactly("b" to 3L)
assertThat(progress.first()).isEqualTo(0 to 2)
assertThat(progress.last()).isEqualTo(2 to 2)
}
@Test
fun `a backup restores a series' moved and deleted occurrences, and skips them where the series is`(
@TempDir tempDir: Path,
) = runTest {
val start = Instant.parse("2026-01-05T09:00:00Z")
fun at(week: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + week * 7 * 86_400_000L)
fun event(at: Instant, status: EventStatus = EventStatus.Confirmed, rrule: String? = null) = IcsEvent(
uid = "s@x",
summary = "Standup",
start = at,
end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L),
isAllDay = false,
zoneId = "Europe/Berlin",
recurrenceRule = rrule,
status = status,
)
val moved = Instant.fromEpochMilliseconds(at(1).toEpochMilliseconds() + 3_600_000L)
val source = FakeCalendarDataSource().apply {
calendarRowsResult = CalendarRows(
series = listOf(MasterRow(1, 1, "sync-1", event(start, rrule = "FREQ=WEEKLY"))),
overrides = listOf(
OverrideRow(1, null, "sync-1", at(1), event(moved)),
OverrideRow(1, null, "sync-1", at(2), event(at(2), EventStatus.Cancelled)),
),
)
}
val file = IcsWriter().writeCalendar(
testRepository(source, tempDir.resolve("a"), Dispatchers.Unconfined).exportEvents(setOf(1L)),
start,
)
val parsed = IcsParser().parse(file).events
val empty = FakeCalendarDataSource()
testRepository(empty, tempDir.resolve("b"), Dispatchers.Unconfined).importEvents(3L, parsed)
val (detached, series) = empty.importedEvents.map { it.first }
assertThat(detached.start).isEqualTo(moved)
assertThat(detached.recurrenceRule).isNull()
assertThat(series.exDates).containsExactly("20260112T090000Z", "20260119T090000Z")
val original = FakeCalendarDataSource().apply { existingUidsResult = setOf("s@x") }
val summary = testRepository(original, tempDir.resolve("c"), Dispatchers.Unconfined).importEvents(3L, parsed)
assertThat(original.importedEvents).isEmpty()
assertThat(summary.skippedDuplicate).isEqualTo(2)
}
@Test
fun `a series keeps an occurrence whose standalone copy didn't land`(
@TempDir tempDir: Path,
) = runTest {
val fake = FakeCalendarDataSource().apply { failingImportSummaries += "moved" }
val repo = testRepository(fake, tempDir, Dispatchers.Unconfined)
val at = Instant.parse("2026-01-12T09:00:00Z")
val summary = repo.importEvents(
3L,
listOf(
parsedEvent("1-s", summary = "moved").copy(overrideOf = "s", overrideAt = at),
parsedEvent("s").copy(recurrenceRule = "FREQ=WEEKLY", exDates = listOf("20260112T090000Z", "20260119T090000Z")),
),
)
assertThat(summary.failed).isEqualTo(1)
assertThat(fake.importedEvents.single().first.exDates).containsExactly("20260119T090000Z")
}
@Test
fun `a standalone occurrence listed after its series still goes first`(
@TempDir tempDir: Path,
) = runTest {
val fake = FakeCalendarDataSource()
val repo = testRepository(fake, tempDir, Dispatchers.Unconfined)
repo.importEvents(3L, listOf(parsedEvent("s"), parsedEvent("1-s").copy(overrideOf = "s")))
assertThat(fake.importedEvents.map { it.first.uid }).containsExactly("1-s", "s").inOrder()
}
@Test
fun `a backup keeps an RDATE-only series and its exceptions`(
@TempDir tempDir: Path,
) = runTest {
val start = Instant.parse("2026-01-05T09:00:00Z")
val other = Instant.parse("2026-01-12T09:00:00Z")
val event = IcsEvent(
"s", "S", start, Instant.parse("2026-01-05T10:00:00Z"), false, "UTC",
recurrenceDates = listOf("20260112T090000Z", "20260119T090000Z"),
)
val fake = FakeCalendarDataSource().apply {
calendarRowsResult = CalendarRows(
listOf(MasterRow(1, 1, null, event)),
listOf(OverrideRow(1, 1, null, other, event.copy(recurrenceDates = emptyList(), status = EventStatus.Cancelled))),
)
}
val exported = testRepository(fake, tempDir, Dispatchers.Unconfined).exportEvents(setOf(1L))
val restored = IcsParser().parse(IcsWriter().writeCalendar(exported, start)).events.single()
assertThat(restored.recurrenceDates).containsExactly("20260112T090000Z", "20260119T090000Z")
assertThat(restored.exDates).containsExactly("20260112T090000Z")
}
private fun parsedEvent(uid: String?, summary: String = "E") =
@@ -13,6 +13,7 @@ import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.UtcOffset
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.time.ZoneId
import kotlin.time.Instant
@@ -33,6 +34,14 @@ class EventWriteMapperTest {
timezone = timezone,
)
@Test
fun `reminders are rewritten when they change or the all-day flag flips`() {
val timed = form().copy(reminders = listOf(10))
assertThat(remindersNeedRewrite(timed, timed.copy(title = "Renamed"))).isFalse()
assertThat(remindersNeedRewrite(timed, timed.copy(reminders = listOf(10, 30)))).isTrue()
assertThat(remindersNeedRewrite(timed, timed.copy(isAllDay = true))).isTrue()
}
@Test
fun `timed event resolves wall clock in the given zone`() {
val times = form().toWriteTimes(berlin)
@@ -492,6 +501,58 @@ class EventWriteMapperTest {
.isEqualTo(CalendarContract.Events.STATUS_CANCELED)
}
// --- seriesDuration (#502) ---
@Test
fun `series duration prefers the expanded occurrence over dtend`() {
// DTEND as the end of the whole series must not stretch every occurrence.
assertThat(seriesDuration(1_000_000L, 9_000_000_000L, 3_600_000L, isAllDay = false)).isEqualTo("P3600S")
}
@Test
fun `series duration falls back to dtend when it lies after dtstart`() {
assertThat(seriesDuration(1_000_000L, 8_200_000L, null, isAllDay = false)).isEqualTo("P7200S")
}
@Test
fun `series duration ignores a zero dtend and uses the occurrence span`() {
assertThat(seriesDuration(1_790_852_400_000L, 0L, 7_200_000L, isAllDay = false)).isEqualTo("P7200S")
}
@Test
fun `series duration gives up rather than guessing`() {
assertThat(seriesDuration(1_000L, 0L, null, isAllDay = false)).isNull()
assertThat(seriesDuration(1_000L, null, null, isAllDay = true)).isNull()
}
@Test
fun `all-day series duration rounds to whole days`() {
// 47 h: a two-day occurrence read across a DST change.
assertThat(seriesDuration(0L, null, 47L * 3_600_000L, isAllDay = true)).isEqualTo("P2D")
}
@Test
fun `series duration keeps a zero length the provider already shows`() {
assertThat(seriesDuration(1_000L, 0L, 0L, isAllDay = false)).isEqualTo("P0S")
assertThat(seriesDuration(1_000L, 1_000L, null, isAllDay = true)).isEqualTo("P1D")
}
@Test
fun `exdate drop clears a stray dtend on the series`() {
val values = buildOccurrenceExdateValues(
existingExdate = null,
occurrenceMillis = 1_784_102_400_000L,
dtStartMillis = 1_783_929_600_000L,
rrule = "FREQ=DAILY;COUNT=5",
rdate = null,
duration = "PT1H",
timezone = "Europe/Berlin",
allDay = 0,
)
assertThat(values).containsKey(CalendarContract.Events.DTEND)
assertThat(values[CalendarContract.Events.DTEND]).isNull()
}
// --- buildOccurrenceExdateValues ("delete only this event", no _sync_id) ---
@Test
@@ -1186,6 +1247,14 @@ class EventWriteMapperTest {
description = "",
)
@Test
fun `moved series with a zero dtend and no duration is refused, not copied broken`() {
val snapshot = masterSnapshot(dtEndMillis = 0L, rrule = "FREQ=WEEKLY;BYDAY=TH")
assertThrows<WriteFailedException> {
buildMovedMasterValues(snapshot, targetCalendarId = 9L, uid = "u@calendula")
}
}
@Test
fun `moved one-off carries target calendar, uid and DTEND but no recurrence`() {
val values = buildMovedMasterValues(masterSnapshot(), targetCalendarId = 9L, uid = "u@calendula")
@@ -8,6 +8,7 @@ import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.SearchCandidate
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.ics.CalendarRows
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import java.time.ZoneId
@@ -23,9 +24,9 @@ internal class FakeCalendarDataSource : CalendarDataSource {
var searchResult: (String) -> List<SearchCandidate> = { _ -> emptyList() }
var eventDetailResult: (Long) -> EventDetail? = { null }
var publishedEventColorsResult: (Long) -> List<EventColorOption> = { emptyList() }
var exportableEventsResult: List<IcsEvent> = emptyList()
/** The [calendarIds] the last [exportableEvents] call received (null = all). */
var lastExportableEventsCalendarIds: Set<Long>? = null
var calendarRowsResult: CalendarRows = CalendarRows(emptyList(), emptyList())
/** The [calendarIds] the last [calendarRows] call received. */
var lastCalendarRowsIds: Set<Long>? = null
/** UIDs the target calendar already holds, for import dedup. */
var existingUidsResult: Set<String> = emptySet()
/** Set to make the next write call throw. */
@@ -64,14 +65,27 @@ internal class FakeCalendarDataSource : CalendarDataSource {
val updatedCalendars = mutableListOf<UpdatedCalendar>()
val deletedCalendarIds = mutableListOf<Long>()
/** eventId → calendarId, for [eventCalendarId]. */
val eventCalendars = mutableMapOf<Long, Long>()
override fun calendarAccount(calendarId: Long): SyncAccount? =
calendarsResult.firstOrNull { it.id == calendarId }
?.let { SyncAccount(it.accountName, it.accountType) }
override fun eventCalendarId(eventId: Long): Long? = eventCalendars[eventId]
private val listeners = mutableListOf<() -> Unit>()
/** How often [calendars] was queried — the repository shares one read per tick. */
var calendarQueries = 0
private set
/** Set to make [calendars] throw until cleared. */
var calendarsError: Exception? = null
override fun calendars(): List<CalendarSource> {
calendarQueries++
calendarsError?.let { throw it }
return calendarsResult
}
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> =
@@ -81,12 +95,9 @@ internal class FakeCalendarDataSource : CalendarDataSource {
eventDetailResult(eventId)
override fun publishedEventColors(calendarId: Long): List<EventColorOption> =
publishedEventColorsResult(calendarId)
override fun exportableEvents(
calendarIds: Set<Long>?,
allDayReminderTimeMinutes: Int,
): List<IcsEvent> {
lastExportableEventsCalendarIds = calendarIds
return exportableEventsResult
override fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows {
lastCalendarRowsIds = calendarIds
return calendarRowsResult
}
override fun existingUids(calendarId: Long): Set<String> = existingUidsResult
@@ -294,4 +294,39 @@ class IcsExportMapperTest {
assertThat(event.exDates).isEmpty()
}
@Test
fun `a zoned RDATE list is written as UTC stamps, a period by its start`() {
assertThat(exportRecurrenceDates("Europe/Berlin;20260110T100000,20260111T100000/PT1H", isAllDay = false))
.containsExactly("20260110T090000Z", "20260111T090000Z").inOrder()
}
@Test
fun `an all-day RDATE keeps its days, junk is dropped`() {
assertThat(exportRecurrenceDates("20260110T000000Z,20260111,garbage", isAllDay = true))
.containsExactly("20260110", "20260111").inOrder()
}
@Test
fun `an RDATE stored over several lines keeps every line's dates`() {
assertThat(exportRecurrenceDates("Europe/Berlin;20260110T100000\nAmerica/New_York;20260112T090000", isAllDay = false))
.containsExactly("20260110T090000Z", "20260112T140000Z").inOrder()
}
@Test
fun `an EXDATE stored over several lines keeps every line, unreadable stamps go`() {
assertThat(exportExDates("Europe/Berlin;20260110T100000\nEurope/Berlin;20260117T100000,junk", isAllDay = false))
.containsExactly("20260110T090000Z", "20260117T090000Z").inOrder()
}
@Test
fun `a bare day on a timed series is read at the series' time of day`() {
val tenBerlin = java.time.ZonedDateTime.of(2026, 1, 5, 10, 0, 0, 0, java.time.ZoneId.of("Europe/Berlin"))
.toInstant().toEpochMilli()
assertThat(exportExDates("20260112", isAllDay = false, "Europe/Berlin", tenBerlin))
.containsExactly("20260112T090000Z")
assertThat(exportRecurrenceDates("20260712", isAllDay = false, "Europe/Berlin", tenBerlin))
.containsExactly("20260712T080000Z")
}
}
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.calendar
import android.provider.CalendarContract
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.AccessLevel
import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
@@ -123,4 +124,21 @@ class ImportedEventValuesTest {
assertThat(v[CalendarContract.Events.DURATION]).isEqualTo("P900S")
assertThat(v[CalendarContract.Events.ALL_DAY]).isEqualTo(0)
}
@Test
fun `a copied RDATE-only series recurs by its dates`() {
val v = values(allDay().copy(recurrenceDates = listOf("20260820"), exDates = listOf("20260820")))
assertThat(v).doesNotContainKey(CalendarContract.Events.DTEND)
assertThat(v).doesNotContainKey(CalendarContract.Events.RRULE)
assertThat(v[CalendarContract.Events.RDATE]).isEqualTo("20260820")
assertThat(v[CalendarContract.Events.EXDATE]).isEqualTo("20260820")
assertThat(v[CalendarContract.Events.DURATION]).isEqualTo("P1D")
}
@Test
fun `a private event stays private, a default one leaves the calendar's say`() {
assertThat(values(allDay().copy(accessLevel = AccessLevel.Private))[CalendarContract.Events.ACCESS_LEVEL])
.isEqualTo(CalendarContract.Events.ACCESS_PRIVATE)
assertThat(values(allDay())).doesNotContainKey(CalendarContract.Events.ACCESS_LEVEL)
}
}
@@ -0,0 +1,314 @@
package de.jeanlucmakiola.calendula.data.calendar
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.RecordingSyncRequester
import de.jeanlucmakiola.calendula.RecordingSyncRequester.Request
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.testRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.time.Instant
class SyncNudgeTest {
private val dav = SyncAccount("me@dav", "bitfire.at.davdroid")
private val google = SyncAccount("me@gmail.com", "com.google")
private fun cal(id: Long, account: SyncAccount, visible: Boolean = true) = CalendarSource(
id = id,
displayName = "Cal $id",
accountName = account.name,
accountType = account.type,
color = 0,
isVisibleInSystem = visible,
isLocal = account.type == "LOCAL",
)
private val local = SyncAccount("Calendula", "LOCAL")
private fun fake() = FakeCalendarDataSource().apply {
calendarsResult = listOf(cal(1L, dav), cal(2L, dav), cal(3L, google), cal(4L, local))
eventCalendars += mapOf(10L to 1L, 30L to 3L, 40L to 4L)
}
private fun form(calendarId: Long) = EventForm(
calendarId = calendarId,
title = "Stand-up",
start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))),
end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15))),
)
private fun auto(account: SyncAccount) = Request(account, userInitiated = false)
@Test
fun `a write to a synced calendar nudges its account once, not manually`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.createEvent(form(1L))
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `a write to a local calendar asks for no sync`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.createEvent(form(4L))
repo.deleteEvent(40L)
assertThat(sync.requests).isEmpty()
}
@Test
fun `event writes resolve the account from the event's calendar`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.updateEventFromOccurrence(10L, 0L, form(1L), form(1L))
repo.deleteOccurrence(30L, 0L)
assertThat(sync.requests).containsExactly(auto(dav), auto(google)).inOrder()
}
@Test
fun `a move between accounts nudges both, each once`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.moveEvent(10L, 3L, form(1L), form(3L))
assertThat(sync.requests).containsExactly(auto(dav), auto(google))
}
@Test
fun `a move between calendars of one account nudges it once`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.moveEvent(10L, 2L, form(1L), form(2L))
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `an import nudges once at the end, however many events`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
val events = (1..5).map {
ParsedIcsEvent(
uid = "u$it",
summary = "E$it",
start = Instant.fromEpochMilliseconds(1_000_000_000L),
end = Instant.fromEpochMilliseconds(1_000_003_600L),
isAllDay = false,
zoneId = "UTC",
)
}
repo.importEvents(3L, events)
assertThat(sync.requests).containsExactly(auto(google))
}
@Test
fun `a failed write still nudges, since part of it may have landed`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val source = fake().apply { writeError = IllegalStateException("boom") }
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
assertThrows<IllegalStateException> { repo.deleteEvent(10L) }
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `a throwing requester never fails the save`(@TempDir dir: Path) = runTest {
val throwing = RecordingSyncRequester(accepts = false)
val source = fake().apply { nextInsertId = 77L }
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = throwing)
assertThat(repo.createEvent(form(1L))).isEqualTo(77L)
}
@Test
fun `manual sync asks each visible synced account once, as manual`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val source = fake().apply {
calendarsResult = calendarsResult + cal(5L, SyncAccount("hidden@dav", "bitfire.at.davdroid"), visible = false)
}
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested)
assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true))
}
@Test
fun `manual sync with only local calendars has nothing to sync`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val source = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(4L, local)) }
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NothingToSync)
assertThat(sync.requests).isEmpty()
}
@Test
fun `manual sync the system refuses reports a failure`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(accepts = false)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Failed)
}
@Test
fun `syncAccounts skips local, invisible and blank accounts`() {
val calendars = listOf(
cal(1L, dav),
cal(2L, dav),
cal(3L, google, visible = false),
cal(4L, local),
cal(5L, SyncAccount("", "com.google")),
)
assertThat(calendars.syncAccounts()).containsExactly(dav)
}
@Test
fun `accounts without a calendar sync adapter are never asked`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(adapterTypes = setOf(dav.type))
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.createEvent(form(3L))
assertThat(sync.requests).isEmpty()
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested)
assertThat(sync.requests).containsExactly(Request(dav, true))
}
@Test
fun `syncTargets needs a visible calendar with an adapter`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(adapterTypes = setOf(google.type))
val source = fake().apply {
calendarsResult = listOf(cal(1L, dav), cal(3L, google, visible = false), cal(4L, local))
}
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets.None)
sync.adapterTypes = setOf(dav.type)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet()))
}
@Test
fun `manual sync refused for some accounts says so`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(refusedTypes = setOf(google.type))
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.PartlyFailed)
assertThat(sync.requests).containsExactly(Request(dav, true))
}
@Test
fun `accounts the app can't see wait for access instead of being asked`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type))
sync.knownAccounts = setOf(dav, google)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.moveEvent(10L, 3L, form(1L), form(3L))
assertThat(sync.requests).containsExactly(auto(dav))
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google)))
sync.requests.clear()
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.SomeNeedAccess)
assertThat(sync.requests).containsExactly(Request(dav, true))
}
@Test
fun `once access is granted the account is asked by name`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type))
sync.knownAccounts = setOf(dav, google)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
sync.hiddenTypes = setOf("other")
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav, google), emptySet()))
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested)
assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true))
}
@Test
fun `only hidden accounts make manual sync ask for access, asking no one`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type))
sync.knownAccounts = setOf(dav, google)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NeedsAccess)
repo.createEvent(form(1L))
assertThat(sync.requests).isEmpty()
}
@Test
fun `unreadable account visibility counts as reachable`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf("other"))
sync.visibilityError = SecurityException("no")
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.createEvent(form(1L))
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `a dismissed hidden account no longer needs access`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type))
sync.knownAccounts = setOf(dav, google)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.setSyncAccessDismissed(google, dismissed = true)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet(), dismissed = setOf(google)))
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested)
repo.setSyncAccessDismissed(google, dismissed = false)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google)))
}
@Test
fun `with every hidden account dismissed there is nothing to sync or grant`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type))
sync.knownAccounts = setOf(dav, google)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.setSyncAccessDismissed(dav, dismissed = true)
repo.setSyncAccessDismissed(google, dismissed = true)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(dav, google)))
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NothingToSync)
}
@Test
fun `a dismissed account that becomes visible is still asked`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.setSyncAccessDismissed(dav, dismissed = true)
repo.createEvent(form(1L))
assertThat(sync.requests).containsExactly(auto(dav))
assertThat(repo.syncTargets.first().dismissed).isEmpty()
}
}
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.prefs
import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.testDataStore
import de.jeanlucmakiola.calendula.testPrefs
import kotlinx.coroutines.flow.first
@@ -34,6 +35,16 @@ class CalendarPrefsTest {
assertThat(prefs.hiddenCalendarIds.first()).isEmpty()
}
@Test
fun `updateHiddenCalendarIds transforms the stored set`(@TempDir tempDir: Path) = runTest {
val prefs = testPrefs(tempDir)
prefs.setHiddenCalendarIds(setOf(9L))
prefs.updateHiddenCalendarIds { it + listOf(1L, 2L) }
assertThat(prefs.hiddenCalendarIds.first()).isEqualTo(setOf(1L, 2L, 9L))
prefs.updateHiddenCalendarIds { emptySet() }
assertThat(prefs.hiddenCalendarIds.first()).isEmpty()
}
@Test
fun `garbage stored string is parsed defensively`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_prefs")
@@ -108,4 +119,18 @@ class CalendarPrefsTest {
prefs.setVisibilityNoticePending(false)
assertThat(prefs.visibilityNoticePending.first()).isFalse()
}
@Test
fun `sync access dismissals round-trip per account, names with any characters`(@TempDir tempDir: Path) = runTest {
val prefs = testPrefs(tempDir)
val dav = SyncAccount("me@dav.example/cal, 1", "bitfire.at.davdroid")
val google = SyncAccount("me@dav.example/cal, 1", "com.google")
prefs.setSyncAccessDismissed(dav, dismissed = true)
prefs.setSyncAccessDismissed(google, dismissed = true)
assertThat(prefs.syncAccessDismissed.first()).containsExactly(dav, google)
prefs.setSyncAccessDismissed(dav, dismissed = false)
assertThat(prefs.syncAccessDismissed.first()).containsExactly(google)
}
}
@@ -5,11 +5,17 @@ import de.jeanlucmakiola.calendula.testSettings
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import androidx.compose.ui.unit.dp
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventFormField
import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS
@@ -501,6 +507,18 @@ class SettingsPrefsTest {
assertThat(prefs.defaultAllDayReminderMinutes.first()).isEmpty()
}
@Test
fun `sub-day all-day defaults read as the day they fire on`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
prefs.setDefaultAllDayReminderMinutes(listOf(120, 0, 1_500))
assertThat(prefs.defaultAllDayReminderMinutes.first()).containsExactly(0, 1_440).inOrder()
prefs.setCalendarAllDayReminderOverride(7L, ReminderOverride.Minutes(listOf(30, 2_880)))
assertThat(prefs.perCalendarAllDayReminderOverride.first()).containsExactly(7L, listOf(0, 2_880))
// The timed default keeps sub-day lead times.
prefs.setDefaultReminderMinutes(listOf(120))
assertThat(prefs.defaultReminderMinutes.first()).containsExactly(120)
}
@Test
fun `per-calendar all-day override round-trips independently of the timed one`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
@@ -601,6 +619,42 @@ class SettingsPrefsTest {
assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 30)
}
@Test
fun `calendar notifications default on and toggle per calendar`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.mutedReminderCalendarIds.first()).isEmpty()
prefs.setCalendarRemindersEnabled(7L, false)
prefs.setCalendarRemindersEnabled(9L, false)
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(7L, 9L)
prefs.setCalendarRemindersEnabled(7L, true)
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L)
}
@Test
fun `calendar alert styles default to notifications and persist per calendar`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.reminderAlertStyles.first()).isEmpty()
prefs.setCalendarAlertStyle(7L, ReminderAlertStyle.FullScreenRing)
prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.FullScreen)
prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.Notification)
assertThat(prefs.reminderAlertStyles.first()).containsExactly(7L, ReminderAlertStyle.FullScreenRing)
}
@Test
fun `reminder channel versions only grow`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.reminderChannelVersions.first()).isEmpty()
assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1))).containsExactly(7L, 1)
assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1, 9L to 5))).containsExactly(7L, 2, 9L, 5)
assertThat(prefs.reminderChannelVersions.first()).containsExactly(7L, 2, 9L, 5)
}
@Test
fun `garbage per-calendar duration entries are dropped, the rest survive`(
@TempDir tempDir: Path,
@@ -616,6 +670,66 @@ class SettingsPrefsTest {
assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 45)
}
@Test
fun `per-calendar hidden views round-trip and clear back to every view`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.perCalendarHiddenViews.first()).isEmpty()
prefs.applyCalendarHiddenChanges(7L, listOf(CalendarView.Month, CalendarView.Agenda).associateWith { true })
prefs.applyCalendarHiddenChanges(9L, listOf(CalendarView.MultiDay).associateWith { true })
assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(
7L, setOf(CalendarView.Month, CalendarView.Agenda),
9L, setOf(CalendarView.MultiDay),
)
prefs.clearCalendarHiddenViews(7L)
assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(9L, setOf(CalendarView.MultiDay))
// One write can hide some views and show others, leaving the rest alone.
prefs.applyCalendarHiddenChanges(9L, mapOf(CalendarView.MultiDay to false, CalendarView.Day to true))
assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(9L, setOf(CalendarView.Day))
}
@Test
fun `toggling one hidden view keeps the others and clears the entry when empty`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
prefs.setCalendarHiddenIn(7L, CalendarView.Month, hidden = true)
prefs.setCalendarHiddenIn(7L, CalendarView.Week, hidden = true)
assertThat(prefs.perCalendarHiddenViews.first())
.containsExactly(7L, setOf(CalendarView.Month, CalendarView.Week))
prefs.setCalendarHiddenIn(7L, CalendarView.Month, hidden = false)
prefs.setCalendarHiddenIn(7L, CalendarView.Week, hidden = false)
assertThat(prefs.perCalendarHiddenViews.first()).isEmpty()
}
@Test
fun `garbage hidden-views entries are dropped, the rest survive`(
@TempDir tempDir: Path,
) = runTest {
val store = testDataStore(tempDir, "test_settings")
val prefs = SettingsPrefs(store)
store.updateData { p ->
val m = p.toMutablePreferences()
// A bad id, only an unknown view, no separator, and a good entry with one unknown view.
m[stringPreferencesKey("per_calendar_hidden_views")] = "x=Month;7=Year;8;9=Month,Year,Agenda"
m
}
assertThat(prefs.perCalendarHiddenViews.first())
.containsExactly(9L, setOf(CalendarView.Month, CalendarView.Agenda))
}
@Test
fun `hidden views serialise in view order and drop empty entries`() {
val stored = mapOf(
3L to setOf(CalendarView.Agenda, CalendarView.Month),
1L to emptySet(),
).toStoredHiddenViews()
assertThat(stored).isEqualTo("3=Month,Agenda")
assertThat(emptyMap<Long, Set<CalendarView>>().toStoredHiddenViews()).isNull()
assertThat(parseHiddenViews(stored)).containsExactly(3L, setOf(CalendarView.Month, CalendarView.Agenda))
}
@Test
fun `resolveDefaultEventDuration prefers the calendar's own length`() {
val overrides = mapOf(7L to 480)
@@ -705,4 +819,208 @@ class SettingsPrefsTest {
prefs.recordSpecialDatesRun(2000L, null)
assertThat(prefs.specialDatesStatus.first()).isEqualTo(SpecialDatesStatus(2000L, null))
}
@Test
fun `fixed-time reminder defaults to off and round-trips`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.defaultFixedTimeReminder.first()).isNull()
val evening = FixedTimeReminder(1, 1_200)
prefs.setDefaultFixedTimeReminder(evening)
assertThat(prefs.defaultFixedTimeReminder.first()).isEqualTo(evening)
prefs.setDefaultFixedTimeReminder(null)
assertThat(prefs.defaultFixedTimeReminder.first()).isNull()
}
@Test
fun `per-calendar fixed-time overrides keep inherit, off and a value apart`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
val morning = FixedTimeReminder(2, 480)
prefs.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200))
prefs.setCalendarFixedTimeReminderOverride(1L, FixedTimeOverride.Off)
prefs.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.At(morning))
val overrides = prefs.perCalendarFixedTimeReminderOverride.first()
assertThat(overrides.fixedTimeOverrideFor(1L)).isEqualTo(FixedTimeOverride.Off)
assertThat(overrides.fixedTimeOverrideFor(2L)).isEqualTo(FixedTimeOverride.At(morning))
assertThat(overrides.fixedTimeOverrideFor(3L)).isEqualTo(FixedTimeOverride.Inherit)
assertThat(resolveDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200), overrides, 1L)).isNull()
assertThat(resolveDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200), overrides, 3L))
.isEqualTo(FixedTimeReminder(1, 1_200))
assertThat(prefs.knownFixedTimeReminders.first()).containsExactly(FixedTimeReminder(1, 1_200), morning)
val picked = FixedTimeReminder(3, 600)
prefs.rememberFixedTimeReminders(listOf(picked, morning))
assertThat(prefs.knownFixedTimeReminders.first()).contains(picked)
// A default already known takes no recents slot.
assertThat(prefs.knownFixedTimeReminders.first()).hasSize(3)
// A replaced default stays known.
prefs.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_140))
assertThat(prefs.knownFixedTimeReminders.first()).contains(FixedTimeReminder(1, 1_200))
prefs.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.Inherit)
assertThat(prefs.perCalendarFixedTimeReminderOverride.first().containsKey(2L)).isFalse()
}
@Test
fun `daily summary is off by default and its settings round-trip`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.dailyDigest.first()).isEqualTo(DailyDigestSettings())
prefs.setDailyDigestEnabled(true)
prefs.setDailyDigestTimeMinutes(420)
prefs.setDailyDigestDay(DigestDay.Today)
prefs.setCalendarInDailyDigest(5L, included = false)
val digest = prefs.dailyDigest.first()
assertThat(digest.copy(armedAtMillis = 0L)).isEqualTo(
DailyDigestSettings(enabled = true, timeMinutes = 420, day = DigestDay.Today, excludedCalendarIds = setOf(5L)),
)
assertThat(digest.armedAtMillis).isGreaterThan(0L)
prefs.setCalendarInDailyDigest(5L, included = true)
assertThat(prefs.dailyDigest.first().excludedCalendarIds).isEmpty()
}
@Test
fun `a fresh install backs up one file per calendar, keeping three`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
prefs.setAutoBackupFolderUri("content://tree/a")
assertThat(prefs.autoBackupCombined.first()).isFalse()
assertThat(prefs.autoBackupKeep.first()).isEqualTo(3)
}
@Test
fun `an install that had a backup folder before 411 keeps its single file`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings")
val prefs = SettingsPrefs(store)
store.updateData { p ->
val m = p.toMutablePreferences()
m[stringPreferencesKey("auto_backup_folder_uri")] = "content://tree/old"
m
}
assertThat(prefs.autoBackupCombined.first()).isTrue()
// Picking another folder pins the layout instead of flipping it, and
// keeps the old file recognised as this install's own.
prefs.setAutoBackupFolderUri("content://tree/new")
assertThat(prefs.autoBackupCombined.first()).isTrue()
// A new folder starts a new ledger: the old file there isn't known to be ours.
assertThat(prefs.autoBackupLedger.first()).isEmpty()
prefs.setAutoBackupCombined(false)
assertThat(prefs.autoBackupCombined.first()).isFalse()
}
@Test
fun `backup calendar choices are stored as deviations from the default`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
val local = backupCalendar(1L, local = true)
val synced = backupCalendar(2L, local = false)
prefs.setAutoBackupCalendar(synced, true)
prefs.setAutoBackupCalendar(local, false)
val selection = prefs.autoBackupSelection.first()
assertThat(selection.included).containsExactly(2L)
assertThat(selection.excluded).containsExactly(1L)
prefs.setAutoBackupCalendar(local, true)
assertThat(prefs.autoBackupSelection.first().excluded).isEmpty()
}
@Test
fun `a stray retention count snaps to an offered one`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
prefs.setAutoBackupKeep(4)
assertThat(prefs.autoBackupKeep.first()).isIn(listOf(3, 5))
prefs.setAutoBackupKeep(99)
assertThat(prefs.autoBackupKeep.first()).isEqualTo(10)
}
@Test
fun `the backup interval is on by default and can only go off alongside after-change backups`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
prefs.setAutoBackupScheduled(false)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
prefs.setAutoBackupOnChange(true)
prefs.setAutoBackupScheduled(false)
assertThat(prefs.autoBackupScheduled.first()).isFalse()
prefs.setAutoBackupScheduled(true)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `turning after-change backups off brings the interval back for good`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
prefs.setAutoBackupIntervalMinutes(6 * 60L)
prefs.setAutoBackupOnChange(true)
prefs.setAutoBackupScheduled(false)
prefs.setAutoBackupOnChange(false)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
assertThat(prefs.autoBackupIntervalMinutes.first()).isEqualTo(6 * 60L)
prefs.setAutoBackupOnChange(true)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `the interval setters report whether they switched it`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.setAutoBackupScheduled(false)).isFalse()
assertThat(prefs.setAutoBackupOnChange(true)).isFalse()
assertThat(prefs.setAutoBackupScheduled(false)).isTrue()
assertThat(prefs.setAutoBackupScheduled(false)).isFalse()
assertThat(prefs.setAutoBackupOnChange(false)).isTrue()
assertThat(prefs.autoBackupOnChangeAndScheduled.first()).isEqualTo(false to true)
}
@Test
fun `switching the interval off without after-change backups leaves nothing behind`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
prefs.setAutoBackupScheduled(false)
prefs.setAutoBackupOnChange(true)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `an interval-off stored without after-change backups doesn't stick once they go on`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings")
val prefs = SettingsPrefs(store)
store.updateData { p ->
val m = p.toMutablePreferences()
m[booleanPreferencesKey("auto_backup_scheduled")] = false
m
}
assertThat(prefs.autoBackupScheduled.first()).isTrue()
assertThat(prefs.setAutoBackupOnChange(true)).isFalse()
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `a pre-411 install adopts its old file when the layout is pinned in place`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings")
val prefs = SettingsPrefs(store)
store.updateData { p ->
val m = p.toMutablePreferences()
m[stringPreferencesKey("auto_backup_folder_uri")] = "content://tree/old"
m
}
prefs.setAutoBackupCombined(false)
assertThat(prefs.autoBackupLedger.first())
.containsExactly("latest-combined", listOf("calendula-backup.ics"))
}
private fun backupCalendar(id: Long, local: Boolean) = CalendarSource(
id = id,
displayName = "C$id",
accountName = "a",
accountType = if (local) "LOCAL" else "com.google",
color = 0,
isVisibleInSystem = true,
canModifyContents = true,
isLocal = local,
)
}
@@ -0,0 +1,208 @@
package de.jeanlucmakiola.calendula.data.reminders
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarSource
import org.junit.jupiter.api.Test
class ReminderChannelPlanTest {
private fun calendar(id: Long, account: String, type: String, local: Boolean = false) = CalendarSource(
id = id,
displayName = "Cal $id",
accountName = account,
accountType = type,
color = 0,
isVisibleInSystem = true,
isLocal = local,
)
@Test
fun `one channel per calendar, grouped by account`() {
val plan = planReminderChannels(
calendars = listOf(
calendar(1, "me@example.org", "com.google"),
calendar(2, "me@example.org", "com.google"),
calendar(3, "dav", "bitfire.at.davdroid"),
),
existing = emptyList(),
existingGroupIds = emptyList(),
unnamed = "Unnamed",
description = DESC,
)
assertThat(plan.groups).hasSize(2)
assertThat(plan.channels.map { it.id })
.containsExactly(reminderChannelId(1), reminderChannelId(2), reminderChannelId(3))
assertThat(plan.channels[0].groupId).isEqualTo(plan.channels[1].groupId)
assertThat(plan.channels[2].groupId).isNotEqualTo(plan.channels[0].groupId)
assertThat(plan.staleChannelIds).isEmpty()
}
@Test
fun `device calendars share one group`() {
val plan = planReminderChannels(
calendars = listOf(
calendar(1, "Calendula", "LOCAL", local = true),
calendar(2, "Other", "LOCAL", local = true),
),
existing = emptyList(),
existingGroupIds = emptyList(),
unnamed = "Unnamed",
description = DESC,
)
assertThat(plan.groups).hasSize(1)
assertThat(plan.groups.single().isLocal).isTrue()
}
@Test
fun `same account name under two types is ambiguous`() {
val plan = planReminderChannels(
calendars = listOf(
calendar(1, "me@example.org", "com.google"),
calendar(2, "me@example.org", "bitfire.at.davdroid"),
calendar(3, "work", "bitfire.at.davdroid"),
),
existing = emptyList(),
existingGroupIds = emptyList(),
unnamed = "Unnamed",
description = DESC,
)
assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType })
.containsExactly("com.google", "bitfire.at.davdroid")
assertThat(plan.groups.single { it.label == "work" }.ambiguous).isFalse()
}
@Test
fun `stale reminder channels and groups go, foreign ones stay`() {
val current = calendar(1, "me@example.org", "com.google")
fun plan(calendars: List<CalendarSource>, existing: List<String> = emptyList(), groups: List<String> = emptyList()) =
planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC, null) }, groups, "Unnamed", DESC)
val keptGroup = plan(listOf(current)).groups.single().id
val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id
val result = plan(
calendars = listOf(current),
existing = listOf(reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup"),
groups = listOf(keptGroup, goneGroup, "other"),
)
assertThat(result.staleChannelIds).containsExactly(reminderChannelId(9))
assertThat(result.staleGroupIds).containsExactly(goneGroup)
}
@Test
fun `only missing or renamed channels are written`() {
val plan = planReminderChannels(
calendars = listOf(
calendar(1, "a", "com.google"),
calendar(2, "a", "com.google"),
calendar(3, "a", "com.google").copy(displayName = ""),
calendar(4, "a", "com.google"),
),
existing = listOf(
ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"),
ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description", "g"),
ExistingReminderChannel(reminderChannelId(2), "Old name", DESC, "g"),
),
existingGroupIds = emptyList(),
unnamed = "Unnamed",
description = DESC,
)
assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L, 4L)
assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed")
}
@Test
fun `non-syncing calendars keep a channel but get none up front`() {
val quiet = calendar(2, "a", "com.google").copy(syncsEvents = false)
val fresh = planReminderChannels(listOf(quiet), emptyList(), emptyList(), "Unnamed", DESC)
assertThat(fresh.channelsToWrite).isEmpty()
assertThat(fresh.groupsInUse).isEmpty()
val posted = planReminderChannels(
calendars = listOf(quiet),
existing = listOf(ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, null)),
existingGroupIds = emptyList(),
unnamed = "Unnamed",
description = DESC,
)
assertThat(posted.staleChannelIds).isEmpty()
assertThat(posted.channelsToWrite.map { it.calendarId }).containsExactly(2L)
assertThat(posted.groupsInUse).hasSize(1)
}
@Test
fun `blocked calendars follow app, channel and group`() {
val channels = mapOf(
reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = "g1"),
reminderChannelId(2) to ReminderChannelState(blocked = false, groupId = "g2"),
reminderChannelId(3) to ReminderChannelState(blocked = false, groupId = "g1"),
)
val ids = listOf(1L, 2L, 3L, 4L)
val groupOff = reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2"))
assertThat(groupOff.blockedCalendarIds).containsExactly(1L, 2L)
assertThat(groupOff.groupBlockedCalendarIds).containsExactly(2L)
assertThat(reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = emptySet()).blockedCalendarIds)
.containsExactly(1L)
val appOff = reminderChannelStatus(ids, appEnabled = false, channels, blockedGroupIds = emptySet())
assertThat(appOff.appBlocked).isTrue()
assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L)
}
@Test
fun `a switched-off ring channel is reported while the app may notify`() {
val ringOff = mapOf(RING_CHANNEL_ID to ReminderChannelState(blocked = true, groupId = null))
assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, ringOff, emptySet()).ringBlocked).isTrue()
assertThat(reminderChannelStatus(listOf(1L), appEnabled = false, ringOff, emptySet()).ringBlocked).isFalse()
assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, emptyMap(), emptySet()).ringBlocked).isFalse()
}
@Test
fun `channel ids round-trip with versions`() {
assertThat(parseReminderChannelId(reminderChannelId(7))).isEqualTo(7L to 0)
assertThat(parseReminderChannelId(reminderChannelId(7, 3))).isEqualTo(7L to 3)
assertThat(parseReminderChannelId("reminders.calendar.7.v0")).isNull()
assertThat(parseReminderChannelId("reminders.calendar.x")).isNull()
assertThat(parseReminderChannelId(LEGACY_REMINDER_CHANNEL_ID)).isNull()
}
@Test
fun `a version bump retires the old channel unless it is showing`() {
val existing = listOf(
ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"),
ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, "g"),
)
val plan = planReminderChannels(
calendars = listOf(calendar(1, "a", "com.google"), calendar(2, "a", "com.google")),
existing = existing,
existingGroupIds = emptyList(),
unnamed = "Unnamed",
description = DESC,
versions = mapOf(1L to 2, 2L to 1),
showingChannelIds = setOf(reminderChannelId(2)),
)
assertThat(plan.channels.map { it.id }).containsExactly(reminderChannelId(1, 2), reminderChannelId(2, 1))
assertThat(plan.staleChannelIds).containsExactly(reminderChannelId(1))
assertThat(plan.keptChannelIds).containsExactly(reminderChannelId(2))
}
@Test
fun `the current version is the highest that exists, else the high-water mark`() {
val versions = currentReminderChannelVersions(
existingChannelIds = listOf(reminderChannelId(1), reminderChannelId(1, 2), reminderChannelId(3), "backup"),
highWater = mapOf(1L to 5, 2L to 4),
)
// Calendar 1 reserved v5 but never wrote it, so v2 stays current.
assertThat(versions).containsExactly(1L, 2, 2L, 4, 3L, 0)
}
@Test
fun `status reads the current channel version`() {
val channels = mapOf(
reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = null),
reminderChannelId(1, 2) to ReminderChannelState(blocked = false, groupId = null),
)
val status = reminderChannelStatus(listOf(1L), true, channels, emptySet(), versions = mapOf(1L to 2))
assertThat(status.blockedCalendarIds).isEmpty()
}
private companion object {
const val DESC = "Reminders"
}
}
@@ -583,9 +583,16 @@ class EventFormTest {
@Test
fun `a copy of a cancelled event starts confirmed, a tentative one stays tentative`() {
val zone = TimeZone.of("Europe/Berlin")
assertThat(testDetail(status = EventStatus.Cancelled).toDuplicateForm(canModify = true, zone).status)
assertThat(testDetail(status = EventStatus.Cancelled).toDuplicateForm(zone).status)
.isEqualTo(EventStatus.Confirmed)
assertThat(testDetail(status = EventStatus.Tentative).toDuplicateForm(canModify = true, zone).status)
assertThat(testDetail(status = EventStatus.Tentative).toDuplicateForm(zone).status)
.isEqualTo(EventStatus.Tentative)
}
@Test
fun `a copy requests its source calendar and keeps its colour`() {
val form = testDetail(eventColor = 7, eventColorKey = "3").toDuplicateForm(TimeZone.of("Europe/Berlin"))
assertThat(form.calendarId).isEqualTo(testEvent().calendarId)
assertThat(form.colorKey).isEqualTo("3")
}
}
@@ -0,0 +1,47 @@
package de.jeanlucmakiola.calendula.domain
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import org.junit.jupiter.api.Test
class FixedTimeReminderFormTest {
private val zone = TimeZone.of("Europe/Berlin")
private val evening = FixedTimeReminder(1, 20 * 60)
private fun form(start: String, reminders: List<Int> = emptyList(), allDay: Boolean = false) = EventForm(
calendarId = 1,
isAllDay = allDay,
start = FormTime(LocalDateTime.parse(start)),
end = FormTime(LocalDateTime.parse(start)),
reminders = reminders,
)
@Test
fun `a moved start re-derives the offset so the wall clock stays`() {
val loaded = form("2026-06-10T10:00", reminders = listOf(10, 840))
.withFixedTimeRemindersRead(known = setOf(evening), deviceZone = zone)
assertThat(loaded.reminders).containsExactly(10)
assertThat(loaded.fixedReminders).containsExactly(evening)
assertThat(loaded.fixedReminderOffsets(zone)).containsExactly(840)
val moved = loaded.copy(start = FormTime(LocalDateTime.parse("2026-06-10T15:30")))
assertThat(moved.fixedReminderOffsets(zone)).containsExactly(19 * 60 + 30)
}
@Test
fun `all-day forms keep their reminders and store no fixed ones`() {
val allDay = form("2026-06-10T00:00", reminders = listOf(840), allDay = true)
assertThat(allDay.withFixedTimeRemindersRead(setOf(evening), zone)).isEqualTo(allDay)
assertThat(allDay.copy(fixedReminders = listOf(evening)).fixedReminderOffsets(zone)).isEmpty()
}
@Test
fun `fixed reminders count as a populated reminders section on a timed event only`() {
val withFixed = form("2026-06-10T10:00").copy(fixedReminders = listOf(evening))
assertThat(withFixed.populatedFields()).contains(EventFormField.Reminders)
assertThat(withFixed.copy(isAllDay = true).populatedFields()).doesNotContain(EventFormField.Reminders)
}
}
@@ -24,6 +24,7 @@ class InsertEventFormTest {
description: String? = null,
location: String? = null,
rrule: String? = null,
calendarId: Long? = null,
): EventForm = buildInsertEventForm(
beginMillis = beginMillis,
endMillis = endMillis,
@@ -32,6 +33,7 @@ class InsertEventFormTest {
description = description,
location = location,
rrule = rrule,
calendarId = calendarId,
zone = zone,
now = now,
)
@@ -50,7 +52,7 @@ class InsertEventFormTest {
location = "Room 1",
rrule = "FREQ=DAILY",
)
assertThat(form.calendarId).isNull() // resolves to last-used / first-writable
assertThat(form.calendarId).isNull() // resolved by the editor
assertThat(form.isAllDay).isFalse()
assertThat(form.start.dateTime).isEqualTo(start)
assertThat(form.end.dateTime).isEqualTo(end)
@@ -60,6 +62,11 @@ class InsertEventFormTest {
assertThat(form.rrule).isEqualTo("FREQ=DAILY")
}
@Test
fun `a named calendar is carried over`() {
assertThat(build(calendarId = 7L).calendarId).isEqualTo(7L)
}
@Test
fun `missing times default to the next full hour and a one-hour duration`() {
val form = build(title = "Quick note")
@@ -0,0 +1,102 @@
package de.jeanlucmakiola.calendula.domain
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class NewEventCalendarTest {
private fun cal(
id: Long,
writable: Boolean = true,
visible: Boolean = true,
managed: Boolean = false,
) = CalendarSource(
id = id,
displayName = "Cal $id",
accountName = "account",
accountType = "com.google",
color = 0,
isVisibleInSystem = visible,
canModifyContents = writable,
isManaged = managed,
)
private fun ref(id: Long) = DefaultCalendarRef.of(cal(id))
private val calendars = listOf(
cal(1L),
cal(2L),
cal(3L),
cal(4L, writable = false),
cal(5L, visible = false),
cal(6L, managed = true),
)
@Test
fun `a user pick always wins`() {
val hints = NewEventCalendarHints(requested = 2L, default = ref(3L), lastUsed = 1L)
assertThat(resolveEventCalendar(4L, hints, calendars)).isEqualTo(4L)
}
@Test
fun `a requested calendar beats the default`() {
val hints = NewEventCalendarHints(requested = 2L, default = ref(3L))
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L)
}
@Test
fun `a requested calendar that is no target falls back to the default`() {
listOf(4L, 5L, 6L, 99L).forEach { requested ->
val hints = NewEventCalendarHints(requested = requested, default = ref(3L))
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L)
}
}
@Test
fun `the default beats the last used calendar`() {
val hints = NewEventCalendarHints(default = ref(3L), lastUsed = 2L)
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L)
}
@Test
fun `a default that is no target falls back to the last used calendar`() {
listOf(4L, 5L, 6L).forEach { id ->
val default = DefaultCalendarRef.of(calendars.single { it.id == id })
val hints = NewEventCalendarHints(default = default, lastUsed = 2L)
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L)
assertThat(effectiveDefaultCalendar(default, calendars)).isNull()
}
assertThat(effectiveDefaultCalendar(ref(99L), calendars)).isNull()
}
@Test
fun `without hints the first target is used`() {
val withoutFirst = listOf(cal(4L, writable = false), cal(5L, visible = false), cal(2L))
assertThat(resolveEventCalendar(null, NewEventCalendarHints(lastUsed = 5L), withoutFirst)).isEqualTo(2L)
assertThat(resolveEventCalendar(null, NewEventCalendarHints(), emptyList())).isNull()
}
@Test
fun `the effective default is the stored calendar while it is a target`() {
assertThat(effectiveDefaultCalendar(ref(3L), calendars)?.id).isEqualTo(3L)
assertThat(effectiveDefaultCalendar(null, calendars)).isNull()
}
@Test
fun `the default survives a rename and a new id, but not another account`() {
assertThat(effectiveDefaultCalendar(ref(3L).copy(displayName = "Old name"), calendars)?.id).isEqualTo(3L)
assertThat(effectiveDefaultCalendar(ref(3L).copy(id = 99L), calendars)?.id).isEqualTo(3L)
// The id was handed to another calendar of the account; the name decides.
assertThat(effectiveDefaultCalendar(ref(3L).copy(id = 2L), calendars)?.id).isEqualTo(3L)
assertThat(effectiveDefaultCalendar(ref(3L).copy(accountName = "other"), calendars)).isNull()
}
@Test
fun `the stored reference round-trips`() {
val stored = DefaultCalendarRef(12L, "com.google", "me@example.com", "Work | Team")
assertThat(DefaultCalendarRef.decode(stored.encode())).isEqualTo(stored)
assertThat(DefaultCalendarRef.decode(null)).isNull()
assertThat(DefaultCalendarRef.decode("12")).isNull()
assertThat(DefaultCalendarRef.decode("x\u001Fa\u001Fb\u001Fc")).isNull()
}
}
@@ -0,0 +1,451 @@
package de.jeanlucmakiola.calendula.domain.backup
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
import kotlin.time.Instant
class BackupPlanTest {
private fun cal(
id: Long,
name: String = "Calendar $id",
local: Boolean = false,
writable: Boolean = true,
managed: Boolean = false,
syncs: Boolean = true,
) = CalendarSource(
id = id,
displayName = name,
accountName = "acc",
accountType = if (local) "LOCAL" else "bitfire.at.davdroid",
color = 0,
isVisibleInSystem = true,
canModifyContents = writable,
isLocal = local,
isManaged = managed,
syncsEvents = syncs,
)
private val at = LocalDateTime.of(2026, 11, 13, 14, 30, 5)
@Test
fun `local calendars are selected by default, synced ones are opt-in`() {
val selection = BackupSelection()
assertThat(selection.selects(cal(1L, local = true))).isTrue()
assertThat(selection.selects(cal(2L))).isFalse()
assertThat(selection.selects(cal(3L, writable = false))).isFalse()
}
@Test
fun `managed and unsynced calendars are never backed up`() {
val selection = BackupSelection(included = setOf(1L, 2L))
assertThat(selection.selects(cal(1L, local = true, managed = true))).isFalse()
assertThat(selection.selects(cal(2L, syncs = false))).isFalse()
}
@Test
fun `toggling back to the default leaves no trace`() {
val synced = cal(2L)
val local = cal(1L, local = true)
val chosen = BackupSelection().with(synced, true).with(local, false)
assertThat(chosen).isEqualTo(BackupSelection(included = setOf(2L), excluded = setOf(1L)))
assertThat(chosen.with(synced, false).with(local, true)).isEqualTo(BackupSelection())
}
@Test
fun `one target per calendar, with no owner the lowest id keeps a clashing name`() {
val targets = backupTargets(
listOf(cal(2L, "personal"), cal(1L, "Personal", local = true), cal(3L, "Work")),
combined = false,
)
assertThat(targets.map { it.baseName }).containsExactly("personal-2", "Personal", "Work").inOrder()
assertThat(targets.map { it.calendarName }).containsExactly("personal", "Personal", "Work").inOrder()
}
@Test
fun `the calendar already owning a name keeps it when a new one shares it`() {
val calendars = listOf(cal(9L, "Fitness"), cal(20L, "Fitness"), cal(4L, "Fitness"))
val byStable = backupTargets(calendars, combined = false, mapOf(latestLedgerKey("9") to listOf("Fitness.ics")))
assertThat(byStable.map { it.baseName }).containsExactly("Fitness", "Fitness-20", "Fitness-4").inOrder()
// A dated file counts too, for a series whose stable copy was blocked by the user's own file.
val byDated = backupTargets(calendars, combined = false, mapOf("20" to listOf("Fitness_2026-11-13_14-30-05.ics")))
assertThat(byDated.map { it.baseName }).containsExactly("Fitness-9", "Fitness", "Fitness-4").inOrder()
}
@Test
fun `series already writing under their id suffix keep it`() {
val ledger = mapOf(
latestLedgerKey("9") to listOf("Fitness-9.ics"),
latestLedgerKey("20") to listOf("Fitness-20.ics"),
)
val targets = backupTargets(listOf(cal(20L, "Fitness"), cal(9L, "Fitness")), combined = false, ledger)
assertThat(targets.map { it.baseName }).containsExactly("Fitness-20", "Fitness-9").inOrder()
}
@Test
fun `the stable copy's owner beats a series with only old dated files under the name`() {
val ledger = mapOf(
"9" to listOf("Fitness_2026-11-01_10-00-00.ics"),
latestLedgerKey("20") to listOf("Fitness.ics"),
)
val targets = backupTargets(listOf(cal(9L, "Fitness"), cal(20L, "Fitness")), combined = false, ledger)
assertThat(targets.map { it.baseName }).containsExactly("Fitness-9", "Fitness").inOrder()
}
@Test
fun `a provider-renamed dated file still claims the name, a file gone from the folder doesn't`() {
val calendars = listOf(cal(9L, "Fitness"), cal(20L, "Fitness"))
val renamed = mapOf("20" to listOf("Fitness_2026-11-13_14-30-05 (1).ics"))
assertThat(backupTargets(calendars, combined = false, renamed).map { it.baseName })
.containsExactly("Fitness-9", "Fitness").inOrder()
val gone = mapOf(latestLedgerKey("20") to listOf("Fitness.ics"))
assertThat(backupTargets(calendars, combined = false, gone, existing = emptySet()).map { it.baseName })
.containsExactly("Fitness", "Fitness-20").inOrder()
}
@Test
fun `a stable copy kept for a calendar out of the backup isn't taken over or left blocking`() {
val ledger = mapOf(latestLedgerKey("9") to listOf("Fitness.ics"))
val target = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, setOf("Fitness.ics")).single()
assertThat(target.baseName).isEqualTo("Fitness-20")
val plan = planBackupFiles(listOf(target), ledger, setOf("Fitness.ics"), at, keep = 3).single()
assertThat(plan.backedUp(intervalOn = false)).isTrue()
val gone = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, existing = emptySet()).single()
assertThat(gone.baseName).isEqualTo("Fitness")
}
@Test
fun `a series writing under its id suffix keeps it once the clash is gone`() {
val ledger = mapOf(latestLedgerKey("20") to listOf("Fitness-20.ics"))
val target = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, setOf("Fitness.ics", "Fitness-20.ics"))
.single()
assertThat(target.baseName).isEqualTo("Fitness-20")
}
@Test
fun `a calendar named like the combined file doesn't share its series`() {
val target = backupTargets(listOf(cal(4L, COMBINED_BACKUP_BASE)), combined = false).single()
assertThat(target.baseName).isEqualTo("$COMBINED_BACKUP_BASE-4")
}
@Test
fun `combined mode is one target holding every calendar`() {
val target = backupTargets(listOf(cal(1L), cal(2L)), combined = true).single()
assertThat(target.key).isEqualTo(COMBINED_SERIES)
assertThat(target.calendarIds).containsExactly(1L, 2L)
assertThat(target.baseName).isEqualTo(COMBINED_BACKUP_BASE)
assertThat(target.calendarName).isNull()
assertThat(backupTargets(emptyList(), combined = true)).isEmpty()
}
@Test
fun `the new file carries the date and time of the run`() {
assertThat(backupFileName("Work", at)).isEqualTo("Work_2026-11-13_14-30-05.ics")
}
private val work = BackupTarget("1", setOf(1L), "Work", "Work")
@Test
fun `pruning keeps the newest recorded files and nothing else`() {
val ledger = mapOf("1" to listOf("Work_a.ics", "Work_b.ics", "Work_c.ics"))
val existing = setOf("Work_a.ics", "Work_b.ics", "Work_c.ics", "Work_2026-11-01_09-00-00.ics", "Work notes.ics")
val plan = planBackupFiles(listOf(work), ledger, existing, at, keep = 3).single()
assertThat(plan.fileName).isEqualTo("Work_2026-11-13_14-30-05.ics")
assertThat(plan.keep).containsExactly("Work_b.ics", "Work_c.ics").inOrder()
assertThat(plan.prune).containsExactly("Work_a.ics")
}
@Test
fun `keeping one replaces every earlier file`() {
val ledger = mapOf("1" to listOf("Work_a.ics", "Work_b.ics"))
val plan = planBackupFiles(listOf(work), ledger, setOf("Work_a.ics", "Work_b.ics"), at, keep = 1).single()
assertThat(plan.keep).isEmpty()
assertThat(plan.prune).containsExactly("Work_a.ics", "Work_b.ics").inOrder()
}
@Test
fun `files gone from the folder are forgotten, not counted`() {
val ledger = mapOf("1" to listOf("Work_a.ics", "Work_b.ics"))
val plan = planBackupFiles(listOf(work), ledger, setOf("Work_b.ics"), at, keep = 2).single()
assertThat(plan.keep).containsExactly("Work_b.ics")
assertThat(plan.prune).isEmpty()
}
@Test
fun `a same-named calendar never prunes another calendar's files`() {
// Local "Work" (id 1) was backed up; the user now backs up a synced "Work" (id 9) instead.
val ledger = mapOf("1" to listOf("Work_a.ics"))
val synced = backupTargets(listOf(cal(9L, "Work")), combined = false).single()
val plan = planBackupFiles(listOf(synced), ledger, setOf("Work_a.ics"), at, keep = 1).single()
assertThat(plan.prune).isEmpty()
}
@Test
fun `a rerun in the same second never prunes the file it writes`() {
val name = "Work_2026-11-13_14-30-05.ics"
val plan = planBackupFiles(listOf(work), mapOf("1" to listOf(name)), setOf(name), at, keep = 1).single()
assertThat(plan.prune).isEmpty()
}
private val combined = BackupTarget(COMBINED_SERIES, setOf(1L, 2L), COMBINED_BACKUP_BASE, null)
@Test
fun `the pre-411 file is the combined stable copy only for the install that wrote it`() {
val adopted = mapOf(latestLedgerKey(COMBINED_SERIES) to listOf(LEGACY_BACKUP_FILE))
val owned = planBackupFiles(listOf(combined), adopted, setOf(LEGACY_BACKUP_FILE), at, 1)
assertThat(owned.single().latestName).isEqualTo(LEGACY_BACKUP_FILE)
assertThat(owned.single().prune).isEmpty()
val foreign = planBackupFiles(listOf(combined), emptyMap(), setOf(LEGACY_BACKUP_FILE), at, 1)
assertThat(foreign.single().latestName).isNull()
}
@Test
fun `a stable name recorded as a dated file by an earlier build is never pruned`() {
val ledger = mapOf(COMBINED_SERIES to listOf(LEGACY_BACKUP_FILE, "calendula-backup_a.ics"))
val plan = planBackupFiles(
listOf(combined), ledger, setOf(LEGACY_BACKUP_FILE, "calendula-backup_a.ics"), at, 1,
).single()
assertThat(plan.prune).containsExactly("calendula-backup_a.ics")
}
@Test
fun `per-calendar series leave the legacy combined file alone`() {
val plan = planBackupFiles(listOf(work), emptyMap(), setOf(LEGACY_BACKUP_FILE), at, keep = 1).single()
assertThat(plan.prune).isEmpty()
assertThat(plan.staleLatest).isEmpty()
assertThat(plan.latestName).isEqualTo("Work.ics")
}
@Test
fun `the stable copy is never pruned and never overwrites the user's own file`() {
val ours = planBackupFiles(
listOf(work),
mapOf("1" to listOf("Work_a.ics"), latestLedgerKey("1") to listOf("Work.ics")),
setOf("Work_a.ics", "Work.ics"),
at,
keep = 1,
).single()
assertThat(ours.latestName).isEqualTo("Work.ics")
assertThat(ours.prune).containsExactly("Work_a.ics")
val foreign = planBackupFiles(listOf(work), emptyMap(), setOf("Work.ics"), at, keep = 1).single()
assertThat(foreign.latestName).isNull()
}
@Test
fun `a renamed calendar replaces its old stable copy`() {
val job = BackupTarget("1", setOf(1L), "Job", "Job")
val plan = planBackupFiles(
listOf(job),
mapOf(latestLedgerKey("1") to listOf("Work.ics")),
setOf("Work.ics"),
at,
keep = 3,
).single()
assertThat(plan.latestName).isEqualTo("Job.ics")
assertThat(plan.staleLatest).containsExactly("Work.ics")
}
@Test
fun `a stable copy is handed over to the calendar that takes its name in the same run`() {
// Calendar 1 was "Work", is now "Job"; calendar 2 is now called "Work".
val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics"))
val plans = planBackupFiles(
listOf(BackupTarget("1", setOf(1L), "Job", "Job"), BackupTarget("2", setOf(2L), "Work", "Work")),
ledger,
setOf("Work.ics"),
at,
keep = 1,
)
assertThat(plans[0].staleLatest).isEmpty()
assertThat(plans[0].handOff).containsExactly("Work.ics")
assertThat(plans[1].latestName).isEqualTo("Work.ics")
}
@Test
fun `a deselected calendar's stable copy is not taken over by a same-named one`() {
// Calendar 3 "Personal" is out of the backup; calendar 9, also "Personal", is in.
val ledger = mapOf(latestLedgerKey("3") to listOf("Personal.ics"))
val plan = planBackupFiles(
listOf(BackupTarget("9", setOf(9L), "Personal", "Personal")), ledger, setOf("Personal.ics"), at, 1,
).single()
assertThat(plan.latestName).isNull()
}
@Test
fun `a layout switch replaces the other layout's stable copies, a deselected calendar keeps its own`() {
val ledger = mapOf(
latestLedgerKey("1") to listOf("Work.ics"),
latestLedgerKey("5") to listOf("Old.ics"),
latestLedgerKey(COMBINED_SERIES) to listOf(LEGACY_BACKUP_FILE),
)
val existing = setOf("Work.ics", "Old.ics", LEGACY_BACKUP_FILE)
assertThat(replacedLatestCopies(listOf(combined), ledger, existing))
.containsExactly("1", listOf("Work.ics"))
assertThat(replacedLatestCopies(listOf(work), ledger, existing))
.containsExactly(COMBINED_SERIES, listOf(LEGACY_BACKUP_FILE))
}
@Test
fun `a ledger entry is set, emptied away, and dropped with its calendar`() {
val previous = mapOf(
"1" to listOf("Work_a.ics"),
latestLedgerKey("7") to listOf("Gone.ics"),
latestLedgerKey(COMBINED_SERIES) to listOf(LEGACY_BACKUP_FILE),
)
val next = withLedgerEntry(previous, "1", listOf("Work_a.ics", "Work_b.ics", "Work_b.ics"), setOf("1"))
assertThat(next).containsExactly(
"1", listOf("Work_a.ics", "Work_b.ics"),
latestLedgerKey(COMBINED_SERIES), listOf(LEGACY_BACKUP_FILE),
)
assertThat(withLedgerEntry(next, "1", emptyList(), setOf("1")).keys)
.containsExactly(latestLedgerKey(COMBINED_SERIES))
}
@Test
fun `the ledger round-trips through storage`() {
val ledger = mapOf("3" to listOf("Work_b.ics", "Work_a (1).ics"), COMBINED_SERIES to listOf("calendula-backup_x.ics"))
assertThat(parseBackupLedger(persistBackupLedger(ledger))).isEqualTo(ledger)
assertThat(persistBackupLedger(emptyMap())).isNull()
assertThat(parseBackupLedger("garbage|/x|4/")).isEmpty()
}
@Test
fun `retention snaps to the offered choices`() {
assertThat(normalizeBackupKeep(0)).isEqualTo(1)
assertThat(normalizeBackupKeep(3)).isEqualTo(3)
assertThat(normalizeBackupKeep(50)).isEqualTo(10)
}
@Test
fun `a suffixed name that meets a real one is told apart again`() {
val targets = backupTargets(
listOf(cal(5L, "Work"), cal(6L, "Work"), cal(9L, "Work-6")),
combined = false,
)
assertThat(targets.map { it.baseName }).containsExactly("Work", "Work-6", "Work-6-9").inOrder()
}
@Test
fun `claiming a stable copy takes it off its previous owner`() {
val previous = mapOf(latestLedgerKey("1") to listOf("Work.ics", "Job.ics"))
val next = withLedgerEntry(previous, latestLedgerKey("2"), listOf("Work.ics"), setOf("1", "2"))
assertThat(next).containsExactly(
latestLedgerKey("1"), listOf("Job.ics"),
latestLedgerKey("2"), listOf("Work.ics"),
)
}
@Test
fun `a claimed hand-off shows as held elsewhere`() {
val ledger = mapOf(latestLedgerKey("1") to listOf("Job.ics"), latestLedgerKey("2") to listOf("Work.ics"), "2" to listOf("Work_a.ics"))
assertThat(ledger.latestHeldElsewhere("1")).containsExactly("Work.ics")
assertThat(ledger.latestHeldElsewhere("2")).containsExactly("Job.ics")
}
@Test
fun `fingerprints survive storage and drop deleted calendars`() {
val stored = persistBackupFingerprints(mapOf("1" to "ab", COMBINED_SERIES to "cd"))
assertThat(parseBackupFingerprints(stored)).containsExactly("1", "ab", COMBINED_SERIES, "cd")
assertThat(persistBackupFingerprints(emptyMap())).isNull()
assertThat(parseBackupFingerprints(null)).isEmpty()
val next = withFingerprint(mapOf("1" to "ab", "9" to "ef", COMBINED_SERIES to "cd"), "2", "gh", setOf("1", "2"))
assertThat(next).containsExactly("1", "ab", COMBINED_SERIES, "cd", "2", "gh")
}
@Test
fun `a fingerprint follows the content`() {
val first = "BEGIN:VEVENT\r\nDTSTAMP:20261113T143005Z\r\nSUMMARY:A\r\nEND:VEVENT\r\n"
val later = first.replace("20261113T143005Z", "20261114T090000Z")
assertThat(backupFingerprint(later, "Work.ics")).isEqualTo(backupFingerprint(first, "Work.ics"))
assertThat(backupFingerprint(first.replace("SUMMARY:A", "SUMMARY:B"), "Work.ics")).isNotEqualTo(backupFingerprint(first, "Work.ics"))
assertThat(backupFingerprint(first, "Work.ics")).hasLength(32)
assertThat(backupFingerprint(first, "Job.ics")).isNotEqualTo(backupFingerprint(first, "Work.ics"))
}
@Test
fun `the writer's output hashes the same at any stamp`() {
val event = IcsEvent(
uid = "u1", summary = "A", start = Instant.fromEpochSeconds(0), end = Instant.fromEpochSeconds(3600),
isAllDay = false, zoneId = "UTC",
)
val early = IcsWriter().writeCalendar(listOf(event), Instant.fromEpochSeconds(0), "Work")
val late = IcsWriter().writeCalendar(listOf(event), Instant.fromEpochSeconds(1_800_000_000), "Work")
assertThat(early).isNotEqualTo(late)
assertThat(backupFingerprint(late, "Work.ics")).isEqualTo(backupFingerprint(early, "Work.ics"))
}
@Test
fun `a change run refreshes only a changed or missing stable copy`() {
val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single()
val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics"))
val plan = planBackupFiles(listOf(target), ledger, setOf("Work.ics"), at, keep = 3).single()
val stored = mapOf("1" to "h1")
val listed = setOf("Work.ics")
assertThat(plan.needsRefresh("h1", stored, listed, complete = true)).isFalse()
assertThat(plan.needsRefresh("h2", stored, listed, complete = true)).isTrue()
assertThat(plan.needsRefresh("h1", emptyMap(), listed, complete = true)).isTrue()
assertThat(plan.needsRefresh("h1", stored, emptySet(), complete = true)).isTrue()
}
@Test
fun `a change run leaves a copy a loading listing doesn't show to the schedule`() {
val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single()
val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics"))
val plan = planBackupFiles(listOf(target), ledger, setOf("Work.ics"), at, keep = 3).single()
assertThat(plan.needsRefresh("h2", mapOf("1" to "h1"), emptySet(), complete = false)).isFalse()
assertThat(plan.needsRefresh("h2", mapOf("1" to "h1"), setOf("Work.ics"), complete = false)).isTrue()
}
@Test
fun `a change run never writes over a file of the user's`() {
val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single()
val plan = planBackupFiles(listOf(target), emptyMap(), setOf("Work.ics"), at, keep = 3).single()
assertThat(plan.latestName).isNull()
assertThat(plan.needsRefresh("h1", emptyMap(), setOf("Work.ics"), complete = true)).isFalse()
}
@Test
fun `backup order doesn't depend on the provider's`() {
fun event(uid: String, reminders: List<Int>) = IcsEvent(
uid = uid, summary = uid, start = Instant.fromEpochSeconds(0), end = Instant.fromEpochSeconds(3600),
isAllDay = false, zoneId = "UTC", reminderMinutes = reminders,
)
val one = listOf(event("b", listOf(15, 10)), event("a", listOf(5)))
val other = listOf(event("a", listOf(5)), event("b", listOf(10, 15)))
assertThat(one.inBackupOrder()).isEqualTo(other.inBackupOrder())
assertThat(one.inBackupOrder().map { it.uid }).containsExactly("a", "b").inOrder()
}
@Test
fun `the interval stays on unless after-change backups cover for it`() {
assertThat(backupIntervalOn(stored = true, onChange = false)).isTrue()
assertThat(backupIntervalOn(stored = false, onChange = false)).isTrue()
assertThat(backupIntervalOn(stored = true, onChange = true)).isTrue()
assertThat(backupIntervalOn(stored = false, onChange = true)).isFalse()
}
@Test
fun `only a run with the interval on writes dated files`() {
assertThat(backupRunLatestOnly(changeRun = false, intervalOn = true)).isFalse()
assertThat(backupRunLatestOnly(changeRun = true, intervalOn = true)).isTrue()
assertThat(backupRunLatestOnly(changeRun = false, intervalOn = false)).isTrue()
assertThat(backupRunLatestOnly(changeRun = true, intervalOn = false)).isTrue()
}
@Test
fun `without the interval a series whose stable name is the user's goes unbacked`() {
val free = planBackupFiles(listOf(work), emptyMap(), emptySet(), at, keep = 3).single()
val blocked = planBackupFiles(listOf(work), emptyMap(), setOf("Work.ics"), at, keep = 3).single()
assertThat(free.backedUp(intervalOn = false)).isTrue()
assertThat(blocked.backedUp(intervalOn = false)).isFalse()
assertThat(blocked.backedUp(intervalOn = true)).isTrue()
}
}
@@ -0,0 +1,287 @@
package de.jeanlucmakiola.calendula.domain.ics
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.calendar.formatExdateStamp
import de.jeanlucmakiola.calendula.domain.EventStatus
import org.junit.jupiter.api.Test
import kotlin.time.Instant
/** How a calendar's exception rows are written out for a backup (#147) or a copy (#325). */
class CalendarRowsTest {
private val start = Instant.parse("2026-01-05T09:00:00Z")
private val week = 7 * 24 * 3_600_000L
private fun event(
uid: String,
rrule: String? = null,
allDay: Boolean = false,
at: Instant = start,
status: EventStatus = EventStatus.Confirmed,
exDates: List<String> = emptyList(),
reminders: List<Int> = emptyList(),
color: Int? = null,
) = IcsEvent(
uid = uid,
summary = uid,
start = at,
end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L),
isAllDay = allDay,
zoneId = "Europe/Berlin",
recurrenceRule = rrule,
exDates = exDates,
reminderMinutes = reminders,
status = status,
color = color,
calendarName = "Work",
)
private fun occurrence(n: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + n * week)
private fun series(uid: String, rrule: String? = "FREQ=WEEKLY", id: Long = 1, calendar: Long = 1, syncId: String? = null, status: EventStatus = EventStatus.Confirmed) =
MasterRow(id, calendar, syncId, event(uid, rrule = rrule, status = status))
private fun flatten(series: List<MasterRow>, overrides: List<OverrideRow>) =
flattenOverrides(CalendarRows(series, overrides), ::formatExdateStamp)
@Test
fun `a cancelled occurrence becomes an EXDATE on the series`() {
val flat = flatten(
listOf(MasterRow(1, 1, "sync-1", event("s", rrule = "FREQ=WEEKLY", exDates = listOf("20260112T080000Z")))),
listOf(OverrideRow(1, null, "sync-1", occurrence(2), event("s", at = occurrence(2), status = EventStatus.Cancelled))),
)
assertThat(flat.single().exDates).containsExactly("20260112T080000Z", "20260119T090000Z").inOrder()
}
@Test
fun `a modified occurrence is excluded from the series and written on its own, first`() {
val moved = Instant.fromEpochMilliseconds(occurrence(1).toEpochMilliseconds() + 3_600_000L)
val flat = flatten(
listOf(series("s")),
listOf(OverrideRow(1, 1, null, occurrence(1), event("s", rrule = "FREQ=WEEKLY", at = moved))),
)
assertThat(flat).hasSize(2)
val detached = flat[0]
assertThat(detached.uid).isEqualTo("${occurrence(1).toEpochMilliseconds()}-s")
assertThat(detached.overrideOf).isEqualTo("s")
assertThat(detached.recurrenceRule).isNull()
assertThat(detached.start).isEqualTo(moved)
assertThat(detached.calendarName).isEqualTo("Work")
assertThat(flat[1].exDates).containsExactly("20260112T090000Z")
}
@Test
fun `an all-day series excludes the occurrence by its day`() {
val day = Instant.parse("2026-01-05T00:00:00Z")
val flat = flatten(
listOf(MasterRow(1, 1, null, event("s", rrule = "FREQ=DAILY", allDay = true, at = day))),
listOf(OverrideRow(1, 1, null, Instant.parse("2026-01-07T00:00:00Z"), event("s", allDay = true, status = EventStatus.Cancelled))),
)
assertThat(flat.single().exDates).containsExactly("20260107")
}
@Test
fun `exceptions without their series are left out`() {
val flat = flatten(
emptyList(),
listOf(
OverrideRow(1, 5, null, occurrence(1), event("x")),
OverrideRow(1, 5, null, occurrence(2), event("y", status = EventStatus.Cancelled)),
),
)
assertThat(flat).isEmpty()
}
@Test
fun `a sync id links an exception only within its own calendar`() {
val flat = flatten(
listOf(series("a", calendar = 1, syncId = "same"), series("b", id = 2, calendar = 2, syncId = "same")),
listOf(OverrideRow(2, null, "same", occurrence(1), event("x", status = EventStatus.Cancelled))),
)
assertThat(flat.first { it.uid == "a" }.exDates).isEmpty()
assertThat(flat.first { it.uid == "b" }.exDates).containsExactly("20260112T090000Z")
}
@Test
fun `an exception to a one-off is ignored`() {
val flat = flatten(
listOf(series("o", rrule = null)),
listOf(OverrideRow(1, 1, null, occurrence(0), event("x"))),
)
assertThat(flat.map { it.uid }).containsExactly("o")
}
@Test
fun `an RDATE-only series keeps its dates and takes its exceptions`() {
val flat = flatten(
listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = listOf("20260112T090000Z")))),
listOf(OverrideRow(1, 1, null, occurrence(1), event("s", status = EventStatus.Cancelled))),
)
assertThat(flat.single().recurrenceDates).containsExactly("20260112T090000Z")
assertThat(flat.single().exDates).containsExactly("20260112T090000Z")
}
@Test
fun `two exception rows for one occurrence are written once`() {
val flat = flatten(
listOf(series("s")),
listOf(OverrideRow(1, 1, null, occurrence(1), event("x")), OverrideRow(1, 1, null, occurrence(1), event("y"))),
)
assertThat(flat.map { it.summary }).containsExactly("x", "s").inOrder()
}
@Test
fun `the output is stable, so a re-run dedups every event`() {
val rows = CalendarRows(listOf(series("s")), listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))))
assertThat(flattenOverrides(rows, ::formatExdateStamp).map { it.uid })
.isEqualTo(flattenOverrides(rows, ::formatExdateStamp).map { it.uid })
}
@Test
fun `a backup keeps a cancelled series, a copy leaves it out with its exceptions`() {
val rows = CalendarRows(
listOf(series("s", status = EventStatus.Cancelled)),
listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))),
)
assertThat(flattenOverrides(rows, ::formatExdateStamp).map { it.uid }).contains("s")
assertThat(planCalendarCopy(rows, ::formatExdateStamp)).isEmpty()
}
@Test
fun `a copy keeps the zone, colour and override link`() {
val rows = CalendarRows(
listOf(MasterRow(1, 1, null, event("s", rrule = "FREQ=WEEKLY", reminders = listOf(10, -5, 10), color = 0xFF112233.toInt()))),
listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))),
)
val (detached, copied) = planCalendarCopy(rows, ::formatExdateStamp)
assertThat(detached.overrideOf).isEqualTo("s")
assertThat(copied.zoneId).isEqualTo("Europe/Berlin")
assertThat(copied.color).isEqualTo(0xFF112233.toInt())
assertThat(copied.reminderMinutes).containsExactly(10)
}
@Test
fun `a zero-length all-day event lasts its day`() {
val day = Instant.parse("2026-01-05T00:00:00Z")
val parsed = event("a", allDay = true, at = day).copy(end = day).toParsedIcsEvent()
assertThat(parsed.end).isEqualTo(Instant.parse("2026-01-06T00:00:00Z"))
}
@Test
fun `the override link survives the file`() {
val text = IcsWriter().writeCalendar(listOf(event("d").copy(overrideOf = "s;1", overrideAt = occurrence(1))), start)
val parsed = IcsParser().parse(text).events.single()
assertThat(parsed.overrideOf).isEqualTo("s;1")
assertThat(parsed.overrideAt).isEqualTo(occurrence(1))
}
@Test
fun `a cancelled series' moved occurrence isn't brought back`() {
val flat = flatten(
listOf(series("s", status = EventStatus.Cancelled)),
listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))),
)
assertThat(flat.map { it.uid }).containsExactly("s")
}
@Test
fun `the same series in two calendars keeps each calendar's moved occurrence`() {
val flat = flatten(
listOf(series("s", id = 1, calendar = 1), series("s", id = 2, calendar = 2)),
listOf(
OverrideRow(1, 1, null, occurrence(1), event("x")),
OverrideRow(2, 2, null, occurrence(1), event("x")),
),
)
assertThat(flat.count { it.overrideOf == "s" }).isEqualTo(2)
}
@Test
fun `a copy leaves declined invitations out but keeps an occurrence accepted on its own`() {
val rows = CalendarRows(
listOf(series("d").copy(declined = true), series("k", id = 2)),
listOf(
OverrideRow(1, 1, null, occurrence(1), event("accepted"), accepted = true),
OverrideRow(1, 1, null, occurrence(2), event("moved by the organizer")),
),
)
val plan = planCalendarCopy(rows, ::formatExdateStamp)
assertThat(plan.map { it.summary }).containsExactly("accepted", "k")
}
@Test
fun `a copy treats a declined occurrence as deleted`() {
val rows = CalendarRows(
listOf(series("s")),
listOf(OverrideRow(1, 1, null, occurrence(1), event("x"), declined = true)),
)
val plan = planCalendarCopy(rows, ::formatExdateStamp)
assertThat(plan.map { it.uid }).containsExactly("s")
assertThat(plan.single().exDates).containsExactly("20260112T090000Z")
}
@Test
fun `RDATE and its exclusions survive the file`() {
val timed = event("t").copy(
recurrenceDates = listOf("20260112T090000Z", "20260120T090000Z"),
exDates = listOf("20260112T090000Z"),
)
val day = Instant.parse("2026-01-05T00:00:00Z")
val allDay = event("a", allDay = true, at = day).copy(
end = Instant.parse("2026-01-06T00:00:00Z"),
recurrenceDates = listOf("20260110"),
exDates = listOf("20260110"),
)
val text = IcsWriter().writeCalendar(listOf(timed, allDay), start)
assertThat(text).contains("RDATE;VALUE=DATE:20260110")
assertThat(text).contains("DTSTART;TZID=Europe/Berlin:20260105T100000")
val (t, a) = IcsParser().parse(text).events
assertThat(t.recurrenceDates).containsExactly("20260112T090000Z", "20260120T090000Z")
assertThat(t.exDates).containsExactly("20260112T090000Z")
assertThat(a.recurrenceDates).containsExactly("20260110")
assertThat(a.exDates).containsExactly("20260110")
}
@Test
fun `a foreign RDATE is read in its own zone, a period by its start`() {
val text = """
BEGIN:VCALENDAR
BEGIN:VEVENT
UID:f
DTSTART;TZID=Europe/Berlin:20260105T100000
DTEND;TZID=Europe/Berlin:20260105T110000
RDATE;TZID=America/New_York:20260110T090000
RDATE;VALUE=PERIOD:20260111T090000Z/PT1H
END:VEVENT
END:VCALENDAR
""".trimIndent().replace("\n", "\r\n")
assertThat(IcsParser().parse(text).events.single().recurrenceDates)
.containsExactly("20260110T140000Z", "20260111T090000Z")
}
@Test
fun `a declined row takes no other row with its UID along`() {
val rows = CalendarRows(listOf(series("u").copy(declined = true), series("u", id = 2)), emptyList())
assertThat(planCalendarCopy(rows, ::formatExdateStamp)).hasSize(1)
}
}
@@ -0,0 +1,89 @@
package de.jeanlucmakiola.calendula.domain.reminders
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
class DailyDigestTest {
private val zone = ZoneId.of("Europe/Berlin")
private val minute = 60_000L
private val eight = 20 * 60
private fun millis(text: String): Long = LocalDateTime.parse(text).atZone(zone).toInstant().toEpochMilli()
@Test
fun `due once the moment passes the watermark`() {
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T19:59"), millis("2026-06-10T20:00"))
assertThat(schedule.dueDay).isEqualTo(LocalDate.of(2026, 6, 11))
assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-11T20:00"))
}
@Test
fun `a second scan does not post again`() {
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T20:00"), millis("2026-06-10T20:05"))
assertThat(schedule.dueDay).isNull()
}
@Test
fun `a day already listed is not listed again`() {
// Posted at 20:00, then the time moved to 21:00 the same evening.
val schedule = scheduleDigest(
21 * 60, DigestDay.Tomorrow, zone, millis("2026-06-10T20:30"), millis("2026-06-10T21:00"),
lastListedDay = LocalDate.of(2026, 6, 11),
)
assertThat(schedule.dueDay).isNull()
}
@Test
fun `before the moment it only arms the alarm`() {
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T08:00"), millis("2026-06-10T09:00"))
assertThat(schedule.dueDay).isNull()
assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-10T20:00"))
}
@Test
fun `a late catch-up still lists a day that has not passed`() {
// Off overnight: last scan before 20:00, back on the next morning.
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T18:00"), millis("2026-06-11T07:00"))
assertThat(schedule.dueDay).isEqualTo(LocalDate.of(2026, 6, 11))
}
@Test
fun `a today summary missed until the next day is dropped`() {
val seven = 7 * 60
val schedule = scheduleDigest(seven, DigestDay.Today, zone, millis("2026-06-10T06:00"), millis("2026-06-11T06:30"))
assertThat(schedule.dueDay).isNull()
assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-11T07:00"))
}
@Test
fun `entries list all-day first, keep the day's own, and skip excluded calendars`() {
val day = LocalDate.of(2026, 6, 11)
val utcMidnight = day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
val allDay = instance(1, utcMidnight, utcMidnight + 24 * 60 * minute, isAllDay = true)
val previousAllDay = instance(2, utcMidnight - 24 * 60 * minute, utcMidnight, isAllDay = true)
val morning = instance(3, millis("2026-06-11T09:00"), millis("2026-06-11T10:00"))
val early = instance(4, millis("2026-06-11T07:00"), millis("2026-06-11T08:00"))
val nextDay = instance(5, millis("2026-06-12T00:00"), millis("2026-06-12T01:00"))
val excluded = instance(6, millis("2026-06-11T12:00"), millis("2026-06-11T13:00"), calendarId = 9)
val entries = digestEntries(
listOf(morning, previousAllDay, nextDay, early, allDay, excluded),
day,
zone,
excludedCalendarIds = setOf(9),
)
assertThat(entries.map { it.eventId }).containsExactly(1L, 4L, 3L).inOrder()
}
private fun instance(
eventId: Long,
begin: Long,
end: Long,
isAllDay: Boolean = false,
calendarId: Long = 1,
) = ReminderEventInstance(eventId, calendarId, begin, end, "Event $eventId", null, isAllDay)
}
@@ -0,0 +1,100 @@
package de.jeanlucmakiola.calendula.domain.reminders
import com.google.common.truth.Truth.assertThat
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import org.junit.jupiter.api.Test
import kotlin.time.Instant
class FixedTimeReminderTest {
private val berlin = TimeZone.of("Europe/Berlin")
private val eveningBefore = FixedTimeReminder(daysBefore = 1, minuteOfDay = 20 * 60)
private fun at(text: String, zone: TimeZone = berlin): Instant = LocalDateTime.parse(text).toInstant(zone)
@Test
fun `offset is the distance from the named wall clock to the start`() {
assertThat(eveningBefore.offsetMinutes(at("2026-06-10T10:00"), berlin)).isEqualTo(14 * 60)
assertThat(eveningBefore.offsetMinutes(at("2026-06-10T21:30"), berlin)).isEqualTo(25 * 60 + 30)
}
@Test
fun `offset spans a DST change in real minutes`() {
// Clocks go forward on 29 March 2026: 20:00 on the 28th to 10:00 on the 29th is 13 hours.
assertThat(eveningBefore.offsetMinutes(at("2026-03-29T10:00"), berlin)).isEqualTo(13 * 60)
}
@Test
fun `a series offset counts clock minutes, so a DST-side occurrence bakes in no hour`() {
// Opened on the Sunday clocks go back: the real span is 15 hours, the clock face says 14.
val start = at("2026-10-25T10:00")
assertThat(eveningBefore.offsetMinutes(start, berlin)).isEqualTo(15 * 60)
val offset = eveningBefore.offsetMinutes(start, berlin, wallClock = true)
assertThat(offset).isEqualTo(14 * 60)
// Read back the same way on any occurrence of the series.
assertThat(fixedTimeReminderAt(offset, at("2026-11-01T10:00"), berlin, wallClock = true)).isEqualTo(eveningBefore)
assertThat(fixedTimeReminderAt(offset, start, berlin, wallClock = true)).isEqualTo(eveningBefore)
}
@Test
fun `an offset reads back as the pattern it was written from`() {
val start = at("2026-03-29T10:00")
val offset = eveningBefore.offsetMinutes(start, berlin)
assertThat(fixedTimeReminderAt(offset, start, berlin)).isEqualTo(eveningBefore)
}
@Test
fun `a reminder on the start's own day or after it is no pattern`() {
val start = at("2026-06-10T10:00")
assertThat(fixedTimeReminderAt(60, start, berlin)).isNull()
assertThat(fixedTimeReminderAt(0, start, berlin)).isNull()
assertThat(fixedTimeReminderAt(-30, start, berlin)).isNull()
}
@Test
fun `only known patterns read as fixed-time`() {
val start = at("2026-06-10T10:00")
// 840 is "1 day before at 20:00" here, but also a plain "14 hours before".
val unknown = splitTimedReminders(listOf(10, 1_440, 840), start, berlin, known = emptySet())
assertThat(unknown.leadMinutes).containsExactly(10, 840, 1_440).inOrder()
assertThat(unknown.fixed).isEmpty()
val known = splitTimedReminders(listOf(10, 1_440, 840), start, berlin, known = setOf(eveningBefore))
assertThat(known.leadMinutes).containsExactly(10, 1_440).inOrder()
assertThat(known.fixed).containsExactly(eveningBefore)
}
@Test
fun `a whole-day offset landing on a known pattern is fixed-time`() {
// An event at 20:00 with "1 day before at 20:00" stores exactly a day.
val start = at("2026-06-10T20:00")
assertThat(splitTimedReminders(listOf(1_440), start, berlin, known = emptySet()).fixed).isEmpty()
val split = splitTimedReminders(listOf(1_440), start, berlin, known = setOf(eveningBefore))
assertThat(split.fixed).containsExactly(eveningBefore)
assertThat(split.leadMinutes).isEmpty()
}
@Test
fun `fixed reminders sort by when they fire`() {
val start = at("2026-06-10T10:00")
val twoDays = FixedTimeReminder(2, 9 * 60)
val split = splitTimedReminders(
listOf(eveningBefore.offsetMinutes(start, berlin), twoDays.offsetMinutes(start, berlin)),
start,
berlin,
known = setOf(eveningBefore, twoDays),
)
assertThat(split.fixed).containsExactly(twoDays, eveningBefore).inOrder()
}
@Test
fun `token round-trips and rejects garbage`() {
assertThat(FixedTimeReminder.parse(eveningBefore.toToken())).isEqualTo(eveningBefore)
assertThat(FixedTimeReminder.parse("0@600")).isNull()
assertThat(FixedTimeReminder.parse("1@1440")).isNull()
assertThat(FixedTimeReminder.parse("x")).isNull()
assertThat(FixedTimeReminder.parse(null)).isNull()
}
}
@@ -0,0 +1,38 @@
package de.jeanlucmakiola.calendula.domain.reminders
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class ReminderAlertStyleTest {
@Test
fun `styles round-trip through their stored form`() {
val styles = mapOf(9L to ReminderAlertStyle.FullScreenRing, 3L to ReminderAlertStyle.FullScreen)
assertThat(parseAlertStyles(styles.toStoredAlertStyles())).isEqualTo(styles)
}
@Test
fun `plain notifications are not stored`() {
val stored = mapOf(1L to ReminderAlertStyle.Notification, 2L to ReminderAlertStyle.FullScreen).toStoredAlertStyles()
assertThat(stored).isEqualTo("2=full_screen")
}
@Test
fun `garbled entries are dropped, the rest survive`() {
assertThat(parseAlertStyles("x=full_screen;4=loud;5;6=full_screen_ring"))
.containsExactly(6L, ReminderAlertStyle.FullScreenRing)
assertThat(parseAlertStyles(null)).isEmpty()
}
@Test
fun `a calendar without a style uses notifications`() {
val styles = mapOf(1L to ReminderAlertStyle.FullScreen)
assertThat(styles.alertStyleFor(1L)).isEqualTo(ReminderAlertStyle.FullScreen)
assertThat(styles.alertStyleFor(2L)).isEqualTo(ReminderAlertStyle.Notification)
assertThat(ReminderAlertStyle.Notification.isFullScreen).isFalse()
assertThat(ReminderAlertStyle.FullScreenRing.isFullScreen).isTrue()
}
}
@@ -0,0 +1,51 @@
package de.jeanlucmakiola.calendula.domain.reminders
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class ReminderMapQueryTest {
@Test
fun `an address is looked up as written`() {
assertThat(reminderMapQuery(" Main St 1, Berlin ")).isEqualTo("Main St 1, Berlin")
}
@Test
fun `no location means no lookup`() {
assertThat(reminderMapQuery(null)).isNull()
assertThat(reminderMapQuery(" ")).isNull()
}
@Test
fun `a bare meeting link is not a place`() {
assertThat(reminderMapQuery("https://meet.google.com/abc-defg-hij")).isNull()
assertThat(reminderMapQuery("HTTP://example.com")).isNull()
assertThat(reminderMapQuery("<https://teams.microsoft.com/l/meetup-join/x>")).isNull()
assertThat(reminderMapQuery("https://a.example\nhttps://b.example")).isNull()
}
@Test
fun `dotted place names are still places`() {
assertThat(reminderMapQuery("Hauptstr. 12/3, Wien")).isEqualTo("Hauptstr. 12/3, Wien")
assertThat(reminderMapQuery("St.Gallen/Zentrum")).isEqualTo("St.Gallen/Zentrum")
}
@Test
fun `a place with a link beside it is still looked up`() {
assertThat(reminderMapQuery("Room 4, https://example.com/map")).isEqualTo("Room 4, https://example.com/map")
}
@Test
fun `the first web link is the reminder's link`() {
assertThat(reminderLink("https://meet.google.com/abc-defg-hij")).isEqualTo("https://meet.google.com/abc-defg-hij")
assertThat(reminderLink("<https://teams.microsoft.com/l/meetup-join/x>")).isEqualTo("https://teams.microsoft.com/l/meetup-join/x")
assertThat(reminderLink("Room 4, https://example.com/map.")).isEqualTo("https://example.com/map")
assertThat(reminderLink("https://a.example\nhttps://b.example")).isEqualTo("https://a.example")
}
@Test
fun `no link without one`() {
assertThat(reminderLink(null)).isNull()
assertThat(reminderLink("Hauptstr. 12/3, Wien")).isNull()
}
}
@@ -0,0 +1,48 @@
package de.jeanlucmakiola.calendula.ui
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import org.junit.jupiter.api.Test
class WidgetNavRequestTest {
private val detail = LeaveTarget.Detail(1, 2, 3)
@Test
fun `a widget's day or event is what back leaves from`() {
assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = true).leaveTarget).isEqualTo(LeaveTarget.View)
assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = false).leaveTarget).isNull()
assertThat(WidgetNavRequest.OpenEvent(1, 2, 3, CalendarView.Agenda).leaveTarget).isEqualTo(detail)
assertThat(WidgetNavRequest.OpenEvent(1, 2, 3, CalendarView.Day).leaveTarget).isEqualTo(detail)
assertThat(WidgetNavRequest.OpenView(CalendarView.Month).leaveTarget).isNull()
assertThat(WidgetNavRequest.Create(null).leaveTarget).isNull()
}
@Test
fun `the target stays only while the views stay put`() {
val day = listOf(CalendarView.Week, CalendarView.Day)
assertThat(LeaveTarget.View.afterMove(day, day.toList())).isEqualTo(LeaveTarget.View)
assertThat(LeaveTarget.View.afterMove(day, listOf(CalendarView.Week))).isNull()
assertThat(detail.afterMove(day, day + CalendarView.Month)).isNull()
assertThat(null.afterMove(day, day)).isNull()
}
@Test
fun `a widget's detail is dropped once it closes or another opens`() {
assertThat(detail.afterDetail(longArrayOf(1, 2, 3))).isEqualTo(detail)
assertThat(detail.afterDetail(null)).isNull()
assertThat(detail.afterDetail(longArrayOf(4, 5, 6))).isNull()
// A widget's day keeps its target under an in-app detail.
assertThat(LeaveTarget.View.afterDetail(longArrayOf(4, 5, 6))).isEqualTo(LeaveTarget.View)
}
@Test
fun `back leaves only from the widget's own day or detail`() {
assertThat(LeaveTarget.View.leaves(detail = null, overlayVisible = false)).isTrue()
assertThat(LeaveTarget.View.leaves(detail = longArrayOf(4, 5, 6), overlayVisible = true)).isFalse()
assertThat(detail.leaves(detail = longArrayOf(1, 2, 3), overlayVisible = true)).isTrue()
assertThat(detail.leaves(detail = longArrayOf(4, 5, 6), overlayVisible = true)).isFalse()
assertThat(detail.leaves(detail = null, overlayVisible = false)).isFalse()
assertThat(null.leaves(detail = null, overlayVisible = false)).isFalse()
}
}
@@ -45,10 +45,10 @@ class BackupUiStateTest {
}
@Test
fun `a synced writable calendar can receive a restore`() {
fun `a synced writable calendar can receive a restore and be backed up`() {
val state = ready(backupUiState(listOf(cal(1L))))
assertThat(state.canImport).isTrue()
assertThat(state.exportable).isEmpty()
assertThat(state.exportable.map { it.id }).containsExactly(1L)
}
@Test
@@ -62,16 +62,18 @@ class BackupUiStateTest {
}
@Test
fun `a read-only subscription is no import target either`() {
assertThat(failure(backupUiState(listOf(cal(1L, writable = false)))))
.isEqualTo(FailureReason.NoImportTarget)
fun `a read-only subscription is no import target but can be backed up`() {
// #147: export only reads, so a subscription is fair game.
val state = ready(backupUiState(listOf(cal(1L, writable = false))))
assertThat(state.canImport).isFalse()
assertThat(state.exportable).hasSize(1)
}
@Test
fun `everything switched off is reported as hidden, not as a missing target`() {
// The remedy differs: a visibility switch fixes this one.
assertThat(failure(backupUiState(listOf(cal(1L, visible = false)))))
.isEqualTo(FailureReason.AllCalendarsHidden)
fun `a switched-off synced calendar still backs up`() {
val state = ready(backupUiState(listOf(cal(1L, visible = false))))
assertThat(state.canImport).isFalse()
assertThat(state.exportable).hasSize(1)
}
@Test
@@ -92,7 +94,51 @@ class BackupUiStateTest {
@Test
fun `a local calendar alongside a synced one offers both halves`() {
val state = ready(backupUiState(listOf(cal(1L, local = true), cal(2L))))
assertThat(state.exportable.map { it.id }).containsExactly(1L)
assertThat(state.exportable.map { it.id }).containsExactly(1L, 2L)
assertThat(state.canImport).isTrue()
}
@Test
fun `a read-only calendar can be copied into a writable one`() {
val readOnly = cal(1, writable = false)
val local = cal(2, local = true)
val state = ready(backupUiState(listOf(readOnly, local)))
assertThat(state.canCopy).isTrue()
assertThat(copySources(listOf(readOnly, local)).map { it.id }).containsExactly(1L)
assertThat(copyTargets(listOf(readOnly, local), 1L).map { it.id }).containsExactly(2L)
}
@Test
fun `a single writable calendar has nothing to copy into`() {
val only = cal(1, local = true)
assertThat(ready(backupUiState(listOf(only))).canCopy).isFalse()
assertThat(copyTargets(listOf(only), 1L)).isEmpty()
}
@Test
fun `the only writable calendar is not offered as a source`() {
val local = cal(1, local = true)
val holidays = cal(2, writable = false)
assertThat(copySources(listOf(local, holidays)).map { it.id }).containsExactly(2L)
}
@Test
fun `a copy never targets a managed or switched-off calendar`() {
val source = cal(1)
val calendars = listOf(source, cal(2, managed = true), cal(3, visible = false))
assertThat(copyTargets(calendars, source.id)).isEmpty()
}
@Test
fun `choosing the target as source drops it`() {
assertThat(CopySelection(sourceId = 1, targetId = 2).withSource(2))
.isEqualTo(CopySelection(sourceId = 2, targetId = null))
assertThat(CopySelection(sourceId = 1, targetId = 2).withSource(3))
.isEqualTo(CopySelection(sourceId = 3, targetId = 2))
}
}
@@ -0,0 +1,67 @@
package de.jeanlucmakiola.calendula.ui.common
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.floret.reminders.ReminderUnit
import org.junit.jupiter.api.Test
class ReminderPresetsTest {
@Test
fun `presets are sorted and unique`() {
for (presets in listOf(REMINDER_PRESETS, ALLDAY_REMINDER_PRESETS)) {
assertThat(presets).isInStrictOrder()
}
}
@Test
fun `all-day presets are whole days`() {
assertThat(ALLDAY_REMINDER_PRESETS.all { it % 1_440 == 0 }).isTrue()
}
@Test
fun `offers two to five days and two and three weeks`() {
val extra = listOf(2_880, 4_320, 5_760, 7_200, 20_160, 30_240)
assertThat(REMINDER_PRESETS).containsAtLeastElementsIn(extra)
assertThat(ALLDAY_REMINDER_PRESETS).containsAtLeastElementsIn(extra)
}
@Test
fun `groups split sub-day from day-scale lead times, sorted`() {
assertThat(groupReminderLeadTimes(listOf(2_880, 10, 0, 1_440, 45), splitSubDay = true))
.containsExactly(listOf(0, 10, 45), listOf(1_440, 2_880)).inOrder()
}
@Test
fun `all-day custom offers whole-day units only`() {
assertThat(customReminderUnits(isAllDay = true))
.containsExactly(ReminderUnit.Days, ReminderUnit.Weeks).inOrder()
assertThat(customReminderUnits(isAllDay = false)).containsExactlyElementsIn(ReminderUnit.entries)
}
@Test
fun `custom placeholder fits the selected unit`() {
assertThat(customReminderPlaceholder(ReminderUnit.Minutes)).isEqualTo("10")
assertThat(customReminderPlaceholder(ReminderUnit.Days)).isEqualTo("1")
}
@Test
fun `only the timed list splits`() {
assertThat(splitsSubDay(REMINDER_PRESETS)).isTrue()
assertThat(splitsSubDay(ALLDAY_REMINDER_PRESETS)).isFalse()
}
@Test
fun `unsplit list is one sorted group`() {
assertThat(groupReminderLeadTimes(listOf(2_880, 0, 30), splitSubDay = false))
.containsExactly(listOf(0, 30, 2_880))
}
@Test
fun `empty groups are dropped`() {
assertThat(groupReminderLeadTimes(listOf(0, 1_440), splitSubDay = true))
.containsExactly(listOf(0), listOf(1_440)).inOrder()
assertThat(groupReminderLeadTimes(listOf(2_880), splitSubDay = true)).containsExactly(listOf(2_880))
assertThat(groupReminderLeadTimes(emptyList(), splitSubDay = true)).isEmpty()
assertThat(groupReminderLeadTimes(emptyList(), splitSubDay = false)).isEmpty()
}
}
@@ -92,12 +92,13 @@ class RescheduleViewModelTest {
io: CoroutineDispatcher = dispatcher,
): RescheduleViewModel {
fake.occurrencesAt(present)
val settings = testSettings(tempDir, CoroutineScope(dispatcher))
val repo = testRepository(
fake, tempDir, io,
prefs = testPrefs(tempDir, CoroutineScope(dispatcher)),
settings = testSettings(tempDir, CoroutineScope(dispatcher)),
settings = settings,
)
return RescheduleViewModel(repo, io, FakeZoneSource())
return RescheduleViewModel(repo, io, FakeZoneSource(), settings)
}
private fun slowViewModel(tempDir: Path, fake: FakeCalendarDataSource): RescheduleViewModel =
@@ -0,0 +1,209 @@
package de.jeanlucmakiola.calendula.ui.common
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.MainDispatcherExtension
import de.jeanlucmakiola.calendula.RecordingSyncRequester
import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.calendar.SyncActivity
import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult
import de.jeanlucmakiola.calendula.data.calendar.SyncTargets
import kotlinx.coroutines.launch
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.testPrefs
import de.jeanlucmakiola.calendula.testRepository
import de.jeanlucmakiola.calendula.testSettings
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
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
@OptIn(ExperimentalCoroutinesApi::class)
class SyncViewModelTest {
@JvmField @RegisterExtension
val mainDispatcher = MainDispatcherExtension(StandardTestDispatcher())
private val dispatcher = mainDispatcher.dispatcher
private val synced = CalendarSource(1L, "Work", "me@dav", "bitfire.at.davdroid", 0, true)
private val davAccount = SyncAccount("me@dav", "bitfire.at.davdroid")
private fun viewModel(dir: Path, sync: RecordingSyncRequester = RecordingSyncRequester()):
Pair<SyncViewModel, FakeCalendarDataSource> {
val source = FakeCalendarDataSource().apply { calendarsResult = listOf(synced) }
val repo = testRepository(
source, dir, dispatcher,
prefs = testPrefs(dir, CoroutineScope(dispatcher)),
settings = testSettings(dir, CoroutineScope(dispatcher)),
syncRequester = sync,
)
return SyncViewModel(repo) to source
}
@Test
fun `completed once the reached account has synced`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester()
var state = SyncActivity.Pending
sync.activity = { state }
val (vm, _) = viewModel(dir, sync)
vm.requestSync()
runCurrent()
assertThat(vm.inFlight.value).isTrue()
assertThat(vm.result.value).isNull()
state = SyncActivity.Active
sync.activityChanges.tryEmit(Unit)
runCurrent()
assertThat(vm.inFlight.value).isTrue()
state = SyncActivity.Idle
sync.activityChanges.tryEmit(Unit)
runCurrent()
assertThat(vm.inFlight.value).isFalse()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed)
}
@Test
fun `a sync already running when asked has to finish and the asked one run`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester()
var state = SyncActivity.Active
sync.activity = { state }
val (vm, _) = viewModel(dir, sync)
vm.requestSync()
runCurrent()
state = SyncActivity.Pending
sync.activityChanges.tryEmit(Unit)
runCurrent()
assertThat(vm.inFlight.value).isTrue()
state = SyncActivity.Idle
sync.activityChanges.tryEmit(Unit)
runCurrent()
assertThat(vm.inFlight.value).isFalse()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed)
}
@Test
fun `a sync that never shows up counts as done after the grace`(@TempDir dir: Path) = runTest(dispatcher) {
val (vm, _) = viewModel(dir)
vm.requestSync()
advanceTimeBy(4_000L)
assertThat(vm.inFlight.value).isTrue()
advanceTimeBy(1_500L)
assertThat(vm.inFlight.value).isFalse()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed)
}
@Test
fun `a sync still running after a minute stays unconfirmed`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester().apply { activity = { SyncActivity.Active } }
val (vm, _) = viewModel(dir, sync)
vm.requestSync()
advanceTimeBy(59_000L)
assertThat(vm.inFlight.value).isTrue()
advanceTimeBy(1_500L)
assertThat(vm.inFlight.value).isFalse()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested)
}
@Test
fun `unreadable sync state says requested at once`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester().apply { activity = { null } }
val (vm, _) = viewModel(dir, sync)
vm.requestSync()
runCurrent()
assertThat(vm.inFlight.value).isFalse()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested)
}
@Test
fun `a tap while in flight asks only once`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester()
val (vm, _) = viewModel(dir, sync)
vm.requestSync()
runCurrent()
vm.requestSync()
runCurrent()
assertThat(sync.requests).hasSize(1)
}
@Test
fun `a refused request stops at once and says so`(@TempDir dir: Path) = runTest(dispatcher) {
val (vm, _) = viewModel(dir, RecordingSyncRequester(accepts = false))
vm.requestSync()
runCurrent()
assertThat(vm.inFlight.value).isFalse()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Failed)
vm.consumeResult()
assertThat(vm.result.value).isNull()
}
@Test
fun `refreshAccess picks up a grant`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester(hiddenTypes = setOf(davAccount.type))
sync.knownAccounts = setOf(davAccount)
val (vm, _) = viewModel(dir, sync)
backgroundScope.launch { vm.targets.collect {} }
runCurrent()
assertThat(vm.targets.value).isEqualTo(SyncTargets(emptySet(), setOf(davAccount)))
sync.hiddenTypes = setOf("other")
vm.refreshAccess()
runCurrent()
assertThat(vm.targets.value).isEqualTo(SyncTargets(setOf(davAccount), emptySet()))
}
@Test
fun `dismissing a hidden account takes it out of the grant list`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester(hiddenTypes = setOf(davAccount.type))
sync.knownAccounts = setOf(davAccount)
val (vm, _) = viewModel(dir, sync)
backgroundScope.launch { vm.targets.collect {} }
runCurrent()
assertThat(vm.targets.value?.needsAccess).containsExactly(davAccount)
vm.dismissAccess(davAccount)
runCurrent()
assertThat(vm.targets.value).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(davAccount)))
}
@Test
fun `a failed read of the targets is retried rather than hiding Sync now for good`(@TempDir dir: Path) =
runTest(dispatcher) {
val (vm, source) = viewModel(dir)
source.calendarsError = IllegalStateException("provider gone")
backgroundScope.launch { vm.targets.collect {} }
runCurrent()
assertThat(vm.targets.value?.reachable.orEmpty()).isEmpty()
source.calendarsError = null
advanceTimeBy(31_000)
runCurrent()
assertThat(vm.targets.value?.reachable).containsExactly(davAccount)
}
}
@@ -6,8 +6,8 @@ import org.junit.jupiter.api.Test
/**
* The pure back-stack rules behind [CalendarHost]'s top-level navigation:
* the home view is always the bottom, a lateral move keeps the stack one deep,
* and a date tap drills the day view on top. Verifies the back sequences the
* widget-UX fix promises (e.g. agenda widget → day → back → agenda → back → home).
* and a date tap drills the day view on top. Verifies the back sequences, e.g.
* agenda → day → back → agenda → back → home.
*/
class ViewBackStackTest {
@@ -74,8 +74,8 @@ class ViewBackStackTest {
}
@Test
fun `agenda widget date tap backs out agenda then home`() {
// openDate(source = Agenda): root in Agenda over the Week home, then drill.
fun `a day tapped in a widget event's view backs out to it, then home`() {
// Agenda widget event tap roots [Week, Agenda]; a day tapped there drills on top.
val stack = viewBaseStack(CalendarView.Week, CalendarView.Agenda).drillToDay()
assertThat(stack)
.containsExactly(CalendarView.Week, CalendarView.Agenda, CalendarView.Day)
@@ -86,11 +86,11 @@ class ViewBackStackTest {
}
@Test
fun `month widget date tap backs out month then home`() {
val stack = viewBaseStack(CalendarView.Week, CalendarView.Month).drillToDay()
assertThat(stack.last()).isEqualTo(CalendarView.Day)
assertThat(stack.dropLast(1).last()).isEqualTo(CalendarView.Month)
assertThat(stack.first()).isEqualTo(CalendarView.Week)
fun `a date launch drills the day over the home view only`() {
assertThat(listOf(CalendarView.Week).drillToDay())
.containsExactly(CalendarView.Week, CalendarView.Day)
.inOrder()
assertThat(listOf(CalendarView.Day).drillToDay()).containsExactly(CalendarView.Day)
}
@Test
@@ -0,0 +1,100 @@
package de.jeanlucmakiola.calendula.ui.common
import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.testEvent
import de.jeanlucmakiola.calendula.testRepository
import de.jeanlucmakiola.calendula.testSettings
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.time.Instant
@OptIn(ExperimentalCoroutinesApi::class)
class ViewHiddenCalendarsTest {
private val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000_000_000L)
private fun event(id: Long, calendarId: Long) = testEvent(
id = id,
calendarId = calendarId,
title = "E $id",
start = Instant.fromEpochMilliseconds(1_000_000_000L),
end = Instant.fromEpochMilliseconds(1_000_003_600L),
color = 0,
)
private fun calendar(id: Long) = CalendarSource(id, "Cal $id", "x@y", "LOCAL", 0, true)
@Test
fun `calendarsHiddenIn picks only the calendars hidden in that view`() {
val map = mapOf(
1L to setOf(CalendarView.Month),
2L to setOf(CalendarView.Month, CalendarView.Agenda),
3L to setOf(CalendarView.Week),
)
assertThat(map.calendarsHiddenIn(CalendarView.Month)).containsExactly(1L, 2L)
assertThat(map.calendarsHiddenIn(CalendarView.Agenda)).containsExactly(2L)
assertThat(map.calendarsHiddenIn(CalendarView.Day)).isEmpty()
}
@Test
fun `instancesWithout drops a calendar only in the views it is hidden in`(@TempDir tempDir: Path) = runTest {
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(calendar(1L), calendar(2L))
instancesResult = { _, _ -> listOf(event(10L, 1L), event(20L, 2L)) }
}
val settings = testSettings(tempDir)
val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), settings = settings)
settings.applyCalendarHiddenChanges(2L, listOf(CalendarView.Month).associateWith { true })
val hidden = settings.perCalendarHiddenViews
assertThat(repo.instancesWithout(range, hidden.calendarsHiddenIn(CalendarView.Month, backgroundScope)).first().map { it.eventId })
.containsExactly(10L)
assertThat(repo.instancesWithout(range, hidden.calendarsHiddenIn(CalendarView.Week, backgroundScope)).first().map { it.eventId })
.containsExactly(10L, 20L)
// The repository itself, which reminders and search build on, is untouched.
assertThat(repo.instances(range).first().map { it.eventId }).containsExactly(10L, 20L)
}
@Test
fun `instancesWithout re-filters live when the setting changes`(@TempDir tempDir: Path) = runTest {
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(calendar(1L), calendar(2L))
instancesResult = { _, _ -> listOf(event(10L, 1L), event(20L, 2L)) }
}
val settings = testSettings(tempDir)
val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), settings = settings)
val hidden = settings.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Agenda, backgroundScope)
repo.instancesWithout(range, hidden).test {
assertThat(awaitItem().map { it.eventId }).containsExactly(10L, 20L)
settings.setCalendarHiddenIn(1L, CalendarView.Agenda, hidden = true)
assertThat(awaitItem().map { it.eventId }).containsExactly(20L)
settings.setCalendarHiddenIn(1L, CalendarView.Agenda, hidden = false)
assertThat(awaitItem().map { it.eventId }).containsExactly(10L, 20L)
cancelAndIgnoreRemainingEvents()
}
}
@Test
fun `a failed read hides nothing and keeps reading`() = runTest {
var reads = 0
val source = kotlinx.coroutines.flow.flow {
reads++
if (reads == 1) throw java.io.IOException("disk")
emit(mapOf(1L to setOf(CalendarView.Month)))
}
source.hidingNothingOnError().test {
assertThat(awaitItem()).isEmpty()
assertThat(awaitItem()).containsExactly(1L, setOf(CalendarView.Month))
awaitComplete()
}
}
}
@@ -51,13 +51,14 @@ class EventDetailViewModelTest {
)
private fun viewModel(tempDir: Path, fake: FakeCalendarDataSource): EventDetailViewModel {
val settings = testSettings(tempDir, CoroutineScope(dispatcher))
val repo = testRepository(
fake, tempDir, dispatcher,
prefs = testPrefs(tempDir, CoroutineScope(dispatcher)),
settings = testSettings(tempDir, CoroutineScope(dispatcher)),
settings = settings,
)
// Only `shareUri()` touches the exporter, and nothing here shares.
return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource())
return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource(), settings)
}
private fun fakeSource(description: () -> String?) = FakeCalendarDataSource().apply {
@@ -9,7 +9,12 @@ import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.time.FakeZoneSource
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.Reminder
import de.jeanlucmakiola.calendula.domain.ReminderMethod
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
@@ -21,6 +26,7 @@ import de.jeanlucmakiola.calendula.testEvent
import de.jeanlucmakiola.calendula.testPrefs
import de.jeanlucmakiola.calendula.testRepository
import de.jeanlucmakiola.calendula.testSettings
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -305,6 +311,31 @@ class EventEditViewModelTest {
end = FormTime(end),
)
@Test
fun `switching to all-day keeps sub-day reminders, removing one drops its whole day`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) }
val vm = viewModel(tempDir, fake)
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 9 * 60)
advanceUntilIdle()
vm.addReminder(10)
vm.addReminder(1_440)
vm.setAllDay(true)
vm.setAllDay(false)
advanceUntilIdle()
// Toggling all-day is lossless.
assertThat(vm.state.value?.form?.reminders).containsExactly(10, 1_440).inOrder()
vm.addReminder(0)
vm.setAllDay(true)
vm.removeReminder(0)
assertThat(vm.state.value?.form?.reminders).containsExactly(1_440)
job.cancel()
}
@Test
fun `an all-day event ignores the default duration`(
@TempDir tempDir: Path,
@@ -719,4 +750,267 @@ class EventEditViewModelTest {
assertThat(vm.state.value?.saveState).isEqualTo(SaveUiState.Idle)
job.cancel()
}
@Test
fun `a new timed event gets the fixed-time default, and a calendar can turn it off`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val s = settings(tempDir)
val evening = FixedTimeReminder(1, 1_200)
s.setDefaultFixedTimeReminder(evening)
s.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.Off)
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 600)
advanceUntilIdle()
assertThat(vm.state.value!!.form!!.fixedReminders).containsExactly(evening)
vm.setCalendar(2L)
advanceUntilIdle()
assertThat(vm.state.value!!.form!!.fixedReminders).isEmpty()
job.cancel()
}
@Test
fun `an event's set-time reminder opens as one and saves without a conflict`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val zone = FakeZoneSource().current()
val start = Instant.fromEpochMilliseconds(beginMillis)
val evening = FixedTimeReminder(1, 1_200)
val offset = evening.offsetMinutes(start, zone)
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(cal(1L))
eventDetailResult = {
detail(calendarId = 1L).copy(reminders = listOf(Reminder(offset, ReminderMethod.Alert)))
}
}
val s = settings(tempDir)
s.setDefaultFixedTimeReminder(evening)
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openForEdit(eventId = 42L, beginMillis = beginMillis, endMillis = endMillis)
advanceUntilIdle()
val form = vm.state.value!!.form!!
assertThat(form.fixedReminders).containsExactly(evening)
assertThat(form.reminders).isEmpty()
assertThat(vm.hasUnsavedChanges.value).isFalse()
vm.setTitle("Renamed")
vm.save()
advanceUntilIdle()
assertThat(vm.state.value?.saveState).isEqualTo(SaveUiState.Saved)
assertThat(fake.updatedEvents.single().third.fixedReminders).containsExactly(evening)
job.cancel()
}
@Test
fun `a new event opens in the default calendar with its reminders`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
s.setCalendarReminderOverride(2L, ReminderOverride.Minutes(listOf(5)))
val p = prefs(tempDir)
p.setLastUsedCalendarId(1L)
val repo = testRepository(fake, tempDir, dispatcher, p, s)
val vm = EventEditViewModel(repo, p, s, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource())
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 9 * 60)
advanceUntilIdle()
assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L)
assertThat(vm.state.value?.form?.reminders).containsExactly(5)
job.cancel()
}
@Test
fun `a switched-off default calendar falls back to the first target`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L, visible = false)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15))
advanceUntilIdle()
assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L)
job.cancel()
}
@Test
fun `an insert naming a calendar wins over the default`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L), cal(3L)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openImported(
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 3L),
ImportSource.Insert,
)
advanceUntilIdle()
assertThat(vm.state.value?.form?.calendarId).isEqualTo(3L)
assertThat(vm.hasUnsavedChanges.value).isFalse()
job.cancel()
}
@Test
fun `an insert naming an unknown calendar falls back to the default`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openImported(
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 77L),
ImportSource.Insert,
)
advanceUntilIdle()
assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L)
job.cancel()
}
@Test
fun `a duplicate in its own calendar keeps its colour`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val vm = viewModel(tempDir, fake)
val job = activate(vm)
vm.openImported(
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7),
ImportSource.Insert,
)
advanceUntilIdle()
assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L)
assertThat(vm.state.value?.form?.colorKey).isEqualTo("3")
job.cancel()
}
@Test
fun `re-picking the shown calendar is no change`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val vm = viewModel(tempDir, fake)
val job = activate(vm)
vm.openImported(
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7),
ImportSource.Insert,
)
advanceUntilIdle()
vm.setCalendar(2L)
advanceUntilIdle()
assertThat(vm.state.value?.form?.colorKey).isEqualTo("3")
assertThat(vm.hasUnsavedChanges.value).isFalse()
job.cancel()
}
@Test
fun `a round trip through all-day keeps set-time reminders`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) }
val s = settings(tempDir)
s.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 600)
advanceUntilIdle()
vm.addFixedReminder(FixedTimeReminder(2, 480))
vm.setAllDay(true)
vm.setAllDay(false)
advanceUntilIdle()
assertThat(vm.state.value!!.form!!.fixedReminders)
.containsExactly(FixedTimeReminder(2, 480), FixedTimeReminder(1, 1_200))
job.cancel()
}
@Test
fun `a set-time reminder replaces a lead firing at the same moment`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) }
val s = settings(tempDir)
s.setDefaultReminderMinutes(listOf(1_440, 10))
val vm = viewModel(tempDir, fake, s, zones = FakeZoneSource(berlin))
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 20 * 60)
advanceUntilIdle()
vm.addFixedReminder(FixedTimeReminder(1, 20 * 60))
val form = vm.state.value!!.form!!
assertThat(form.reminders).containsExactly(10)
assertThat(form.fixedReminders).containsExactly(FixedTimeReminder(1, 20 * 60))
job.cancel()
}
@Test
fun `a copy carrying only set-time reminders keeps them`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) }
val s = settings(tempDir)
s.setDefaultReminderMinutes(listOf(15))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
val copy = importedForm(end = LocalDateTime(2030, 1, 15, 10, 0))
.copy(reminders = emptyList(), fixedReminders = listOf(FixedTimeReminder(1, 1_200)))
vm.openImported(copy, ImportSource.Insert)
advanceUntilIdle()
val form = vm.state.value!!.form!!
assertThat(form.fixedReminders).containsExactly(FixedTimeReminder(1, 1_200))
assertThat(form.reminders).isEmpty()
job.cancel()
}
@Test
fun `a duplicate that can't stay in its calendar drops its colour`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L, visible = false)) }
val vm = viewModel(tempDir, fake)
val job = activate(vm)
vm.openImported(
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7),
ImportSource.Insert,
)
advanceUntilIdle()
assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L)
assertThat(vm.state.value?.form?.colorKey).isNull()
assertThat(vm.state.value?.form?.color).isNull()
vm.setColorRaw(9)
advanceUntilIdle()
assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L)
assertThat(vm.state.value?.form?.color).isEqualTo(9)
job.cancel()
}
}
@@ -0,0 +1,31 @@
package de.jeanlucmakiola.calendula.ui.filter
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
import org.junit.jupiter.api.Test
class FilterUiStateTest {
private fun calendar(id: Long) = CalendarSource(id, "Cal $id", "x@y", "LOCAL", 0, true)
@Test
fun `hiddenOnlyIn lists the calendars the view hides on its own`() {
val state = FilterUiState.Success(
groups = listOf(calendar(1L), calendar(2L), calendar(3L)).groupByAccount(),
// 3 is hidden everywhere from the drawer already.
hidden = setOf(3L),
hiddenViews = mapOf(
1L to setOf(CalendarView.Month),
2L to setOf(CalendarView.Month, CalendarView.Week),
3L to setOf(CalendarView.Month),
// Not listed (switched off device-wide).
9L to setOf(CalendarView.Month),
),
)
assertThat(state.hiddenOnlyIn(CalendarView.Month)).containsExactly(1L, 2L)
assertThat(state.hiddenOnlyIn(CalendarView.Week)).containsExactly(2L)
assertThat(state.hiddenOnlyIn(CalendarView.Agenda)).isEmpty()
}
}
@@ -0,0 +1,49 @@
package de.jeanlucmakiola.calendula.ui.filter
import androidx.compose.ui.state.ToggleableState
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class GroupVisibilityTest {
private val group = listOf(1L, 2L, 3L)
@Test
fun `all shown is on and hides on tap`() {
val state = groupVisibility(group, hidden = setOf(9L))
assertThat(state).isEqualTo(ToggleableState.On)
assertThat(state.nextGroupVisible()).isFalse()
}
@Test
fun `none shown is off and shows on tap`() {
val state = groupVisibility(group, hidden = setOf(1L, 2L, 3L))
assertThat(state).isEqualTo(ToggleableState.Off)
assertThat(state.nextGroupVisible()).isTrue()
}
@Test
fun `some shown is indeterminate and shows all on tap`() {
val state = groupVisibility(group, hidden = setOf(2L))
assertThat(state).isEqualTo(ToggleableState.Indeterminate)
assertThat(state.nextGroupVisible()).isTrue()
}
@Test
fun `empty group is off`() {
assertThat(groupVisibility(emptyList(), hidden = emptySet())).isEqualTo(ToggleableState.Off)
}
@Test
fun `toggling twice from the stored set alternates`() {
val hidden = setOf(9L)
val once = toggledGroup(hidden, group)
assertThat(once).isEqualTo(setOf(1L, 2L, 3L, 9L))
assertThat(toggledGroup(once, group)).isEqualTo(setOf(9L))
}
@Test
fun `toggling a partly shown group shows all`() {
assertThat(toggledGroup(setOf(2L, 9L), group)).isEqualTo(setOf(9L))
}
}