Release 1.1.0 (#51)
Renovate / renovate (push) Successful in 54s
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 6s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 21m44s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m32s
Renovate / renovate (push) Successful in 54s
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 6s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 21m44s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m32s
Agendula 1.1.0. Merging this triggers the release pipeline (F-Droid, Codeberg, Play) and mints the v1.1.0 tag. - Tags, synced as CATEGORIES (#35) - Saved filters, also usable in the Tasks widget (#47) - Offline flavor without sync or network, published to Codeberg only (#39) - New Today, Up next, Lists and Week widgets; widgets can show several lists - Synced lists can be renamed and deleted - All-day tasks no longer land a day off west of UTC in smart lists and filters versionName 1.1.0 / versionCode 1010099. CHANGELOG has the 1.1.0 section, and What's New is written for en-US, en-GB, de-DE, pt-BR, plus new fr-FR and ar. After the tag lands, fdroiddata!49998 needs a 1.1.0 build entry with gradle: full. Closes #35, closes #39, closes #47 Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de> Reviewed-on: https://codeberg.org/jlmakiola/agendula/pulls/51
This commit is contained in:
1 parent
b6f0391cb3
commit
dd08c035df
219 files changed
+7010
-1227
No files matched your search
@@ -0,0 +1,92 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class SavedFilterCodecTest {
|
||||
|
||||
private val filter = SavedFilter(
|
||||
id = 3,
|
||||
name = "Work | today, 100%",
|
||||
due = setOf(DueWindow.TODAY, DueWindow.OVERDUE),
|
||||
listIds = setOf(4L, 9L),
|
||||
tags = setOf("a,b", "größe", "x|y"),
|
||||
tagMatch = TagMatch.ALL,
|
||||
minPriority = Priority.MEDIUM,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `a filter round-trips, separators and all`() {
|
||||
val raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(filter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `upsert replaces by id and keeps the order`() {
|
||||
val first = filter.copy(id = 1, name = "one")
|
||||
var raw = SavedFilterCodec.upsert(null, first, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, first.copy(name = "renamed"), "OWN")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").map { it.name }).containsExactly("renamed", filter.name).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `list ids belong to their store`() {
|
||||
val raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
assertThat(elsewhere.listIds).isEmpty()
|
||||
assertThat(elsewhere.listsElsewhere).isTrue()
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listsElsewhere).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `choosing any list in one store drops the other store's lists`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = emptySet(), listsElsewhere = false), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().anyList).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unticking the last list here keeps the other store's lists`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = setOf(1L)), "EXTERNAL")
|
||||
val external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
assertThat(external.listsElsewhere).isTrue()
|
||||
raw = SavedFilterCodec.upsert(raw, external.copy(listIds = emptySet()), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
|
||||
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().anyList).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `saving untouched in the other store keeps the lists`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
raw = SavedFilterCodec.upsert(raw, elsewhere.copy(name = "renamed"), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `editing in one store keeps the other store's lists`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = setOf(1L)), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
|
||||
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().listIds).containsExactly(1L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `remove drops only that filter`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter.copy(id = 1), "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter, "OWN")
|
||||
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 1), "OWN").map { it.id }).containsExactly(3L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `broken lines are skipped`() {
|
||||
val raw = "nonsense\n" + SavedFilterCodec.upsert(null, filter, "OWN") + "\n7|short\n8|bad%zz||||ANY|NONE"
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(filter)
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import java.io.File
|
||||
|
||||
/** The sign-in prompt is posted once per stop, not on every refused run. */
|
||||
class AccountStateStoreTest {
|
||||
|
||||
@TempDir lateinit var directory: File
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
|
||||
|
||||
private val dataStore: DataStore<Preferences> by lazy {
|
||||
PreferenceDataStoreFactory.create(scope = scope) { File(directory, "state.preferences_pb") }
|
||||
}
|
||||
|
||||
private val store by lazy { AccountStateStore(dataStore) }
|
||||
|
||||
@AfterEach fun tearDown() = scope.cancel()
|
||||
|
||||
@Test
|
||||
fun `a stopped account is announced once`() = runTest {
|
||||
store.setNeedsSignIn(1, true)
|
||||
|
||||
assertThat(store.markSignInNotified(1)).isTrue()
|
||||
assertThat(store.markSignInNotified(1)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `signing in again makes the next stop news again`() = runTest {
|
||||
store.setNeedsSignIn(1, true)
|
||||
store.markSignInNotified(1)
|
||||
store.setNeedsSignIn(1, false)
|
||||
store.setNeedsSignIn(1, true)
|
||||
|
||||
assertThat(store.markSignInNotified(1)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `accounts are announced independently`() = runTest {
|
||||
store.markSignInNotified(1)
|
||||
|
||||
assertThat(store.markSignInNotified(2)).isTrue()
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
|
||||
import de.jeanlucmakiola.caldav.TaskCollection
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
/** Choosing which lists sync after setup. */
|
||||
class CollectionChangeTest {
|
||||
|
||||
private val work = collection("work")
|
||||
private val home = collection("home")
|
||||
private val shared = collection("shared")
|
||||
|
||||
@Test
|
||||
fun `a newly ticked collection is attached, an already synced one is not`() {
|
||||
val change = AccountRepository.collectionChange(
|
||||
offered = listOf(work, home),
|
||||
selected = setOf(work.url, home.url),
|
||||
synced = listOf(list(1, work)),
|
||||
)
|
||||
|
||||
assertThat(change.attach).containsExactly(home)
|
||||
assertThat(change.drop).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unticked synced list is dropped`() {
|
||||
val change = AccountRepository.collectionChange(
|
||||
offered = listOf(work, home),
|
||||
selected = setOf(work.url),
|
||||
synced = listOf(list(1, work), list(2, home)),
|
||||
)
|
||||
|
||||
assertThat(change.attach).isEmpty()
|
||||
assertThat(change.drop.map { it.id }).containsExactly(2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a synced list the server did not offer this time is left alone`() {
|
||||
// A flaky listing or a share revoked a moment ago is not the user
|
||||
// unticking it.
|
||||
val change = AccountRepository.collectionChange(
|
||||
offered = listOf(work),
|
||||
selected = setOf(work.url),
|
||||
synced = listOf(list(1, work), list(3, shared)),
|
||||
)
|
||||
|
||||
assertThat(change.drop).isEmpty()
|
||||
}
|
||||
|
||||
private fun collection(name: String) = TaskCollection(
|
||||
url = "https://cloud.example.com/dav/$name/".toHttpUrl(),
|
||||
displayName = name,
|
||||
color = null,
|
||||
readOnly = false,
|
||||
isShared = false,
|
||||
supportsSyncCollection = true,
|
||||
maxResourceSize = null,
|
||||
)
|
||||
|
||||
private fun list(id: Long, collection: TaskCollection) = TaskListEntity(
|
||||
id = id,
|
||||
name = collection.displayName!!,
|
||||
color = 0,
|
||||
accountId = 1,
|
||||
href = collection.url.toString(),
|
||||
)
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.caldav.CollectionSupport
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import java.io.File
|
||||
|
||||
/** The cache in front of OPTIONS, which exists so a picker can draw at once. */
|
||||
class CollectionSupportStoreTest {
|
||||
|
||||
@TempDir lateinit var directory: File
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
|
||||
|
||||
private val dataStore: DataStore<Preferences> by lazy {
|
||||
PreferenceDataStoreFactory.create(scope = scope) { File(directory, "support.preferences_pb") }
|
||||
}
|
||||
|
||||
private val store by lazy { CollectionSupportStore(dataStore) }
|
||||
|
||||
@AfterEach fun tearDown() = scope.cancel()
|
||||
|
||||
@Test
|
||||
fun `an account nobody has asked about offers nothing`() = runTest {
|
||||
// Unknown reads as "no": the cost of a missing affordance is one tap to
|
||||
// get it back, and the cost of the other error is a 405 at the end of a
|
||||
// form the user has already filled in.
|
||||
assertThat(store.get(1)).isEqualTo(CollectionSupport.NONE)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a refreshed answer is the one that comes back`() = runTest {
|
||||
val answered = store.refresh(1) { CollectionSupport(mkCalendar = false, extendedMkCol = true) }
|
||||
|
||||
assertThat(answered.extendedMkCol).isTrue()
|
||||
assertThat(store.get(1)).isEqualTo(answered)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a server that loses the capability says so on the next ask`() = runTest {
|
||||
store.refresh(1) { CollectionSupport(mkCalendar = true, extendedMkCol = false) }
|
||||
store.refresh(1) { CollectionSupport.NONE }
|
||||
|
||||
// The whole reason this is a cache rather than the answer: a config
|
||||
// change on the server has to be able to take the affordance away.
|
||||
assertThat(store.get(1).canCreate).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `one account's answer leaves another's alone`() = runTest {
|
||||
store.refresh(1) { CollectionSupport(mkCalendar = true, extendedMkCol = false) }
|
||||
store.refresh(2) { CollectionSupport(mkCalendar = false, extendedMkCol = true) }
|
||||
store.forget(1)
|
||||
|
||||
assertThat(store.get(1)).isEqualTo(CollectionSupport.NONE)
|
||||
assertThat(store.get(2).extendedMkCol).isTrue()
|
||||
}
|
||||
}
|
||||
@@ -1,990 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
|
||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
|
||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskMove
|
||||
import de.jeanlucmakiola.caldav.FetchFailure
|
||||
import de.jeanlucmakiola.caldav.FetchResult
|
||||
import de.jeanlucmakiola.caldav.PushSupport
|
||||
import de.jeanlucmakiola.caldav.PutOutcome
|
||||
import de.jeanlucmakiola.caldav.RemoteResource
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.time.Instant
|
||||
|
||||
class CollectionSyncerTest {
|
||||
|
||||
private val store = FakeStore()
|
||||
private val remote = FakeRemote()
|
||||
private val quarantine = mutableMapOf<String, Int>()
|
||||
private val list = TaskListEntity(
|
||||
id = 1,
|
||||
name = "Tasks",
|
||||
color = 0,
|
||||
accountId = 7,
|
||||
href = "http://server/dav/tasks/",
|
||||
)
|
||||
|
||||
private fun sync(fullDue: Boolean = true) =
|
||||
CollectionSyncer(store) { NOW }.sync(list, remote, quarantine, fullDue)
|
||||
|
||||
// ------------------------------------------------------------------ push
|
||||
|
||||
@Test fun `push support read from the collection reaches the report`() {
|
||||
remote.push = PushSupport(topic = "t1", vapidPublicKey = "key")
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(report.collectionRead).isTrue()
|
||||
assertThat(report.pushSupport).isEqualTo(PushSupport(topic = "t1", vapidPublicKey = "key"))
|
||||
}
|
||||
|
||||
@Test fun `an unreadable collection says nothing about push`() {
|
||||
// Not "no support": a failed PROPFIND must not tear down a working
|
||||
// subscription.
|
||||
remote.push = PushSupport(topic = "t1", vapidPublicKey = null)
|
||||
remote.stateFailure = "503"
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(report.collectionRead).isFalse()
|
||||
assertThat(report.pushSupport).isNull()
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- download
|
||||
|
||||
@Test fun `a new remote task is downloaded and is not dirty`() {
|
||||
remote.put("one.ics", vtodo("a", "Buy milk"))
|
||||
|
||||
val report = sync()
|
||||
|
||||
val row = store.rows.single()
|
||||
assertThat(row.uid).isEqualTo("a")
|
||||
assertThat(row.title).isEqualTo("Buy milk")
|
||||
assertThat(row.href).isEqualTo("http://server/dav/tasks/one.ics")
|
||||
assertThat(row.etag).isEqualTo("e-one.ics")
|
||||
// ⚠️ Explicit, not defaulted. A downstream write that leaves this set
|
||||
// uploads what was just downloaded, and that is how a sync loop starts.
|
||||
assertThat(row.isDirty).isFalse()
|
||||
assertThat(report.downloaded).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `an unchanged etag is not downloaded again`() {
|
||||
remote.put("one.ics", vtodo("a", "Buy milk"))
|
||||
sync()
|
||||
remote.log.clear()
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
}
|
||||
|
||||
@Test fun `a changed etag is downloaded`() {
|
||||
remote.put("one.ics", vtodo("a", "Buy milk"))
|
||||
sync()
|
||||
remote.put("one.ics", vtodo("a", "Buy oat milk"), eTag = "e-2")
|
||||
remote.log.clear()
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(store.rows.single().title).isEqualTo("Buy oat milk")
|
||||
assertThat(remote.log).contains("FETCH one.ics")
|
||||
}
|
||||
|
||||
@Test fun `a weak remote etag is never stored`() {
|
||||
remote.put("one.ics", vtodo("a", "Buy milk"))
|
||||
remote.resources.values.single().eTag =
|
||||
de.jeanlucmakiola.caldav.ETag("weak", weak = true)
|
||||
|
||||
sync()
|
||||
|
||||
// Storing it would make the next conditional write look conditional
|
||||
// while silently not being one.
|
||||
assertThat(store.rows.single().etag).isNull()
|
||||
}
|
||||
|
||||
@Test fun `local-only columns survive a download`() {
|
||||
store.rows += task(id = 5, uid = "a", href = "http://server/dav/tasks/one.ics")
|
||||
.copy(etag = "old", sortOrder = 42, color = 0xFF00FF00.toInt())
|
||||
remote.put("one.ics", vtodo("a", "Renamed"), eTag = "new")
|
||||
|
||||
sync()
|
||||
|
||||
val row = store.rows.single()
|
||||
assertThat(row.title).isEqualTo("Renamed")
|
||||
// The server has no opinion about either, so taking the mapper's defaults
|
||||
// would silently reset the user's ordering and colour on every sync.
|
||||
assertThat(row.sortOrder).isEqualTo(42)
|
||||
assertThat(row.color).isEqualTo(0xFF00FF00.toInt())
|
||||
assertThat(row.id).isEqualTo(5)
|
||||
}
|
||||
|
||||
@Test fun `RELATED-TO is resolved to a row id once both rows exist`() {
|
||||
// The child arrives first, so an eager resolution would lose the link.
|
||||
remote.put("child.ics", vtodo("child", "Sub", extra = "RELATED-TO;RELTYPE=PARENT:parent"))
|
||||
remote.put("parent.ics", vtodo("parent", "Top"))
|
||||
|
||||
sync()
|
||||
|
||||
val parent = store.rows.single { it.uid == "parent" }
|
||||
val child = store.rows.single { it.uid == "child" }
|
||||
assertThat(child.parentId).isEqualTo(parent.id)
|
||||
}
|
||||
|
||||
@Test fun `an unreadable body quarantines just that resource`() {
|
||||
remote.put("bad.ics", "this is not iCalendar")
|
||||
remote.put("good.ics", vtodo("a", "Fine"))
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(store.rows.map { it.uid }).containsExactly("a")
|
||||
assertThat(report.quarantined.single().href).endsWith("bad.ics")
|
||||
assertThat(quarantine.values.single()).isEqualTo(1)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- upload
|
||||
|
||||
@Test fun `a new local task is created and its href recorded`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Write it down").copy(isDirty = true)
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(remote.resources.keys.single()).endsWith("/a.ics")
|
||||
val row = store.rows.single()
|
||||
assertThat(row.href).isEqualTo("http://server/dav/tasks/a.ics")
|
||||
assertThat(row.etag).isEqualTo("e-a.ics")
|
||||
assertThat(row.isDirty).isFalse()
|
||||
assertThat(report.uploaded).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `an edited task is updated with If-Match`() {
|
||||
remote.put("one.ics", vtodo("a", "Old"))
|
||||
store.rows += task(id = 1, uid = "a", title = "New")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-one.ics", isDirty = true)
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(remote.log).contains("UPDATE one.ics if-match=e-one.ics")
|
||||
assertThat(remote.resources.values.single().body).contains("SUMMARY:New")
|
||||
}
|
||||
|
||||
@Test fun `a failed validator fetch defers the update instead of writing blind`() {
|
||||
remote.put("one.ics", vtodo("a", "Server"))
|
||||
// No local etag: what StoredNeedsRefetch, and any server that serves none,
|
||||
// leave behind.
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", isDirty = true)
|
||||
var failNext = true
|
||||
remote.onFetch = {
|
||||
if (failNext) {
|
||||
failNext = false
|
||||
Result.failure(IllegalStateException("timeout"))
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Not knowing the validator is not the same as the server having none.
|
||||
assertThat(remote.log.none { it.startsWith("UPDATE") }).isTrue()
|
||||
assertThat(remote.resources.values.single().body).contains("SUMMARY:Server")
|
||||
assertThat(report.unconditionalWrites).isEqualTo(0)
|
||||
val row = store.rows.single()
|
||||
assertThat(row.title).isEqualTo("Mine")
|
||||
assertThat(row.isDirty).isTrue()
|
||||
assertThat(quarantine).isEmpty()
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(0)
|
||||
assertThat(report.quarantined.single().reason).contains("validator fetch failed")
|
||||
|
||||
remote.onFetch = null
|
||||
sync()
|
||||
|
||||
assertThat(remote.log).contains("UPDATE one.ics if-match=e-one.ics")
|
||||
assertThat(remote.resources.values.single().body).contains("SUMMARY:Mine")
|
||||
assertThat(store.rows.single().isDirty).isFalse()
|
||||
assertThat(quarantine).isEmpty()
|
||||
}
|
||||
|
||||
@Test fun `a server with no validator to offer is still written to`() {
|
||||
remote.put("one.ics", vtodo("a", "Server"), eTag = null)
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", isDirty = true)
|
||||
|
||||
val report = sync()
|
||||
|
||||
// The fetch succeeded and there was simply no validator — the case
|
||||
// unconditionalWrites exists to count. Deferring here instead would stop
|
||||
// syncing to every etag-less server.
|
||||
assertThat(remote.log).contains("UPDATE one.ics if-match=null")
|
||||
assertThat(report.unconditionalWrites).isEqualTo(1)
|
||||
assertThat(remote.resources.values.single().body).contains("SUMMARY:Mine")
|
||||
}
|
||||
|
||||
@Test fun `a PUT that returns no usable etag triggers a refetch`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "New").copy(isDirty = true)
|
||||
remote.onPut = { href -> PutOutcome.StoredNeedsRefetch(href) }
|
||||
|
||||
sync()
|
||||
|
||||
// Not an error: the resource is on the server, but without a usable
|
||||
// validator and possibly not as the bytes we sent.
|
||||
assertThat(remote.log).contains("FETCH a.ics")
|
||||
assertThat(store.rows.single().etag).isNull()
|
||||
}
|
||||
|
||||
@Test fun `a rejected upload quarantines and leaves the row dirty`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Bad").copy(isDirty = true)
|
||||
remote.onPut = { PutOutcome.Rejected(415, "Unsupported Media Type") }
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(report.quarantined.single().reason).contains("415")
|
||||
// Retrying identical bytes cannot help, but the edit is not thrown away.
|
||||
assertThat(store.rows.single().isDirty).isTrue()
|
||||
}
|
||||
|
||||
@Test fun `a quarantined resource is skipped once it hits the threshold`() {
|
||||
remote.put("one.ics", vtodo("a", "Server"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-one.ics", isDirty = true)
|
||||
remote.onPut = { PutOutcome.Rejected(400, "Bad Request") }
|
||||
|
||||
repeat(QuarantineStore.THRESHOLD) { sync() }
|
||||
remote.log.clear()
|
||||
sync()
|
||||
|
||||
// ⚠️ A single 400 on one resource has halted all calendar sync in DAVx5
|
||||
// for weeks. After the threshold this one is left alone and the rest of
|
||||
// the collection still runs.
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
}
|
||||
|
||||
@Test fun `an invalid body never leaves the device`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Backwards").copy(
|
||||
isDirty = true,
|
||||
dtstart = Instant.parse("2026-03-01T10:00:00Z"),
|
||||
due = Instant.parse("2026-03-01T09:00:00Z"),
|
||||
)
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
assertThat(report.quarantined.single().reason).contains("DUE precedes DTSTART")
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- conflict
|
||||
|
||||
@Test fun `a 412 on update discards the local edit and reports it`() {
|
||||
remote.put("one.ics", vtodo("a", "Server won"), eTag = "newer")
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "stale", isDirty = true)
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Decision 2: server wins. The report is the other half of that policy —
|
||||
// without it this is indistinguishable from data loss.
|
||||
assertThat(report.discardedEdits.single().cause)
|
||||
.isEqualTo(DiscardedEdit.Cause.SERVER_NEWER)
|
||||
assertThat(report.discardedEdits.single().title).isEqualTo("Mine")
|
||||
assertThat(store.rows.single().title).isEqualTo("Server won")
|
||||
assertThat(store.rows.single().isDirty).isFalse()
|
||||
}
|
||||
|
||||
@Test fun `a lost 412 conflict keeps the edit when the replacement never arrives`() {
|
||||
remote.put("one.ics", vtodo("a", "Server won"), eTag = "newer")
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "stale", isDirty = true)
|
||||
// The 412 lands, then the replacement download dies.
|
||||
remote.resources["http://server/dav/tasks/one.ics"]!!.body = "not iCalendar"
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Nothing was replaced, so nothing was discarded — and the edit is still
|
||||
// there to try again with.
|
||||
assertThat(report.discardedEdits).isEmpty()
|
||||
assertThat(store.rows.single().title).isEqualTo("Mine")
|
||||
assertThat(store.rows.single().isDirty).isTrue()
|
||||
}
|
||||
|
||||
@Test fun `an edit to a task deleted on the server loses`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/gone.ics", etag = "e", isDirty = true)
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(store.rows).isEmpty()
|
||||
assertThat(report.discardedEdits.single().cause)
|
||||
.isEqualTo(DiscardedEdit.Cause.DELETED_ON_SERVER)
|
||||
}
|
||||
|
||||
@Test fun `a delete that loses to a server edit is undone`() {
|
||||
remote.put("one.ics", vtodo("a", "Server changed it"), eTag = "newer")
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine").copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "stale",
|
||||
isDeleted = true,
|
||||
isDirty = true,
|
||||
)
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(report.discardedEdits.single().cause)
|
||||
.isEqualTo(DiscardedEdit.Cause.DELETE_LOST)
|
||||
val row = store.rows.single()
|
||||
assertThat(row.isDeleted).isFalse()
|
||||
assertThat(row.title).isEqualTo("Server changed it")
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- deletion
|
||||
|
||||
@Test fun `a tombstone with an href is deleted on the server`() {
|
||||
remote.put("one.ics", vtodo("a", "Gone"))
|
||||
store.rows += task(id = 1, uid = "a")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-one.ics", isDeleted = true)
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(remote.resources).isEmpty()
|
||||
assertThat(store.rows).isEmpty()
|
||||
assertThat(report.deletedRemotely).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `a task deleted before it was ever uploaded is never DELETEd`() {
|
||||
store.rows += task(id = 1, uid = "a").copy(isDeleted = true, isDirty = true)
|
||||
|
||||
sync()
|
||||
|
||||
// A DELETE here would 404 on every sync, forever.
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
assertThat(store.rows).isEmpty()
|
||||
}
|
||||
|
||||
@Test fun `a deleted occurrence is dropped from the store once the PUT lands`() {
|
||||
remote.put("one.ics", vtodo("a", "Weekly"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Weekly")
|
||||
.copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-one.ics",
|
||||
rrule = "FREQ=WEEKLY",
|
||||
)
|
||||
store.rows += task(id = 2, uid = "a", title = "Weekly")
|
||||
.copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-one.ics",
|
||||
masterId = 1,
|
||||
recurrenceId = NOW,
|
||||
isDeleted = true,
|
||||
isDirty = true,
|
||||
)
|
||||
|
||||
sync()
|
||||
|
||||
// The occurrence left the body, so the PUT is its deletion. Marking the
|
||||
// tombstone synced instead strands is_deleted = 1 with is_dirty = 0,
|
||||
// which no phase can reach and which the unique index on
|
||||
// (list_id, uid, recurrence_id) turns into a permanent failure to re-add.
|
||||
assertThat(remote.log.any { it.startsWith("UPDATE one.ics") }).isTrue()
|
||||
assertThat(remote.log.none { it.startsWith("DELETE") }).isTrue()
|
||||
assertThat(store.rows.none { it.isDeleted }).isTrue()
|
||||
assertThat(store.rows.map { it.id }).containsExactly(1L)
|
||||
// FakeStore models neither the unique index on (list_id, uid,
|
||||
// recurrence_id) nor the master_id cascade, so the permanent-failure-to-
|
||||
// re-add consequence is reasoned about, not asserted here.
|
||||
assertThat(store.rows.single().isDirty).isFalse()
|
||||
}
|
||||
|
||||
@Test fun `a tombstoned master with a live override keeps its row`() {
|
||||
remote.put("one.ics", vtodo("a", "Series"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Series").copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-one.ics",
|
||||
isDeleted = true,
|
||||
isDirty = true,
|
||||
)
|
||||
store.rows += task(id = 2, uid = "a", title = "Series").copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-one.ics",
|
||||
masterId = 1,
|
||||
recurrenceId = NOW,
|
||||
)
|
||||
|
||||
sync()
|
||||
|
||||
// ⚠️ The shape an older version of markDeleted left behind: the master
|
||||
// tombstoned, its overrides live. Read as rows.all it was "partly
|
||||
// deleted", so it went to the upload phase, no DELETE was ever sent, and
|
||||
// it ended is_deleted = 1, is_dirty = 0 with a matching ETag — beyond
|
||||
// every phase's reach, gone here and still there for everyone else. The
|
||||
// master's tombstone is the resource's, so the next sync finishes what
|
||||
// the user asked for.
|
||||
assertThat(remote.log).contains("DELETE one.ics if-match=e-one.ics")
|
||||
assertThat(store.rows).isEmpty()
|
||||
}
|
||||
|
||||
@Test fun `the sweep does not remove what this run just created`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Fresh").copy(isDirty = true)
|
||||
|
||||
sync()
|
||||
|
||||
// The listing was taken before the upload, so the new href is not in it.
|
||||
assertThat(store.rows).hasSize(1)
|
||||
assertThat(remote.resources).hasSize(1)
|
||||
}
|
||||
|
||||
@Test fun `an empty listing never sweeps`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e")
|
||||
store.rows += task(id = 2, uid = "b", title = "Also mine")
|
||||
.copy(href = "http://server/dav/tasks/two.ics", etag = "e")
|
||||
|
||||
val report = sync()
|
||||
|
||||
// ⚠️ A server that mishandles the VTODO comp-filter answers with an empty
|
||||
// *successful* multistatus, which is indistinguishable from an empty
|
||||
// collection. Sweeping on that evidence hard-deletes every task at once.
|
||||
assertThat(store.rows).hasSize(2)
|
||||
assertThat(report.deletedLocally).isEqualTo(0)
|
||||
assertThat(report.failure).contains("listed no tasks")
|
||||
}
|
||||
|
||||
@Test fun `a resource missing from a non-empty listing is swept`() {
|
||||
remote.put("one.ics", vtodo("a", "Still there"))
|
||||
store.rows += task(id = 1, uid = "a")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-one.ics")
|
||||
store.rows += task(id = 2, uid = "b")
|
||||
.copy(href = "http://server/dav/tasks/two.ics", etag = "e")
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(store.rows.map { it.uid }).containsExactly("a")
|
||||
assertThat(report.deletedLocally).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `a task recreated under a new href is repointed, not swept`() {
|
||||
// Another client deleted one.ics and recreated the same UID as two.ics.
|
||||
remote.put("two.ics", vtodo("a", "Buy milk"))
|
||||
store.rows += task(id = 5, uid = "a", title = "Buy milk")
|
||||
.copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-one.ics",
|
||||
sortOrder = 42,
|
||||
color = 0xFF0000,
|
||||
)
|
||||
|
||||
val report = sync()
|
||||
|
||||
// The download re-points row 5; a sweep reading the pre-download list
|
||||
// would purge it by id and lose the local-only columns for good.
|
||||
val row = store.rows.single()
|
||||
assertThat(row.id).isEqualTo(5)
|
||||
assertThat(row.href).isEqualTo("http://server/dav/tasks/two.ics")
|
||||
assertThat(row.sortOrder).isEqualTo(42)
|
||||
assertThat(row.color).isEqualTo(0xFF0000)
|
||||
assertThat(report.deletedLocally).isEqualTo(0)
|
||||
assertThat(report.downloaded).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `the post-download sweep still removes a stale row`() {
|
||||
remote.put("one.ics", vtodo("a", "New"))
|
||||
store.rows += task(id = 1, uid = "b")
|
||||
.copy(href = "http://server/dav/tasks/gone.ics", etag = "e")
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Reading locals after the download widens what the sweep sees; the row
|
||||
// just inserted must survive it, the stale one must not.
|
||||
assertThat(store.rows.map { it.uid }).containsExactly("a")
|
||||
assertThat(report.deletedLocally).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `a resource the server refuses is counted, and the batch survives`() {
|
||||
remote.put("one.ics", vtodo("a", "Fine"))
|
||||
remote.put("two.ics", vtodo("b", "Refused"))
|
||||
remote.onFetch = { hrefs -> refuseTwoIcs(hrefs, code = 403) }
|
||||
|
||||
val report = sync()
|
||||
|
||||
// A refusal on one member says nothing about the others.
|
||||
assertThat(store.rows.map { it.uid }).containsExactly("a")
|
||||
assertThat(quarantine.values.single()).isEqualTo(1)
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(1)
|
||||
assertThat(report.quarantined.single().reason).contains("403")
|
||||
}
|
||||
|
||||
@Test fun `a resource the server says is gone is not counted`() {
|
||||
remote.put("one.ics", vtodo("a", "Fine"))
|
||||
remote.put("two.ics", vtodo("b", "Gone"))
|
||||
remote.onFetch = { hrefs -> refuseTwoIcs(hrefs, code = 404) }
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Counting it would quarantine the resource out of the sweep that is
|
||||
// about to clean it up once the listing drops it.
|
||||
assertThat(quarantine).isEmpty()
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test fun `a resource the server fails on is not counted`() {
|
||||
remote.put("one.ics", vtodo("a", "Fine"))
|
||||
remote.put("two.ics", vtodo("b", "Broken"))
|
||||
remote.onFetch = { hrefs -> refuseTwoIcs(hrefs, code = 500) }
|
||||
|
||||
val report = sync()
|
||||
|
||||
// A multiget carries no body of ours, so there is nothing here a server
|
||||
// could be permanently right to reject.
|
||||
assertThat(quarantine).isEmpty()
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test fun `a missing href is not counted when the server also sent strays`() {
|
||||
remote.put("one.ics", vtodo("a", "Fine"))
|
||||
remote.onFetch = { hrefs ->
|
||||
Result.success(
|
||||
FetchResult(
|
||||
resources = emptyList(),
|
||||
missing = hrefs,
|
||||
failed = emptyList(),
|
||||
// The shape an href we failed to recognise takes: the same
|
||||
// path, in both buckets.
|
||||
unsolicited = listOf("http://elsewhere/dav/tasks/one.ics".toHttpUrl()),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val report = sync()
|
||||
|
||||
// ⚠️ Counting here is irreversible — at THRESHOLD the href is stripped
|
||||
// before the fetch, so nothing can ever clear it again.
|
||||
assertThat(quarantine).isEmpty()
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test fun `a stray for another path does not excuse a missing one`() {
|
||||
remote.put("one.ics", vtodo("a", "Fine"))
|
||||
remote.onFetch = { hrefs ->
|
||||
Result.success(
|
||||
FetchResult(
|
||||
resources = emptyList(),
|
||||
missing = hrefs,
|
||||
failed = emptyList(),
|
||||
// Servers volunteer siblings routinely. Excusing every
|
||||
// missing href on that basis would mean nothing is ever
|
||||
// counted, and the loop never breaks.
|
||||
unsolicited = listOf("http://server/dav/tasks/somebody-else.ics".toHttpUrl()),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(quarantine.values.single()).isEqualTo(1)
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `a missing href is still counted when nothing was unmatched`() {
|
||||
remote.put("one.ics", vtodo("a", "Fine"))
|
||||
remote.onFetch = { hrefs ->
|
||||
Result.success(
|
||||
FetchResult(
|
||||
resources = emptyList(),
|
||||
missing = hrefs,
|
||||
failed = emptyList(),
|
||||
unsolicited = emptyList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val report = sync()
|
||||
|
||||
// A plain omission repeats identically every run and nothing else breaks
|
||||
// the loop, which is what the counter is for.
|
||||
assertThat(quarantine.values.single()).isEqualTo(1)
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `a resource the server keeps refusing stops being requested`() {
|
||||
remote.put("two.ics", vtodo("b", "Refused"))
|
||||
remote.onFetch = { hrefs -> refuseTwoIcs(hrefs, code = 403) }
|
||||
|
||||
repeat(QuarantineStore.THRESHOLD) { sync() }
|
||||
remote.log.clear()
|
||||
sync(fullDue = false)
|
||||
|
||||
// The whole point. It is in the listing, so the sweep leaves it alone,
|
||||
// and it never reaches apply, so without a count it is re-requested on
|
||||
// every sync for ever. The daily reconciliation still probes it once —
|
||||
// otherwise nothing on this side could ever clear the count.
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
}
|
||||
|
||||
@Test fun `a create the server keeps refusing is eventually quarantined`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Never acceptable").copy(isDirty = true)
|
||||
remote.onPut = { PutOutcome.Rejected(415, "Unsupported Media Type") }
|
||||
|
||||
repeat(QuarantineStore.THRESHOLD) { sync() }
|
||||
remote.log.clear()
|
||||
sync()
|
||||
|
||||
// A resource with no href yet still has to be countable, or it is re-PUT
|
||||
// on every sync forever.
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
assertThat(quarantine.keys.single()).isEqualTo("${list.id}|uid:a")
|
||||
}
|
||||
|
||||
@Test fun `a successful create clears the counter it accrued as a uid`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Flaky").copy(isDirty = true)
|
||||
remote.onPut = { PutOutcome.Failed("network") }
|
||||
sync()
|
||||
assertThat(quarantine).isNotEmpty()
|
||||
|
||||
remote.onPut = null
|
||||
sync()
|
||||
|
||||
// Both keys, or the uid-keyed one leaks into the store forever.
|
||||
assertThat(quarantine).isEmpty()
|
||||
}
|
||||
|
||||
@Test fun `a RELATED-TO removed on the server unparents the task`() {
|
||||
remote.put("parent.ics", vtodo("parent", "Top"))
|
||||
remote.put("child.ics", vtodo("child", "Sub", extra = "RELATED-TO;RELTYPE=PARENT:parent"))
|
||||
sync()
|
||||
assertThat(store.rows.single { it.uid == "child" }.parentId).isNotNull()
|
||||
|
||||
remote.put("child.ics", vtodo("child", "Sub"), eTag = "e-2")
|
||||
sync()
|
||||
|
||||
// Carrying the old parent_id forward would re-upload, on the next local
|
||||
// edit, the relationship the user deleted elsewhere.
|
||||
assertThat(store.rows.single { it.uid == "child" }.parentId).isNull()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- name clashes
|
||||
|
||||
@Test fun `a name taken by another task gets a fresh one`() {
|
||||
remote.put("a.ics", vtodo("somebody-else", "Not ours"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Ours").copy(isDirty = true)
|
||||
|
||||
sync()
|
||||
|
||||
val ours = store.rows.single { it.uid == "a" }
|
||||
assertThat(ours.href).isNotEqualTo("http://server/dav/tasks/a.ics")
|
||||
assertThat(ours.href).endsWith(".ics")
|
||||
assertThat(ours.isDirty).isFalse()
|
||||
}
|
||||
|
||||
@Test fun `a name taken by the same task is adopted`() {
|
||||
// A previous run's PUT whose answer we never saw.
|
||||
remote.put("a.ics", vtodo("a", "Uploaded last time"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Ours").copy(isDirty = true)
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(remote.resources).hasSize(1)
|
||||
assertThat(store.rows.single().href).isEqualTo("http://server/dav/tasks/a.ics")
|
||||
}
|
||||
|
||||
@Test fun `a create whose verification fetch fails is not duplicated`() {
|
||||
// Our own PUT from a run whose answer never arrived, and an edit the user
|
||||
// made afterwards that only exists here.
|
||||
remote.put("a.ics", vtodo("a", "Uploaded last time"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Edited after the lost PUT")
|
||||
.copy(isDirty = true)
|
||||
// Only the verification fetch fails. A blanket failure would take the
|
||||
// download phase's multiget with it and pass for the wrong reason.
|
||||
var failNext = true
|
||||
remote.onFetch = {
|
||||
if (failNext) {
|
||||
failNext = false
|
||||
Result.failure(IllegalStateException("timeout"))
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Renaming on a failed fetch would put one UID in two resources, which
|
||||
// RFC 4791 §4.1 forbids and which no later sync can clean up.
|
||||
assertThat(remote.resources).hasSize(1)
|
||||
assertThat(remote.log.count { it.startsWith("CREATE") }).isEqualTo(1)
|
||||
// Deferring the write is only worth anything if the read defers too: the
|
||||
// row has no href, so downloadPhase cannot match it and would otherwise
|
||||
// overwrite the edit by UID with nothing in discardedEdits.
|
||||
val row = store.rows.single()
|
||||
assertThat(row.title).isEqualTo("Edited after the lost PUT")
|
||||
assertThat(row.isDirty).isTrue()
|
||||
assertThat(row.href).isNull()
|
||||
// Deferred, not charged: nothing can refund a UID-keyed count once the
|
||||
// resource is quarantined out of uploadPhase.
|
||||
assertThat(quarantine).isEmpty()
|
||||
assertThat(report.quarantined.single().reason).contains("verification failed")
|
||||
assertThat(report.quarantined.single().failures).isEqualTo(0)
|
||||
|
||||
// And the next run adopts the resource.
|
||||
remote.onFetch = null
|
||||
sync()
|
||||
|
||||
assertThat(remote.resources).hasSize(1)
|
||||
val adopted = store.rows.single()
|
||||
assertThat(adopted.href).isEqualTo("http://server/dav/tasks/a.ics")
|
||||
assertThat(adopted.title).isEqualTo("Edited after the lost PUT")
|
||||
assertThat(quarantine).isEmpty()
|
||||
}
|
||||
|
||||
@Test fun `an adoption whose validator fetch fails keeps the local edit`() {
|
||||
// Create 412s, the first fetch proves the resource is ours, and the
|
||||
// validator fetch inside the adoption then fails.
|
||||
remote.put("a.ics", vtodo("a", "Uploaded last time"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Edited after the lost PUT")
|
||||
.copy(isDirty = true)
|
||||
var fetches = 0
|
||||
remote.onFetch = {
|
||||
fetches += 1
|
||||
if (fetches == 2) Result.failure(IllegalStateException("timeout")) else null
|
||||
}
|
||||
|
||||
sync()
|
||||
|
||||
// The row still has no href here, so downloadPhase cannot match it and
|
||||
// only `deferred` keeps apply from overwriting the edit by UID. This is
|
||||
// the call site that makes updateResource's `deferred` load-bearing.
|
||||
assertThat(remote.resources).hasSize(1)
|
||||
val row = store.rows.single()
|
||||
assertThat(row.title).isEqualTo("Edited after the lost PUT")
|
||||
assertThat(row.isDirty).isTrue()
|
||||
assertThat(row.href).isNull()
|
||||
}
|
||||
|
||||
@Test fun `a refused verification fetch does not rename the create`() {
|
||||
remote.put("a.ics", vtodo("a", "Uploaded last time"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Edited after the lost PUT")
|
||||
.copy(isDirty = true)
|
||||
// A per-resource refusal is a *successful* multiget. Without inspecting
|
||||
// `failed`, the empty resources list reads as somebody else's resource.
|
||||
remote.onFetch = { hrefs ->
|
||||
Result.success(
|
||||
FetchResult(
|
||||
resources = emptyList(),
|
||||
missing = emptyList(),
|
||||
failed = hrefs.map { FetchFailure(it, 403) },
|
||||
unsolicited = emptyList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(remote.resources).hasSize(1)
|
||||
assertThat(remote.log.count { it.startsWith("CREATE") }).isEqualTo(1)
|
||||
val row = store.rows.single()
|
||||
assertThat(row.title).isEqualTo("Edited after the lost PUT")
|
||||
assertThat(row.isDirty).isTrue()
|
||||
}
|
||||
|
||||
@Test fun `a refused validator fetch does not write unconditionally`() {
|
||||
remote.put("one.ics", vtodo("a", "Server"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", isDirty = true)
|
||||
remote.onFetch = { hrefs ->
|
||||
Result.success(
|
||||
FetchResult(
|
||||
resources = emptyList(),
|
||||
missing = emptyList(),
|
||||
failed = hrefs.map { FetchFailure(it, 500) },
|
||||
unsolicited = emptyList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(remote.log.none { it.startsWith("UPDATE") }).isTrue()
|
||||
assertThat(report.unconditionalWrites).isEqualTo(0)
|
||||
assertThat(remote.resources.values.single().body).contains("SUMMARY:Server")
|
||||
assertThat(store.rows.single().isDirty).isTrue()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ protection
|
||||
|
||||
@Test fun `a read-only collection is never written to`() {
|
||||
remote.readOnly = true
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine").copy(isDirty = true)
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
assertThat(report.quarantined.single().reason).contains("read-only")
|
||||
// ⚠️ ACL churn is silent, so the refreshed flag is written back.
|
||||
assertThat(store.readOnlyWrites.single()).isEqualTo(list.id to true)
|
||||
}
|
||||
|
||||
@Test fun `a confidential task in a shared collection is not written back`() {
|
||||
remote.shared = true
|
||||
remote.put("one.ics", vtodo("a", "Secret"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Secret").copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-one.ics",
|
||||
classification = 2,
|
||||
isDirty = true,
|
||||
)
|
||||
|
||||
val report = sync()
|
||||
|
||||
// ⚠️ Nextcloud's CalendarObject::get() serves a whitelist-reduced copy of
|
||||
// a confidential object from a share while leaving the ETag untouched.
|
||||
// Writing that back destroys the owner's task, and the ETag matches.
|
||||
assertThat(remote.log).containsExactly("LIST")
|
||||
assertThat(report.quarantined.single().reason).contains("reduced copy")
|
||||
}
|
||||
|
||||
@Test fun `a confidential task the user owns is written normally`() {
|
||||
remote.shared = false
|
||||
remote.put("one.ics", vtodo("a", "Secret"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Secret").copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-one.ics",
|
||||
classification = 2,
|
||||
isDirty = true,
|
||||
)
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(remote.log).contains("UPDATE one.ics if-match=e-one.ics")
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- failures
|
||||
|
||||
@Test fun `a collection that cannot be listed reports rather than throws`() {
|
||||
remote.listFailure = "boom"
|
||||
val report = sync()
|
||||
assertThat(report.failure).contains("boom")
|
||||
}
|
||||
|
||||
@Test fun `a collection that is no longer readable reports rather than throws`() {
|
||||
remote.stateFailure = "revoked"
|
||||
val report = sync()
|
||||
assertThat(report.failure).contains("revoked")
|
||||
}
|
||||
|
||||
@Test fun `a rename into a name another task took keeps both rows`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Moved")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-old")
|
||||
// Fetched in insertion order, so the rename is applied first and leaves
|
||||
// the index entry for `one.ics` behind.
|
||||
remote.put("two.ics", vtodo("a", "Moved"))
|
||||
remote.put("one.ics", vtodo("b", "A different task at the old name"))
|
||||
|
||||
sync()
|
||||
|
||||
// ⚠️ `one.ics` now holds somebody else, and row 1 no longer lives there
|
||||
// — reading it out of a stale index entry deletes the task the rename
|
||||
// just repaired.
|
||||
assertThat(store.rows.map { it.uid }).containsExactly("a", "b")
|
||||
}
|
||||
|
||||
@Test fun `a full reconciliation probes a resource the download gave up on`() {
|
||||
remote.put("one.ics", vtodo("a", "Buy milk"))
|
||||
quarantine[QuarantineStore.key(list.id, "http://server/dav/tasks/one.ics")] =
|
||||
QuarantineStore.THRESHOLD
|
||||
|
||||
sync()
|
||||
|
||||
// ⚠️ The download side has no refund — at THRESHOLD the href is stripped
|
||||
// before the fetch, so nothing can ever clear the count again. One probe
|
||||
// per periodic reconciliation is the expiry.
|
||||
assertThat(store.rows.single().uid).isEqualTo("a")
|
||||
assertThat(quarantine).isEmpty()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- setup
|
||||
|
||||
/** A multiget in which `two.ics` alone comes back refused. */
|
||||
private fun refuseTwoIcs(hrefs: List<HttpUrl>, code: Int): Result<FetchResult> {
|
||||
val refused = hrefs.filter { it.pathSegments.last() == "two.ics" }
|
||||
val rest = hrefs - refused.toSet()
|
||||
val served = remote.resources.filterKeys { key -> rest.any { it.toString() == key } }
|
||||
return Result.success(
|
||||
FetchResult(
|
||||
resources = served.map { (href, stored) ->
|
||||
RemoteResource(
|
||||
href = href.toHttpUrl(),
|
||||
eTag = stored.eTag,
|
||||
iCalendar = stored.body,
|
||||
)
|
||||
},
|
||||
missing = emptyList(),
|
||||
failed = refused.map { FetchFailure(it, code) },
|
||||
unsolicited = emptyList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ move
|
||||
|
||||
@Test fun `a task moved to another collection leaves the old one and is created in the new`() {
|
||||
remote.put("one.ics", vtodo("a", "Milk"))
|
||||
sync()
|
||||
val row = store.rows.single()
|
||||
val other = TaskListEntity(id = 2, name = "Other", color = 0, accountId = 7, href = "http://server/dav/other/")
|
||||
val otherRemote = FakeRemote("http://server/dav/other/".toHttpUrl())
|
||||
|
||||
val plan = TaskMove.plan(row.copy(listId = other.id), row, emptyList(), true, null)
|
||||
plan.update.forEach(store::update)
|
||||
plan.tombstone?.let(store::insert)
|
||||
|
||||
val syncer = CollectionSyncer(store) { NOW }
|
||||
syncer.sync(list, remote, quarantine)
|
||||
syncer.sync(other, otherRemote, quarantine)
|
||||
|
||||
// ⚠️ Keeping the href would have PUT the edit back into the old
|
||||
// collection, and the new one would never have heard of it.
|
||||
assertThat(remote.log).contains("DELETE one.ics if-match=e-one.ics")
|
||||
assertThat(remote.resources).isEmpty()
|
||||
assertThat(otherRemote.resources).hasSize(1)
|
||||
val moved = store.rows.single()
|
||||
assertThat(moved.id).isEqualTo(row.id)
|
||||
assertThat(moved.listId).isEqualTo(other.id)
|
||||
assertThat(moved.href).startsWith("http://server/dav/other/")
|
||||
assertThat(moved.isDirty).isFalse()
|
||||
}
|
||||
|
||||
@Test fun `a move that lost to a server edit brings the server's copy back`() {
|
||||
remote.put("one.ics", vtodo("a", "Milk"))
|
||||
sync()
|
||||
val row = store.rows.single()
|
||||
val plan = TaskMove.plan(row.copy(listId = 2), row, emptyList(), true, null)
|
||||
plan.update.forEach(store::update)
|
||||
plan.tombstone?.let(store::insert)
|
||||
remote.put("one.ics", vtodo("a", "Oat milk"), eTag = "e-2")
|
||||
|
||||
val report = sync()
|
||||
|
||||
// The DELETE is conditional, so a newer copy on the server survives and
|
||||
// is downloaded again rather than destroyed.
|
||||
assertThat(remote.resources).hasSize(1)
|
||||
assertThat(store.rowsIn(list.id).single().title).isEqualTo("Oat milk")
|
||||
assertThat(report.discardedEdits.single().cause).isEqualTo(DiscardedEdit.Cause.DELETE_LOST)
|
||||
}
|
||||
|
||||
private fun task(
|
||||
id: Long,
|
||||
uid: String,
|
||||
title: String? = null,
|
||||
href: String? = null,
|
||||
) = TaskEntity(id = id, listId = list.id, uid = uid, title = title, href = href)
|
||||
|
||||
private fun vtodo(uid: String, summary: String, extra: String? = null) = buildString {
|
||||
append("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VTODO\r\n")
|
||||
append("UID:$uid\r\nSUMMARY:$summary\r\n")
|
||||
extra?.let { append("$it\r\n") }
|
||||
append("END:VTODO\r\nEND:VCALENDAR\r\n")
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val NOW: Instant = Instant.parse("2026-03-01T12:00:00Z")
|
||||
}
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
|
||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
|
||||
import de.jeanlucmakiola.caldav.ChangeSet
|
||||
import de.jeanlucmakiola.caldav.ETag
|
||||
import de.jeanlucmakiola.caldav.RemoteRef
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** RFC 6578, from the engine's side. */
|
||||
class IncrementalSyncTest {
|
||||
|
||||
private val store = FakeStore()
|
||||
private val remote = FakeRemote()
|
||||
private val quarantine = mutableMapOf<String, Int>()
|
||||
private var list = TaskListEntity(
|
||||
id = 1,
|
||||
name = "Tasks",
|
||||
color = 0,
|
||||
accountId = 7,
|
||||
href = "http://server/dav/tasks/",
|
||||
syncToken = "urn:x:1",
|
||||
)
|
||||
|
||||
init {
|
||||
remote.supportsSyncCollection = true
|
||||
remote.syncToken = "urn:x:from-propfind"
|
||||
}
|
||||
|
||||
private fun sync(fullDue: Boolean = false) =
|
||||
CollectionSyncer(store) { NOW }.sync(list, remote, quarantine, fullDue)
|
||||
|
||||
// ------------------------------------------------------------ the cursor
|
||||
|
||||
@Test fun `the token is stored only after its bodies are applied`() {
|
||||
remote.put("one.ics", vtodo("a", "New"))
|
||||
remote.changePages += page(changed = listOf("one.ics"), token = "urn:x:2")
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(store.rows.single().title).isEqualTo("New")
|
||||
assertThat(store.tokenWrites).containsExactly("urn:x:2")
|
||||
// The full path was not needed, so no listing was taken.
|
||||
assertThat(remote.log).doesNotContain("LIST")
|
||||
}
|
||||
|
||||
@Test fun `a truncated page is resumed and each page commits its own token`() {
|
||||
remote.put("one.ics", vtodo("a", "First"))
|
||||
remote.put("two.ics", vtodo("b", "Second"))
|
||||
remote.changePages += page(changed = listOf("one.ics"), token = "urn:x:2", truncated = true)
|
||||
remote.changePages += page(changed = listOf("two.ics"), token = "urn:x:3")
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(store.rows.map { it.uid }).containsExactly("a", "b")
|
||||
// ⚠️ Per page, in order. A token written ahead of its bodies is a
|
||||
// permanent hole in the collection the moment the process dies.
|
||||
assertThat(store.tokenWrites).containsExactly("urn:x:2", "urn:x:3").inOrder()
|
||||
}
|
||||
|
||||
@Test fun `a server that truncates without advancing its token is not looped on`() {
|
||||
remote.changePages += page(changed = emptyList(), token = "urn:x:1", truncated = true)
|
||||
|
||||
val report = sync()
|
||||
|
||||
// The RFC never requires the token to advance. The full path then
|
||||
// reconciled the collection, so this is a note rather than a failure.
|
||||
assertThat(report.incrementalNote).contains("without advancing")
|
||||
assertThat(report.failure).isNull()
|
||||
assertThat(remote.log.count { it.startsWith("CHANGES") }).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `a page with no token at all falls back to a full reconciliation`() {
|
||||
remote.put("one.ics", vtodo("a", "New"))
|
||||
remote.changePages += page(changed = listOf("one.ics"), token = null)
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(store.rows.single().uid).isEqualTo("a")
|
||||
assertThat(report.reconciledInFull).isTrue()
|
||||
assertThat(remote.log).contains("LIST")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------- invalidation
|
||||
|
||||
@Test fun `an invalidated token is cleared and the run reconciles in full`() {
|
||||
remote.put("one.ics", vtodo("a", "From the listing"))
|
||||
remote.changePages += ChangeSet.TokenInvalid
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Cleared first, so a crash before the full run cannot leave behind a
|
||||
// token we already know the server rejects.
|
||||
assertThat(store.tokenWrites.first()).isNull()
|
||||
assertThat(report.reconciledInFull).isTrue()
|
||||
assertThat(store.rows.single().uid).isEqualTo("a")
|
||||
// Adopted from the PROPFIND that preceded the listing, never after it.
|
||||
assertThat(store.tokenWrites.last()).isEqualTo("urn:x:from-propfind")
|
||||
}
|
||||
|
||||
@Test fun `an unsupported report falls back without clearing the token`() {
|
||||
remote.put("one.ics", vtodo("a", "From the listing"))
|
||||
remote.changePages += ChangeSet.Unsupported
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(report.reconciledInFull).isTrue()
|
||||
assertThat(store.tokenWrites).doesNotContain(null)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- membership
|
||||
|
||||
@Test fun `a removal for an href we never had is a no-op`() {
|
||||
remote.changePages += page(removed = listOf("stranger.ics"), token = "urn:x:2")
|
||||
|
||||
val report = sync()
|
||||
|
||||
// Created and deleted between two syncs: reported as removed without ever
|
||||
// having been reported as added.
|
||||
assertThat(report.failure).isNull()
|
||||
assertThat(report.deletedLocally).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test fun `a removal we do know about deletes the rows`() {
|
||||
store.rows += task(id = 1, uid = "a")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e")
|
||||
remote.changePages += page(removed = listOf("one.ics"), token = "urn:x:2")
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(store.rows).isEmpty()
|
||||
assertThat(report.deletedLocally).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test fun `delete-then-recreate at the same href replaces the old task`() {
|
||||
store.rows += task(id = 1, uid = "old")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-old")
|
||||
remote.put("one.ics", vtodo("new", "A different task"), eTag = "e-new")
|
||||
remote.changePages += page(changed = listOf("one.ics"), token = "urn:x:2")
|
||||
|
||||
sync()
|
||||
|
||||
// ⚠️ Reported as a *change*, not as a removal plus an addition — so the
|
||||
// UID in the body is the only thing that says the old task is gone.
|
||||
assertThat(store.rows.map { it.uid }).containsExactly("new")
|
||||
}
|
||||
|
||||
@Test fun `a mass removal is refused and reconciled against a listing instead`() {
|
||||
(1..20).forEach { n ->
|
||||
store.rows += task(id = n.toLong(), uid = "u$n")
|
||||
.copy(href = "http://server/dav/tasks/$n.ics", etag = "e")
|
||||
remote.put("$n.ics", vtodo("u$n", "Task $n"))
|
||||
}
|
||||
remote.changePages += page(removed = (1..20).map { "$it.ics" }, token = "urn:x:2")
|
||||
|
||||
val report = sync()
|
||||
|
||||
// ⚠️ ACL churn arrives looking exactly like this. Acting on it deletes
|
||||
// the user's data on the strength of a change log.
|
||||
assertThat(report.incrementalNote).contains("removed 20 of 20")
|
||||
assertThat(report.reconciledInFull).isTrue()
|
||||
assertThat(store.rows).hasSize(20)
|
||||
}
|
||||
|
||||
@Test fun `a delete-and-recreate in one page keeps the row's local columns`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Old")
|
||||
.copy(
|
||||
href = "http://server/dav/tasks/one.ics",
|
||||
etag = "e-old",
|
||||
sortOrder = 5,
|
||||
color = 0x00FF00,
|
||||
)
|
||||
remote.put("two.ics", vtodo("a", "Same task, new file"), eTag = "e-new")
|
||||
remote.changePages += page(
|
||||
changed = listOf("two.ics"),
|
||||
removed = listOf("one.ics"),
|
||||
token = "urn:x:2",
|
||||
eTag = "e-new",
|
||||
)
|
||||
|
||||
val report = sync()
|
||||
|
||||
// ⚠️ Same UID, new filename. Purging `one.ics` before `two.ics` is
|
||||
// fetched re-inserts the task with sortOrder 0 and no colour, and
|
||||
// reports a deletion nobody asked for.
|
||||
val row = store.rows.single()
|
||||
assertThat(row.id).isEqualTo(1)
|
||||
assertThat(row.href).isEqualTo("http://server/dav/tasks/two.ics")
|
||||
assertThat(row.sortOrder).isEqualTo(5)
|
||||
assertThat(row.color).isEqualTo(0x00FF00)
|
||||
assertThat(report.deletedLocally).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test fun `an un-uploaded local edit is never downloaded over`() {
|
||||
remote.readOnly = true
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine, unsent")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-old", isDirty = true)
|
||||
remote.put("one.ics", vtodo("a", "Owner's version"), eTag = "e-new")
|
||||
remote.changePages += page(changed = listOf("one.ics"), token = "urn:x:2")
|
||||
|
||||
sync()
|
||||
|
||||
// The upload was refused because the share was demoted, so the row is
|
||||
// still dirty. Downloading over it destroys the edit with nothing in the
|
||||
// report to say so.
|
||||
assertThat(store.rows.single().title).isEqualTo("Mine, unsent")
|
||||
assertThat(store.rows.single().isDirty).isTrue()
|
||||
}
|
||||
|
||||
@Test fun `a stale removal never deletes what this run just wrote`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-one.ics", isDirty = true)
|
||||
remote.put("one.ics", vtodo("a", "Server copy"))
|
||||
// The change log predates our own upload in this same run.
|
||||
remote.changePages += page(removed = listOf("one.ics"), token = "urn:x:2")
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(remote.log).contains("UPDATE one.ics if-match=e-one.ics")
|
||||
assertThat(store.rows).hasSize(1)
|
||||
assertThat(report.deletedLocally).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test fun `a removal that loses a local edit says so`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine")
|
||||
.copy(href = "http://server/dav/tasks/gone.ics", etag = "e", isDirty = true)
|
||||
remote.onPut = { de.jeanlucmakiola.caldav.PutOutcome.Rejected(400, "no") }
|
||||
remote.changePages += page(removed = listOf("gone.ics"), token = "urn:x:2")
|
||||
|
||||
val report = sync()
|
||||
|
||||
assertThat(store.rows).isEmpty()
|
||||
assertThat(report.discardedEdits.single().cause)
|
||||
.isEqualTo(DiscardedEdit.Cause.DELETED_ON_SERVER)
|
||||
}
|
||||
|
||||
@Test fun `a fallback that succeeds is not reported as a failure`() {
|
||||
remote.put("one.ics", vtodo("a", "New"))
|
||||
remote.changePages += ChangeSet.Failed("HTTP 400")
|
||||
|
||||
val report = sync()
|
||||
|
||||
// The collection is reconciled and the user has nothing to act on, so
|
||||
// this must not surface as "last sync didn't finish".
|
||||
assertThat(report.failure).isNull()
|
||||
assertThat(report.incrementalNote).contains("400")
|
||||
assertThat(report.reconciledInFull).isTrue()
|
||||
assertThat(store.tokenWrites.last()).isEqualTo("urn:x:from-propfind")
|
||||
}
|
||||
|
||||
@Test fun `a refetch the change log never mentions still happens`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Mine").copy(isDirty = true)
|
||||
remote.onPut = { href -> de.jeanlucmakiola.caldav.PutOutcome.StoredNeedsRefetch(href) }
|
||||
remote.put("a.ics", vtodo("a", "Server's canonical form"))
|
||||
// A server need not echo our own write back to us.
|
||||
remote.changePages += page(token = "urn:x:2")
|
||||
|
||||
sync()
|
||||
|
||||
// Otherwise the row keeps a null ETag and never gets the canonical body.
|
||||
assertThat(store.rows.single().title).isEqualTo("Server's canonical form")
|
||||
}
|
||||
|
||||
@Test fun `a failed download never advances the cursor`() {
|
||||
remote.changePages += page(changed = listOf("one.ics"), token = "urn:x:2")
|
||||
remote.fetchFailure = "connection reset"
|
||||
|
||||
sync()
|
||||
|
||||
// ⚠️ A cursor committed past bodies that never landed is a permanent hole
|
||||
// in the collection, invisible until the next full reconciliation.
|
||||
assertThat(store.tokenWrites).doesNotContain("urn:x:2")
|
||||
}
|
||||
|
||||
@Test fun `a listed resource the server will not return is counted`() {
|
||||
remote.changePages += page(changed = listOf("ghost.ics"), token = "urn:x:2")
|
||||
|
||||
val report = sync()
|
||||
|
||||
// In the listing, so the sweep leaves it; never applied, so nothing else
|
||||
// would ever count it.
|
||||
assertThat(report.quarantined.single().reason).contains("listed but not returned")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- cadence
|
||||
|
||||
@Test fun `a due full reconciliation ignores the token entirely`() {
|
||||
remote.put("one.ics", vtodo("a", "New"))
|
||||
|
||||
val report = sync(fullDue = true)
|
||||
|
||||
// The pruned-change-log failure has no signal at all, so the full path is
|
||||
// a permanent safety net rather than a fallback.
|
||||
assertThat(remote.log).doesNotContain("CHANGES urn:x:1")
|
||||
assertThat(report.reconciledInFull).isTrue()
|
||||
}
|
||||
|
||||
@Test fun `a collection that does not advertise the report is never asked`() {
|
||||
remote.supportsSyncCollection = false
|
||||
remote.put("one.ics", vtodo("a", "New"))
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(remote.log.none { it.startsWith("CHANGES") }).isTrue()
|
||||
}
|
||||
|
||||
@Test fun `an unchanged etag in the change log is not downloaded`() {
|
||||
store.rows += task(id = 1, uid = "a", title = "Known")
|
||||
.copy(href = "http://server/dav/tasks/one.ics", etag = "e-one.ics")
|
||||
remote.put("one.ics", vtodo("a", "Known"))
|
||||
remote.changePages += page(changed = listOf("one.ics"), token = "urn:x:2", eTag = "e-one.ics")
|
||||
|
||||
sync()
|
||||
|
||||
assertThat(remote.log.none { it.startsWith("FETCH") }).isTrue()
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- setup
|
||||
|
||||
@Test fun `a deferred create is not overwritten by the change log`() {
|
||||
// A previous run's PUT landed but its answer was lost; the user has since
|
||||
// edited the task, so the row is dirty with no href.
|
||||
remote.put("a.ics", vtodo("a", "On the server"))
|
||||
store.rows += task(id = 1, uid = "a", title = "Edited after the lost PUT")
|
||||
.copy(isDirty = true)
|
||||
remote.changePages += page(changed = listOf("a.ics"), token = "urn:x:2")
|
||||
var failNext = true
|
||||
remote.onFetch = {
|
||||
if (failNext) {
|
||||
failNext = false
|
||||
Result.failure(IllegalStateException("timeout"))
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
sync()
|
||||
|
||||
// downloadChanged matches by href too, so a row with none is past its
|
||||
// dirty-row guard: without honouring `deferred` here, apply matches by
|
||||
// UID and the edit is gone with nothing in discardedEdits.
|
||||
val row = store.rows.single()
|
||||
assertThat(row.title).isEqualTo("Edited after the lost PUT")
|
||||
assertThat(row.isDirty).isTrue()
|
||||
assertThat(row.href).isNull()
|
||||
}
|
||||
|
||||
private fun page(
|
||||
changed: List<String> = emptyList(),
|
||||
removed: List<String> = emptyList(),
|
||||
token: String?,
|
||||
truncated: Boolean = false,
|
||||
eTag: String = "e-changed",
|
||||
) = ChangeSet.Page(
|
||||
changed = changed.map {
|
||||
RemoteRef("http://server/dav/tasks/$it".toHttpUrl(), ETag(eTag, weak = false))
|
||||
},
|
||||
removed = removed.map { "http://server/dav/tasks/$it".toHttpUrl() },
|
||||
token = token,
|
||||
truncated = truncated,
|
||||
)
|
||||
|
||||
private fun task(id: Long, uid: String, title: String? = null) =
|
||||
TaskEntity(id = id, listId = list.id, uid = uid, title = title)
|
||||
|
||||
private fun vtodo(uid: String, summary: String) =
|
||||
"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VTODO\r\nUID:$uid\r\n" +
|
||||
"SUMMARY:$summary\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"
|
||||
|
||||
private companion object {
|
||||
val NOW: Instant = Instant.parse("2026-03-01T12:00:00Z")
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import java.io.File
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** "Retry" on a quarantined task: one resource released, nothing else touched. */
|
||||
class QuarantineRetryTest {
|
||||
|
||||
@TempDir lateinit var directory: File
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
|
||||
|
||||
private val dataStore: DataStore<Preferences> by lazy {
|
||||
PreferenceDataStoreFactory.create(scope = scope) { File(directory, "sync.preferences_pb") }
|
||||
}
|
||||
|
||||
private val quarantine by lazy { QuarantineStore(dataStore) }
|
||||
private val notices by lazy { SyncNoticeStore(dataStore) }
|
||||
|
||||
@AfterEach fun tearDown() = scope.cancel()
|
||||
|
||||
@Test
|
||||
fun `releasing a resource clears only its count`() = runTest {
|
||||
quarantine.merge(
|
||||
updates = mapOf(
|
||||
QuarantineStore.key(1, BAD) to 3,
|
||||
QuarantineStore.key(1, OTHER) to 3,
|
||||
QuarantineStore.key(9, BAD) to 3,
|
||||
),
|
||||
cleared = emptySet(),
|
||||
)
|
||||
|
||||
quarantine.release(setOf(1, 2), BAD)
|
||||
|
||||
assertThat(quarantine.counts()).containsExactly(
|
||||
QuarantineStore.key(1, OTHER), 3,
|
||||
// Another account's list is not this retry's business.
|
||||
QuarantineStore.key(9, BAD), 3,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a retried quarantine notice goes, a discarded edit stays`() = runTest {
|
||||
notices.record(
|
||||
accountId = 1,
|
||||
at = Instant.fromEpochMilliseconds(1),
|
||||
reports = listOf(
|
||||
SyncReport(
|
||||
listId = 1,
|
||||
listName = "Tasks",
|
||||
discardedEdits = listOf(DiscardedEdit("u", "Milk", DiscardedEdit.Cause.SERVER_NEWER)),
|
||||
quarantined = listOf(
|
||||
QuarantinedResource(BAD, "415", QuarantineStore.THRESHOLD),
|
||||
QuarantinedResource(OTHER, "415", QuarantineStore.THRESHOLD),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
notices.forgetQuarantined(1, BAD)
|
||||
|
||||
val left = notices.observeAll().first()
|
||||
assertThat(left.map { it.key }).containsExactly("u", OTHER)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val BAD = "http://server/dav/tasks/bad.ics"
|
||||
const val OTHER = "http://server/dav/tasks/other.ics"
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.sync.SyncFailure.Kind
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
/** What the accounts screen says about `last_sync_error`, which is written for logs. */
|
||||
class SyncFailureTest {
|
||||
|
||||
@Test
|
||||
fun `a rejected credential asks for the password`() {
|
||||
assertThat(kind("collection unavailable: at.bitfire.dav4jvm.exception.UnauthorizedException: HTTP 401 Unauthorized"))
|
||||
.isEqualTo(Kind.SIGN_IN)
|
||||
assertThat(kind("the server rejected the credentials")).isEqualTo(Kind.SIGN_IN)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a network failure is unreachable`() {
|
||||
assertThat(kind("collection unavailable: java.net.UnknownHostException: Unable to resolve host \"cloud\""))
|
||||
.isEqualTo(Kind.UNREACHABLE)
|
||||
assertThat(kind("listing failed: java.net.SocketTimeoutException: timeout")).isEqualTo(Kind.UNREACHABLE)
|
||||
assertThat(kind("download failed: java.net.ConnectException: Failed to connect")).isEqualTo(Kind.UNREACHABLE)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a TLS failure is about the certificate`() {
|
||||
assertThat(
|
||||
kind("collection unavailable: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException"),
|
||||
).isEqualTo(Kind.CERTIFICATE)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a server error carries its code`() {
|
||||
val failure = SyncFailure.of("listing failed: at.bitfire.dav4jvm.exception.HttpException: HTTP 500 Internal Server Error")
|
||||
|
||||
assertThat(failure.kind).isEqualTo(Kind.SERVER)
|
||||
assertThat(failure.httpCode).isEqualTo(500)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a missing piece of the account is misconfiguration`() {
|
||||
assertThat(kind("account has no principal URL")).isEqualTo(Kind.MISCONFIGURED)
|
||||
assertThat(kind("list has no collection URL")).isEqualTo(Kind.MISCONFIGURED)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `anything else is not guessed at`() {
|
||||
assertThat(kind("the server listed no tasks while 4 are known here — nothing was deleted"))
|
||||
.isEqualTo(Kind.OTHER)
|
||||
}
|
||||
|
||||
private fun kind(error: String) = SyncFailure.of(error).kind
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
|
||||
import de.jeanlucmakiola.caldav.CalendarCollection
|
||||
import de.jeanlucmakiola.caldav.ChangeSet
|
||||
import de.jeanlucmakiola.caldav.DeleteOutcome
|
||||
import de.jeanlucmakiola.caldav.ETag
|
||||
import de.jeanlucmakiola.caldav.FetchResult
|
||||
import de.jeanlucmakiola.caldav.PushSupport
|
||||
import de.jeanlucmakiola.caldav.PutOutcome
|
||||
import de.jeanlucmakiola.caldav.RemoteCalendar
|
||||
import de.jeanlucmakiola.caldav.RemoteRef
|
||||
import de.jeanlucmakiola.caldav.RemoteResource
|
||||
import de.jeanlucmakiola.caldav.TaskCollection
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
|
||||
/** An in-memory [SyncStore], standing in for Room. */
|
||||
class FakeStore(rows: List<TaskEntity> = emptyList()) : SyncStore {
|
||||
|
||||
val rows = rows.toMutableList()
|
||||
val readOnlyWrites = mutableListOf<Pair<Long, Boolean>>()
|
||||
|
||||
/** In order, so a test can prove the token was stored *after* its bodies. */
|
||||
val tokenWrites = mutableListOf<String?>()
|
||||
private var nextId = 1L
|
||||
|
||||
override fun rowsIn(listId: Long) = this.rows.filter { it.listId == listId }
|
||||
|
||||
override fun insert(row: TaskEntity): Long {
|
||||
// Computed against the rows as they stand, not at construction: tests
|
||||
// seed `rows` directly after building this, and an id fixed up front
|
||||
// collides with the first seeded row — which then makes a delete of one
|
||||
// take the other with it.
|
||||
nextId = maxOf(nextId, (rows.maxOfOrNull { it.id } ?: 0L) + 1)
|
||||
val id = nextId++
|
||||
rows += row.copy(id = id)
|
||||
return id
|
||||
}
|
||||
|
||||
override fun update(row: TaskEntity) {
|
||||
val index = rows.indexOfFirst { it.id == row.id }
|
||||
if (index >= 0) rows[index] = row
|
||||
}
|
||||
|
||||
override fun deleteAll(taskIds: List<Long>) {
|
||||
rows.removeAll { it.id in taskIds }
|
||||
}
|
||||
|
||||
override fun markSynced(taskIds: List<Long>, href: String?, eTag: String?) {
|
||||
taskIds.forEach { id ->
|
||||
val index = rows.indexOfFirst { it.id == id }
|
||||
if (index >= 0) {
|
||||
rows[index] = rows[index].copy(href = href, etag = eTag, isDirty = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun setParent(taskId: Long, parentId: Long?) {
|
||||
val index = rows.indexOfFirst { it.id == taskId }
|
||||
if (index >= 0) rows[index] = rows[index].copy(parentId = parentId)
|
||||
}
|
||||
|
||||
override fun masterByUid(listId: Long, uid: String) =
|
||||
rows.firstOrNull { it.listId == listId && it.uid == uid && it.recurrenceId == null }
|
||||
|
||||
override fun row(taskId: Long) = rows.firstOrNull { it.id == taskId }
|
||||
|
||||
override fun setListReadOnly(listId: Long, readOnly: Boolean) {
|
||||
readOnlyWrites += listId to readOnly
|
||||
}
|
||||
|
||||
override fun setSyncToken(listId: Long, token: String?) {
|
||||
tokenWrites += token
|
||||
}
|
||||
}
|
||||
|
||||
/** An in-memory CalDAV collection that answers like a server rather than a mock. */
|
||||
class FakeRemote(override val url: HttpUrl = "http://server/dav/tasks/".toHttpUrl()) :
|
||||
RemoteCalendar {
|
||||
|
||||
data class Stored(var eTag: ETag?, var body: String)
|
||||
|
||||
val resources = linkedMapOf<String, Stored>()
|
||||
val log = mutableListOf<String>()
|
||||
|
||||
var readOnly = false
|
||||
var shared = false
|
||||
var supportsSyncCollection = false
|
||||
var syncToken: String? = null
|
||||
var push: PushSupport? = null
|
||||
|
||||
/** Pages the next `changes()` calls will return, in order. */
|
||||
val changePages = ArrayDeque<ChangeSet>()
|
||||
var stateFailure: String? = null
|
||||
var listFailure: String? = null
|
||||
var fetchFailure: String? = null
|
||||
|
||||
/** Returns non-null to pre-empt the default behaviour for that href. */
|
||||
var onPut: ((HttpUrl) -> PutOutcome?)? = null
|
||||
var onDelete: ((HttpUrl) -> DeleteOutcome?)? = null
|
||||
|
||||
/**
|
||||
* Returns non-null to pre-empt the default behaviour for that fetch.
|
||||
*
|
||||
* Unlike [fetchFailure], which breaks every fetch in the run, this can fail
|
||||
* one and leave the rest working — the difference between "the server is
|
||||
* down" and "this one request timed out".
|
||||
*/
|
||||
var onFetch: ((List<HttpUrl>) -> Result<FetchResult>?)? = null
|
||||
|
||||
fun put(name: String, body: String, eTag: String? = "e-$name") {
|
||||
resources[url.newBuilder().addPathSegment(name).build().toString()] =
|
||||
Stored(eTag?.let { ETag(it, weak = false) }, body)
|
||||
}
|
||||
|
||||
override fun state(): Result<CalendarCollection.State> {
|
||||
stateFailure?.let { return Result.failure(IllegalStateException(it)) }
|
||||
return Result.success(
|
||||
CalendarCollection.State(
|
||||
collection = TaskCollection(
|
||||
url = url,
|
||||
displayName = "Tasks",
|
||||
color = null,
|
||||
readOnly = readOnly,
|
||||
isShared = shared,
|
||||
supportsSyncCollection = supportsSyncCollection,
|
||||
maxResourceSize = null,
|
||||
push = push,
|
||||
),
|
||||
ctag = "ctag",
|
||||
syncToken = syncToken,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override fun changes(token: String?): ChangeSet {
|
||||
log += "CHANGES $token"
|
||||
return changePages.removeFirstOrNull()
|
||||
?: ChangeSet.Failed("the test queued no page for token $token")
|
||||
}
|
||||
|
||||
override fun list(): Result<List<RemoteRef>> {
|
||||
listFailure?.let { return Result.failure(IllegalStateException(it)) }
|
||||
log += "LIST"
|
||||
return Result.success(
|
||||
resources.map { (href, stored) -> RemoteRef(href.toHttpUrl(), stored.eTag) },
|
||||
)
|
||||
}
|
||||
|
||||
override fun fetch(hrefs: List<HttpUrl>): Result<FetchResult> {
|
||||
log += "FETCH ${hrefs.joinToString(",") { it.pathSegments.last() }}"
|
||||
onFetch?.invoke(hrefs)?.let { return it }
|
||||
fetchFailure?.let { return Result.failure(IllegalStateException(it)) }
|
||||
val found = hrefs.mapNotNull { href ->
|
||||
resources[href.toString()]?.let { RemoteResource(href, it.eTag, it.body) }
|
||||
}
|
||||
return Result.success(
|
||||
FetchResult(
|
||||
resources = found,
|
||||
missing = hrefs.filterNot { it.toString() in resources },
|
||||
failed = emptyList(),
|
||||
unsolicited = emptyList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override fun create(name: String, iCalendar: String): PutOutcome {
|
||||
val href = url.newBuilder().addPathSegment(name).build()
|
||||
log += "CREATE $name"
|
||||
onPut?.invoke(href)?.let { return it }
|
||||
if (href.toString() in resources) return PutOutcome.NameTaken(href)
|
||||
val eTag = ETag("e-$name", weak = false)
|
||||
resources[href.toString()] = Stored(eTag, iCalendar)
|
||||
return PutOutcome.Stored(href, eTag)
|
||||
}
|
||||
|
||||
override fun update(href: HttpUrl, eTag: String?, iCalendar: String): PutOutcome {
|
||||
log += "UPDATE ${href.pathSegments.last()} if-match=$eTag"
|
||||
onPut?.invoke(href)?.let { return it }
|
||||
val stored = resources[href.toString()] ?: return PutOutcome.Vanished
|
||||
if (eTag != null && stored.eTag?.value != eTag) return PutOutcome.ServerNewer
|
||||
val fresh = ETag("e-${resources.size}-${iCalendar.hashCode()}", weak = false)
|
||||
stored.eTag = fresh
|
||||
stored.body = iCalendar
|
||||
return PutOutcome.Stored(href, fresh)
|
||||
}
|
||||
|
||||
override fun delete(href: HttpUrl, eTag: String?): DeleteOutcome {
|
||||
log += "DELETE ${href.pathSegments.last()} if-match=$eTag"
|
||||
onDelete?.invoke(href)?.let { return it }
|
||||
val stored = resources[href.toString()] ?: return DeleteOutcome.Deleted
|
||||
if (eTag != null && stored.eTag?.value != eTag) return DeleteOutcome.ServerNewer
|
||||
resources.remove(href.toString())
|
||||
return DeleteOutcome.Deleted
|
||||
}
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import java.io.File
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* The two halves of "tell the user what the sync did".
|
||||
*
|
||||
* They are stored differently on purpose — one is news, the other a standing
|
||||
* condition — and getting that backwards either loses the news to the next quiet
|
||||
* sync or re-announces the same broken task every four hours for ever.
|
||||
*/
|
||||
class SyncNoticeStoreTest {
|
||||
|
||||
@TempDir lateinit var directory: File
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
|
||||
|
||||
private val dataStore: DataStore<Preferences> by lazy {
|
||||
PreferenceDataStoreFactory.create(scope = scope) { File(directory, "notices.preferences_pb") }
|
||||
}
|
||||
|
||||
private val store by lazy { SyncNoticeStore(dataStore) }
|
||||
|
||||
@AfterEach fun tearDown() = scope.cancel()
|
||||
|
||||
@Test
|
||||
fun `a discarded edit is kept when a later sync finds nothing`() = runTest {
|
||||
store.record(ACCOUNT, at(1), listOf(report(discarded = listOf(edit("Milk")))))
|
||||
store.record(ACCOUNT, at(2), listOf(report()))
|
||||
|
||||
// ⚠️ The edit is gone from the device either way. A clean sync an hour
|
||||
// later does not make that untrue, and replacing the set would erase the
|
||||
// one thing worth saying before anyone saw it.
|
||||
val kept = store.observeAll().first()
|
||||
assertThat(kept.map { it.subject }).containsExactly("Milk")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a resource that starts syncing again clears its own notice`() = runTest {
|
||||
store.record(ACCOUNT, at(1), listOf(report(quarantined = listOf(stuck("a.ics")))))
|
||||
store.record(ACCOUNT, at(2), listOf(report()))
|
||||
|
||||
// A standing condition, not news: it is re-reported for as long as it
|
||||
// holds, so the absence of a report *is* the recovery.
|
||||
assertThat(store.observeAll().first()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a resource still failing is not announced twice`() = runTest {
|
||||
val first = store.record(ACCOUNT, at(1), listOf(report(quarantined = listOf(stuck("a.ics")))))
|
||||
val second = store.record(ACCOUNT, at(2), listOf(report(quarantined = listOf(stuck("a.ics")))))
|
||||
|
||||
assertThat(first).hasSize(1)
|
||||
// Announcing it every four hours is how a user learns to ignore the one
|
||||
// that matters. It stays on the account screen throughout.
|
||||
assertThat(second).isEmpty()
|
||||
assertThat(store.observeAll().first()).hasSize(1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a resource below the threshold says nothing`() = runTest {
|
||||
val fresh = store.record(
|
||||
ACCOUNT,
|
||||
at(1),
|
||||
listOf(report(quarantined = listOf(stuck("a.ics", failures = 1)))),
|
||||
)
|
||||
|
||||
// Still being retried. "One of your tasks has stopped syncing" would be
|
||||
// untrue of a single 502 from a proxy mid-restart.
|
||||
assertThat(fresh).isEmpty()
|
||||
assertThat(store.observeAll().first()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two untitled edits in one run are both reported`() = runTest {
|
||||
store.record(
|
||||
ACCOUNT,
|
||||
at(1),
|
||||
listOf(report(discarded = listOf(edit(null, "uid-a"), edit(null, "uid-b")))),
|
||||
)
|
||||
|
||||
// ⚠️ These are stored as a Set<String>. Two discards from one run share
|
||||
// an account, a list, a cause and a timestamp, so without the UID in the
|
||||
// key they encoded identically and one silently vanished — the
|
||||
// notification counted two and the screen listed one.
|
||||
assertThat(store.observeAll().first()).hasSize(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two edits with the same title are both reported`() = runTest {
|
||||
store.record(
|
||||
ACCOUNT,
|
||||
at(1),
|
||||
listOf(report(discarded = listOf(edit("Milk", "uid-a"), edit("Milk", "uid-b")))),
|
||||
)
|
||||
|
||||
assertThat(store.observeAll().first()).hasSize(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a quarantined task is named by its title where one is known`() = runTest {
|
||||
val href = "https://server/dav/tasks/a1f9c3e2.ics"
|
||||
store.record(
|
||||
ACCOUNT,
|
||||
at(1),
|
||||
listOf(report(quarantined = listOf(stuck("a1f9c3e2.ics")))),
|
||||
titles = mapOf(href to "Renew the passport"),
|
||||
)
|
||||
|
||||
// "A task has stopped syncing" over a row reading `a1f9c3e2.ics` names
|
||||
// nothing the user can act on — the same objection this file makes to
|
||||
// showing a UID.
|
||||
assertThat(store.observeAll().first().single().subject).isEqualTo("Renew the passport")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a quarantined resource we never stored falls back to its filename`() = runTest {
|
||||
store.record(ACCOUNT, at(1), listOf(report(quarantined = listOf(stuck("a1f9c3e2.ics")))))
|
||||
|
||||
// Nothing local to name it by, so the filename is genuinely all there is.
|
||||
assertThat(store.observeAll().first().single().subject).isEqualTo("a1f9c3e2.ics")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `titles and list names survive whatever characters they contain`() = runTest {
|
||||
store.record(
|
||||
ACCOUNT,
|
||||
at(1),
|
||||
listOf(
|
||||
report(
|
||||
listName = "Work | Home",
|
||||
discarded = listOf(edit("Pay the bill | urgent")),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
// A list is named by its owner and a task titled by its author, so both
|
||||
// can hold the separator this store writes with.
|
||||
val notice = store.observeAll().first().single()
|
||||
assertThat(notice.subject).isEqualTo("Pay the bill | urgent")
|
||||
assertThat(notice.listName).isEqualTo("Work | Home")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `one account's notices leave another's alone`() = runTest {
|
||||
store.record(ACCOUNT, at(1), listOf(report(discarded = listOf(edit("Milk")))))
|
||||
store.record(OTHER, at(1), listOf(report(discarded = listOf(edit("Bread")))))
|
||||
store.dismiss(ACCOUNT)
|
||||
|
||||
assertThat(store.observeAll().first().map { it.subject }).containsExactly("Bread")
|
||||
}
|
||||
|
||||
private fun report(
|
||||
listName: String = "Tasks",
|
||||
discarded: List<DiscardedEdit> = emptyList(),
|
||||
quarantined: List<QuarantinedResource> = emptyList(),
|
||||
) = SyncReport(
|
||||
listId = 1,
|
||||
listName = listName,
|
||||
discardedEdits = discarded,
|
||||
quarantined = quarantined,
|
||||
)
|
||||
|
||||
private fun edit(title: String?, uid: String = "uid-$title") =
|
||||
DiscardedEdit(uid = uid, title = title, cause = DiscardedEdit.Cause.SERVER_NEWER)
|
||||
|
||||
private fun stuck(href: String, failures: Int = QuarantineStore.THRESHOLD) =
|
||||
QuarantinedResource(href = "https://server/dav/tasks/$href", reason = "415", failures = failures)
|
||||
|
||||
private fun at(seconds: Long) = Instant.fromEpochMilliseconds(seconds * 1_000)
|
||||
|
||||
private companion object {
|
||||
const val ACCOUNT = 1L
|
||||
const val OTHER = 2L
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.data.sync.push
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.caldav.PushSupport
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import java.io.File
|
||||
import kotlin.time.Instant
|
||||
|
||||
class PushStoreTest {
|
||||
|
||||
@TempDir lateinit var directory: File
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
|
||||
|
||||
private val dataStore: DataStore<Preferences> by lazy {
|
||||
PreferenceDataStoreFactory.create(scope = scope) { File(directory, "push.preferences_pb") }
|
||||
}
|
||||
|
||||
private val store by lazy { PushStore(dataStore) }
|
||||
|
||||
@AfterEach fun tearDown() = scope.cancel()
|
||||
|
||||
@Test
|
||||
fun `support and subscription survive a round trip, separators and all`() = runTest {
|
||||
// Server-chosen strings: nothing stops a topic or a URL carrying the
|
||||
// separator the entries are joined with.
|
||||
val support = PushSupport(topic = "a|b c", vapidPublicKey = "BA1H_x-y")
|
||||
store.recordSupport(mapOf(1L to support))
|
||||
store.recordSubscription(
|
||||
listId = 1,
|
||||
subscription = "https://dav.example.com/subs/1?x=|",
|
||||
endpoint = "https://up.example.net/abc",
|
||||
expires = Instant.fromEpochSeconds(1_800_000_000),
|
||||
)
|
||||
|
||||
assertThat(store.all()[1]).isEqualTo(
|
||||
PushStore.ListPush(
|
||||
listId = 1,
|
||||
support = support,
|
||||
subscription = "https://dav.example.com/subs/1?x=|",
|
||||
endpoint = "https://up.example.net/abc",
|
||||
expires = Instant.fromEpochSeconds(1_800_000_000),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only a change in support is reported as one`() = runTest {
|
||||
val support = PushSupport(topic = "t", vapidPublicKey = null)
|
||||
|
||||
assertThat(store.recordSupport(mapOf(1L to support))).isTrue()
|
||||
assertThat(store.recordSupport(mapOf(1L to support))).isFalse()
|
||||
// A rotated VAPID key is a change: it needs a new registration.
|
||||
assertThat(store.recordSupport(mapOf(1L to support.copy(vapidPublicKey = "new")))).isTrue()
|
||||
// Nothing known, nothing offered: no change either.
|
||||
assertThat(store.recordSupport(mapOf(2L to null))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `losing support keeps the subscription until it is removed`() = runTest {
|
||||
store.recordSupport(mapOf(1L to PushSupport(topic = "t", vapidPublicKey = null)))
|
||||
store.recordSubscription(1, "https://dav/subs/1", "https://up/1", Instant.fromEpochSeconds(1))
|
||||
|
||||
store.recordSupport(mapOf(1L to null))
|
||||
|
||||
// Still here, so the registrar can find it and tell the server.
|
||||
assertThat(store.all()[1]?.subscription).isEqualTo("https://dav/subs/1")
|
||||
|
||||
store.clearSubscription(1)
|
||||
assertThat(store.all()).doesNotContainKey(1L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `forgetting a list leaves the others alone`() = runTest {
|
||||
store.recordSupport(
|
||||
mapOf(
|
||||
1L to PushSupport(topic = "one", vapidPublicKey = null),
|
||||
2L to PushSupport(topic = "two", vapidPublicKey = null),
|
||||
),
|
||||
)
|
||||
|
||||
store.forget(setOf(1L))
|
||||
|
||||
assertThat(store.all().keys).containsExactly(2L)
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,17 @@ class TaskWriteMapperTest {
|
||||
assertThat(undone[Tasks.COMPLETED]).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `category row carries only the name, so the provider resolves the category itself`() {
|
||||
val values = TaskWriteMapper.categoryValues(taskId = 12L, name = "Work")
|
||||
|
||||
assertThat(values).containsExactly(
|
||||
TasksContract.Properties.TASK_ID, 12L,
|
||||
TasksContract.Properties.MIMETYPE, "vnd.android.cursor.item/category",
|
||||
TasksContract.Category.NAME, "Work",
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `alarm carries every column the provider's validator demands`() {
|
||||
val values = TaskWriteMapper.alarmValues(taskId = 12L, minutesBeforeDue = 30)
|
||||
|
||||
@@ -303,6 +303,65 @@ class VTodoMapperTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
inner class Categories {
|
||||
|
||||
@Test
|
||||
fun `a single plain line is claimed into the column`() {
|
||||
val mapped = VTodoMapper.read(vtodo("CATEGORIES:Work,Home\\, Garden"))
|
||||
assertThat(mapped.entity.categories).containsExactly("Work", "Home, Garden").inOrder()
|
||||
assertThat(mapped.entity.unknownProperties.orEmpty()).doesNotContain("CATEGORIES")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `several lines are read but round-trip from the residue`() {
|
||||
val mapped = VTodoMapper.read(vtodo("CATEGORIES:Work", "CATEGORIES:Errands"))
|
||||
assertThat(mapped.entity.categories).containsExactly("Work", "Errands").inOrder()
|
||||
|
||||
val written = VTodoMapper.write(mapped.entity).properties("CATEGORIES").map { it.value }
|
||||
assertThat(written).containsExactly("Work", "Errands")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a line the column would not reproduce exactly stays in the residue`() {
|
||||
val mapped = VTodoMapper.read(vtodo("CATEGORIES;LANGUAGE=de:Arbeit", "SUMMARY:x"))
|
||||
assertThat(mapped.entity.categories).containsExactly("Arbeit")
|
||||
assertThat(VTodoMapper.read(vtodo("CATEGORIES:a, b")).entity.unknownProperties)
|
||||
.contains("CATEGORIES:a, b")
|
||||
|
||||
val written = VTodoMapper.write(mapped.entity).properties("CATEGORIES")
|
||||
assertThat(written.single().param("LANGUAGE")).isEqualTo("de")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `editing the tags evicts the residue copies and authors one line`() {
|
||||
val mapped = VTodoMapper.read(vtodo("CATEGORIES:Work", "CATEGORIES:Errands"))
|
||||
val edited = mapped.entity.copy(categories = listOf("Work", "Home"))
|
||||
|
||||
val written = VTodoMapper.write(edited).properties("CATEGORIES")
|
||||
assertThat(written.single().value).isEqualTo("Work,Home")
|
||||
assertThat(written.single().params).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no tags writes no line`() {
|
||||
assertThat(VTodoMapper.write(entity()).properties("CATEGORIES")).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a duplicated or blank tag is dropped and the line stays in the residue`() {
|
||||
val mapped = VTodoMapper.read(vtodo("CATEGORIES:Work, ,Work"))
|
||||
assertThat(mapped.entity.categories).containsExactly("Work")
|
||||
assertThat(VTodoMapper.write(mapped.entity).properties("CATEGORIES").single().value).isEqualTo("Work, ,Work")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unclean column is cleaned on the way out`() {
|
||||
val written = VTodoMapper.write(entity().copy(categories = listOf(" a ", "", "a", "b")))
|
||||
assertThat(written.properties("CATEGORIES").single().value).isEqualTo("a,b")
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
inner class Validation {
|
||||
|
||||
|
||||
@@ -39,6 +39,8 @@ class VTodoRoundTripTest {
|
||||
"mixed-value-types",
|
||||
"malformed-scalars",
|
||||
"two-timezones",
|
||||
"categories-shapes",
|
||||
"categories-split",
|
||||
)
|
||||
|
||||
@TestFactory
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package de.jeanlucmakiola.agendula.data.tasks.room
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class CategoriesLiftTest {
|
||||
|
||||
@Test
|
||||
fun `claims a lone plain line and keeps the rest of the residue`() {
|
||||
val result = CategoriesLift.lift("X-FOO:bar\r\nCATEGORIES:Work,Home\r\n")
|
||||
assertThat(result.categories).containsExactly("Work", "Home").inOrder()
|
||||
assertThat(result.claimed).isTrue()
|
||||
assertThat(result.residue).contains("X-FOO:bar")
|
||||
assertThat(result.residue).doesNotContain("CATEGORIES")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a residue that was only the line becomes null`() {
|
||||
assertThat(CategoriesLift.lift("CATEGORIES:Work\r\n").residue).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `several lines are read but not claimed`() {
|
||||
val residue = "CATEGORIES:a\r\nCATEGORIES:b\r\n"
|
||||
val result = CategoriesLift.lift(residue)
|
||||
assertThat(result.categories).containsExactly("a", "b").inOrder()
|
||||
assertThat(result.claimed).isFalse()
|
||||
assertThat(result.residue).isEqualTo(residue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `nothing to lift from an empty residue`() {
|
||||
assertThat(CategoriesLift.lift(null)).isEqualTo(CategoriesLift.Result(emptyList(), null, claimed = false))
|
||||
}
|
||||
}
|
||||
@@ -50,4 +50,12 @@ class ConvertersTest {
|
||||
}
|
||||
assertThat(Converters.alarmReferenceFrom("NONSENSE")).isEqualTo(AlarmReference.DUE)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `categories round-trip with escaped commas and come back cleaned`() {
|
||||
val stored = CategoriesConverter.toText(listOf("a,b", " c ", "", "c"))
|
||||
assertThat(stored).isEqualTo("a\\,b,c")
|
||||
assertThat(CategoriesConverter.fromText(stored)).containsExactly("a,b", "c").inOrder()
|
||||
assertThat(CategoriesConverter.fromText("")).isEmpty()
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ private fun form(
|
||||
start: Instant? = null,
|
||||
due: Instant? = null,
|
||||
isAllDay: Boolean = false,
|
||||
tags: List<String> = emptyList(),
|
||||
) = TaskForm(
|
||||
title = title,
|
||||
listId = 1,
|
||||
@@ -36,6 +37,7 @@ private fun form(
|
||||
start = start,
|
||||
due = due,
|
||||
isAllDay = isAllDay,
|
||||
tags = tags,
|
||||
)
|
||||
|
||||
class TaskFormWriterTest {
|
||||
@@ -51,6 +53,12 @@ class TaskFormWriterTest {
|
||||
assertThat(entity.isDirty).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tags are trimmed and blanks dropped`() {
|
||||
val entity = TaskFormWriter.apply(task(), form(tags = listOf(" Work ", "", " ", "Home")), NOW, ZONE)
|
||||
assertThat(entity.categories).containsExactly("Work", "Home").inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `progress and status move together in both directions`() {
|
||||
assertThat(TaskFormWriter.apply(task(), form(percentComplete = 100), NOW, ZONE).status)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
class SavedFilterTest {
|
||||
|
||||
private val dayMs = 86_400_000L
|
||||
private val todayStart = Instant.fromEpochMilliseconds(1000 * dayMs)
|
||||
private val todayEnd = Instant.fromEpochMilliseconds(1001 * dayMs)
|
||||
private val overdue = Instant.fromEpochMilliseconds(999 * dayMs)
|
||||
private val today = Instant.fromEpochMilliseconds(1000 * dayMs + 1)
|
||||
private val upcoming = Instant.fromEpochMilliseconds(1002 * dayMs)
|
||||
|
||||
private fun SavedFilter.matches(task: Task) = matches(task, todayStart, todayEnd)
|
||||
|
||||
private val empty = SavedFilter(id = 1, name = "f")
|
||||
|
||||
@Test
|
||||
fun `an empty filter is every open task`() {
|
||||
assertThat(empty.matches(testTask(due = null))).isTrue()
|
||||
assertThat(empty.matches(testTask(due = overdue))).isTrue()
|
||||
assertThat(empty.matches(testTask(status = TaskStatus.COMPLETED))).isFalse()
|
||||
assertThat(empty.matches(testTask(status = TaskStatus.CANCELLED))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `today and overdue together`() {
|
||||
val filter = empty.copy(due = setOf(DueWindow.TODAY, DueWindow.OVERDUE))
|
||||
assertThat(filter.matches(testTask(due = overdue))).isTrue()
|
||||
assertThat(filter.matches(testTask(due = today))).isTrue()
|
||||
assertThat(filter.matches(testTask(due = upcoming))).isFalse()
|
||||
assertThat(filter.matches(testTask(due = null))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lists narrow by membership`() {
|
||||
val filter = empty.copy(listIds = setOf(2L, 3L))
|
||||
assertThat(filter.matches(testTask(listId = 2))).isTrue()
|
||||
assertThat(filter.matches(testTask(listId = 1))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lists from another store match nothing here`() {
|
||||
val filter = empty.copy(listsElsewhere = true)
|
||||
assertThat(filter.matches(testTask(listId = 1))).isFalse()
|
||||
assertThat(filter.copy(listIds = setOf(1L)).matches(testTask(listId = 1))).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `priority is a floor`() {
|
||||
val filter = empty.copy(minPriority = Priority.MEDIUM)
|
||||
assertThat(filter.matches(testTask(priority = Priority.HIGH))).isTrue()
|
||||
assertThat(filter.matches(testTask(priority = Priority.MEDIUM))).isTrue()
|
||||
assertThat(filter.matches(testTask(priority = Priority.LOW))).isFalse()
|
||||
assertThat(filter.matches(testTask(priority = Priority.NONE))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tags match any or all`() {
|
||||
val any = empty.copy(tags = setOf("work", "home"))
|
||||
val all = any.copy(tagMatch = TagMatch.ALL)
|
||||
val one = testTask(tags = listOf("work"))
|
||||
val both = testTask(tags = listOf("home", "work", "x"))
|
||||
assertThat(any.matches(one)).isTrue()
|
||||
assertThat(any.matches(testTask(tags = listOf("x")))).isFalse()
|
||||
assertThat(all.matches(one)).isFalse()
|
||||
assertThat(all.matches(both)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `criteria combine with and`() {
|
||||
val filter = empty.copy(due = setOf(DueWindow.TODAY), listIds = setOf(1L), tags = setOf("work"))
|
||||
assertThat(filter.matches(testTask(listId = 1, due = today, tags = listOf("work")))).isTrue()
|
||||
assertThat(filter.matches(testTask(listId = 2, due = today, tags = listOf("work")))).isFalse()
|
||||
assertThat(filter.matches(testTask(listId = 1, due = today))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an all-day due is read as its date west of utc`() {
|
||||
val zone = ZoneId.of("America/New_York")
|
||||
val date = LocalDate.of(2026, 10, 10)
|
||||
val start = Instant.fromEpochMilliseconds(date.atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
val end = Instant.fromEpochMilliseconds(date.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
fun window(d: LocalDate) = dueWindowOf(testTask(due = allDayInstantOf(d), isAllDay = true), start, end, zone)
|
||||
assertThat(window(date)).isEqualTo(DueWindow.TODAY)
|
||||
assertThat(window(date.plusDays(1))).isEqualTo(DueWindow.UPCOMING)
|
||||
assertThat(window(date.minusDays(1))).isEqualTo(DueWindow.OVERDUE)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new task preset lands in its filter`() {
|
||||
val day = LocalDate.of(2026, 10, 10)
|
||||
val filter = empty.copy(
|
||||
due = setOf(DueWindow.UPCOMING),
|
||||
tags = setOf("work", "home"),
|
||||
tagMatch = TagMatch.ALL,
|
||||
minPriority = Priority.HIGH,
|
||||
)
|
||||
val preset = filter.newTaskPreset(day)
|
||||
assertThat(preset.dueDate).isEqualTo(day.plusDays(1))
|
||||
assertThat(preset.tags).containsExactly("home", "work")
|
||||
assertThat(preset.priority).isEqualTo(Priority.HIGH)
|
||||
assertThat(empty.copy(due = setOf(DueWindow.TODAY, DueWindow.UPCOMING)).newTaskPreset(day).dueDate).isEqualTo(day)
|
||||
assertThat(empty.copy(due = setOf(DueWindow.TODAY, DueWindow.NO_DATE)).newTaskPreset(day).dueDate).isNull()
|
||||
assertThat(empty.copy(tags = setOf("b", "a")).newTaskPreset(day).tags).containsExactly("a")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lists since deleted drop out`() {
|
||||
val filter = empty.copy(listIds = setOf(1L, 5L))
|
||||
assertThat(filter.withListsIn(setOf(1L, 2L)).listIds).containsExactly(1L)
|
||||
assertThat(filter.withListsIn(setOf(2L)).anyList).isTrue()
|
||||
assertThat(filter.copy(listsElsewhere = true).withListsIn(setOf(2L)).anyList).isFalse()
|
||||
}
|
||||
}
|
||||
@@ -58,4 +58,32 @@ class TaskFilteringTest {
|
||||
assertThat(TaskFiltering.matches(task, TaskFilter.OfList(7), todayStart, todayEnd)).isTrue()
|
||||
assertThat(TaskFiltering.matches(task, TaskFilter.OfList(8), todayStart, todayEnd)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Tagged matches open and completed tasks carrying the tag`() {
|
||||
val filter = TaskFilter.Tagged("Work")
|
||||
assertThat(TaskFiltering.matches(testTask(tags = listOf("Home", "Work")), filter, todayStart, todayEnd)).isTrue()
|
||||
assertThat(
|
||||
TaskFiltering.matches(testTask(tags = listOf("Work"), status = TaskStatus.COMPLETED), filter, todayStart, todayEnd),
|
||||
).isTrue()
|
||||
assertThat(TaskFiltering.matches(testTask(tags = listOf("work")), filter, todayStart, todayEnd)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `narrowing by tags needs every one of them`() {
|
||||
val task = testTask(tags = listOf("Home", "Work"))
|
||||
assertThat(TaskFiltering.hasAllTags(task, emptySet())).isTrue()
|
||||
assertThat(TaskFiltering.hasAllTags(task, setOf("Work"))).isTrue()
|
||||
assertThat(TaskFiltering.hasAllTags(task, setOf("Work", "Home"))).isTrue()
|
||||
assertThat(TaskFiltering.hasAllTags(task, setOf("Work", "Errands"))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tags in use are listed once each, alphabetically ignoring case`() {
|
||||
val tasks = listOf(
|
||||
testTask(id = 1, tags = listOf("work", "Home")),
|
||||
testTask(id = 2, tags = listOf("Home", "errands")),
|
||||
)
|
||||
assertThat(tagsInUse(tasks)).containsExactly("errands", "Home", "work").inOrder()
|
||||
}
|
||||
}
|
||||
@@ -44,4 +44,16 @@ class TaskFormTest {
|
||||
assertThat(TaskForm(title = "x", listId = 1, percentComplete = 30, parentId = 9).populatedFields())
|
||||
.containsExactly(TaskFormField.Progress, TaskFormField.Parent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tags auto-reveal when the task has any`() {
|
||||
assertThat(TaskForm(title = "x", listId = 1, tags = listOf("Work")).populatedFields())
|
||||
.containsExactly(TaskFormField.Tags)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tags are normalised to trimmed, non-blank, unique spellings in order`() {
|
||||
assertThat(normalizeTags(listOf(" Work", "", "Home ", "Work", "work")))
|
||||
.containsExactly("Work", "Home", "work").inOrder()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,10 @@ fun testTask(
|
||||
status: TaskStatus = TaskStatus.NEEDS_ACTION,
|
||||
priority: Priority = Priority.NONE,
|
||||
due: Instant? = null,
|
||||
isAllDay: Boolean = false,
|
||||
completedAt: Instant? = null,
|
||||
parentId: Long? = null,
|
||||
tags: List<String> = emptyList(),
|
||||
): Task = Task(
|
||||
taskId = id,
|
||||
listId = listId,
|
||||
@@ -22,17 +26,18 @@ fun testTask(
|
||||
percentComplete = null,
|
||||
start = null,
|
||||
due = due,
|
||||
isAllDay = false,
|
||||
isAllDay = isAllDay,
|
||||
timeZone = null,
|
||||
completedAt = null,
|
||||
completedAt = completedAt,
|
||||
listColor = 0,
|
||||
taskColor = null,
|
||||
listName = null,
|
||||
accountName = null,
|
||||
parentId = null,
|
||||
parentId = parentId,
|
||||
isRecurring = false,
|
||||
occurrenceStart = null,
|
||||
distanceFromCurrent = 0,
|
||||
created = null,
|
||||
lastModified = null,
|
||||
tags = tags,
|
||||
)
|
||||
@@ -35,9 +35,10 @@ class ICalendarWriterTest {
|
||||
rrule: String? = null,
|
||||
rdate: String? = null,
|
||||
parentId: Long? = null,
|
||||
tags: List<String> = emptyList(),
|
||||
) = ExportTask(
|
||||
taskId, uid, title, description, location, url, priority, status, percentComplete,
|
||||
start, due, isAllDay, completedAt, created, lastModified, rrule, rdate, parentId,
|
||||
start, due, isAllDay, completedAt, created, lastModified, rrule, rdate, parentId, tags,
|
||||
)
|
||||
|
||||
private fun write(vararg tasks: ExportTask, name: String = "Groceries"): String =
|
||||
@@ -59,6 +60,13 @@ class ICalendarWriterTest {
|
||||
assertThat(lines).containsAtLeast("VERSION:2.0", "BEGIN:VTODO", "END:VTODO")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `writes the tags as one CATEGORIES line, escaped`() {
|
||||
val lines = linesOf(write(task(tags = listOf("Work", "Home, Garden"))))
|
||||
assertThat(lines).contains("CATEGORIES:Work,Home\\, Garden")
|
||||
assertThat(linesOf(write(task())).none { it.startsWith("CATEGORIES") }).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `uses CRLF line endings`() {
|
||||
// RFC 5545 requires CRLF. Bare LF is the classic way an .ics is rejected
|
||||
|
||||
-1330
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
package de.jeanlucmakiola.agendula.ui.navigation
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class DestinationsTest {
|
||||
@@ -17,4 +18,13 @@ class DestinationsTest {
|
||||
assertThat(Dest.Settings.build()).isEqualTo(Dest.SETTINGS)
|
||||
assertThat(Dest.Settings.build(Dest.Settings.SECTION_ACCOUNTS)).isEqualTo("settings?section=Accounts")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a saved filter routes by id and comes back from its arguments`() {
|
||||
assertThat(Dest.TaskList.build(TaskFilter.Saved(5))).isEqualTo("taskList?filterId=5")
|
||||
assertThat(Dest.TaskList.filterOf(smart = null, listId = Dest.NO_ID, filterId = 5)).isEqualTo(TaskFilter.Saved(5))
|
||||
assertThat(Dest.FilterEdit.build()).isEqualTo("filterEdit")
|
||||
assertThat(Dest.FilterEdit.build(5)).isEqualTo("filterEdit?filterId=5")
|
||||
assertThat(Dest.TaskEdit.buildNew(filterId = 5)).isEqualTo("taskEdit?filterId=5")
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
package de.jeanlucmakiola.agendula.widget
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import de.jeanlucmakiola.floret.glance.WidgetBackground
|
||||
import de.jeanlucmakiola.floret.glance.WidgetThemeMode
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
@@ -27,7 +30,10 @@ class WidgetDataTest {
|
||||
|
||||
@Test
|
||||
fun `every offered filter round-trips through storage`() {
|
||||
val filters = WIDGET_SMART_LISTS.map { TaskFilter.Smart(it) } + TaskFilter.OfList(42)
|
||||
val filters = WIDGET_SMART_LISTS.map { TaskFilter.Smart(it) } +
|
||||
TaskFilter.OfList(42) +
|
||||
TaskFilter.OfLists(setOf(1L, 2L, 3L)) +
|
||||
TaskFilter.Saved(7)
|
||||
filters.forEach { assertThat(parseWidgetFilter(it.widgetStorageValue())).isEqualTo(it) }
|
||||
}
|
||||
|
||||
@@ -38,7 +44,10 @@ class WidgetDataTest {
|
||||
|
||||
@Test
|
||||
fun `garbage and smart lists the widget does not offer fall back to Today`() {
|
||||
listOf("", "list:", "list:-3", "list:abc", "smart:COMPLETED", "smart:nope", "whatever").forEach {
|
||||
listOf(
|
||||
"", "list:", "list:-3", "list:abc", "lists:", "lists:abc", "lists:-1,-2",
|
||||
"smart:COMPLETED", "smart:nope", "filter:", "filter:0", "filter:x", "whatever",
|
||||
).forEach {
|
||||
assertThat(parseWidgetFilter(it)).isEqualTo(DEFAULT_WIDGET_FILTER)
|
||||
}
|
||||
}
|
||||
@@ -80,6 +89,8 @@ class WidgetDataTest {
|
||||
TaskSorting.DEFAULT,
|
||||
now,
|
||||
newYork,
|
||||
groupByList = false,
|
||||
listNames = emptyMap(),
|
||||
)
|
||||
assertThat(rows.map { it.title }).containsExactly("soon", "later").inOrder()
|
||||
}
|
||||
@@ -89,13 +100,135 @@ class WidgetDataTest {
|
||||
val parent = testTask(id = 1, title = "parent")
|
||||
val child = testTask(id = 2, title = "child").copy(parentId = 1)
|
||||
val orphan = testTask(id = 3, title = "orphan").copy(parentId = 99)
|
||||
val rows = widgetRows(listOf(parent, child, orphan), TaskSorting.DEFAULT, now, newYork)
|
||||
val rows = widgetRows(
|
||||
listOf(parent, child, orphan),
|
||||
TaskSorting.DEFAULT,
|
||||
now,
|
||||
newYork,
|
||||
groupByList = false,
|
||||
listNames = emptyMap(),
|
||||
)
|
||||
assertThat(rows.map { it.title }).containsExactly("parent", "orphan")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rows are capped`() {
|
||||
val many = (1L..(MAX_WIDGET_ROWS + 10L)).map { testTask(id = it, title = "t$it") }
|
||||
assertThat(widgetRows(many, TaskSorting.DEFAULT, now, newYork)).hasSize(MAX_WIDGET_ROWS)
|
||||
assertThat(
|
||||
widgetRows(many, TaskSorting.DEFAULT, now, newYork, groupByList = false, listNames = emptyMap()),
|
||||
).hasSize(MAX_WIDGET_ROWS)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `grouping sorts by list name, keeping each list's own order`() {
|
||||
val tasks = listOf(
|
||||
testTask(id = 1, listId = 2, title = "b-later", due = at("2026-07-22T09:00:00")),
|
||||
testTask(id = 2, listId = 1, title = "a-soon", due = at("2026-07-20T15:00:00")),
|
||||
testTask(id = 3, listId = 1, title = "a-later", due = at("2026-07-22T09:00:00")),
|
||||
)
|
||||
val rows = widgetRows(
|
||||
tasks,
|
||||
TaskSorting.DEFAULT,
|
||||
now,
|
||||
newYork,
|
||||
groupByList = true,
|
||||
listNames = mapOf(1L to "Alpha", 2L to "Beta"),
|
||||
)
|
||||
assertThat(rows.map { it.title }).containsExactly("a-soon", "a-later", "b-later").inOrder()
|
||||
}
|
||||
|
||||
// --- sections ----------------------------------------------------------
|
||||
|
||||
private fun row(id: Long, listId: Long = 1, dueKind: DueKind? = null, overdue: Boolean = false) = WidgetTaskRow(
|
||||
taskId = id,
|
||||
listId = listId,
|
||||
occurrenceStart = null,
|
||||
title = "t$id",
|
||||
due = null,
|
||||
isAllDay = false,
|
||||
dueKind = dueKind,
|
||||
isOverdue = overdue,
|
||||
color = 0,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `due buckets appear in a fixed order and skip empty ones`() {
|
||||
val rows = listOf(
|
||||
row(1, dueKind = DueKind.LATER),
|
||||
row(2, dueKind = DueKind.PAST, overdue = true),
|
||||
row(3, dueKind = DueKind.TODAY),
|
||||
)
|
||||
val sections = widgetSections(rows, groupByList = false, listNames = emptyMap()) { it?.name ?: "none" }
|
||||
assertThat(sections.filterIsInstance<WidgetSection.Header>().map { it.name })
|
||||
.containsExactly("PAST", "TODAY", "LATER").inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a bucket's rows keep their own order under its one header`() {
|
||||
val rows = listOf(row(1, dueKind = DueKind.TODAY), row(2, dueKind = DueKind.TODAY), row(3, dueKind = DueKind.TODAY))
|
||||
val sections = widgetSections(rows, groupByList = false, listNames = emptyMap()) { "x" }
|
||||
assertThat(sections.filterIsInstance<WidgetSection.Header>()).hasSize(1)
|
||||
assertThat(sections.filterIsInstance<WidgetSection.TaskItem>().map { it.row.taskId }).containsExactly(1L, 2L, 3L).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `grouping by list keeps the widgetRows order and headers each run once`() {
|
||||
val rows = listOf(row(1, listId = 1), row(2, listId = 1), row(3, listId = 2))
|
||||
val sections = widgetSections(rows, groupByList = true, listNames = mapOf(1L to "Alpha", 2L to "Beta")) { "x" }
|
||||
assertThat(sections.filterIsInstance<WidgetSection.Header>().map { it.name }).containsExactly("Alpha", "Beta").inOrder()
|
||||
assertThat(sections.filterIsInstance<WidgetSection.TaskItem>().map { it.row.taskId }).containsExactly(1L, 2L, 3L).inOrder()
|
||||
}
|
||||
|
||||
// --- per-widget background / theme --------------------------------------
|
||||
|
||||
@Test
|
||||
fun `an unset background is Solid, and round-trips`() {
|
||||
assertThat(parseWidgetBackground(null)).isEqualTo(WidgetBackground.SOLID)
|
||||
WidgetBackground.entries.forEach { assertThat(parseWidgetBackground(it.name)).isEqualTo(it) }
|
||||
assertThat(parseWidgetBackground("garbage")).isEqualTo(WidgetBackground.SOLID)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unset theme override follows the app, Light and Dark pin regardless`() {
|
||||
assertThat(parseWidgetThemeOverride(null)).isNull()
|
||||
assertThat(parseWidgetThemeOverride("garbage")).isNull()
|
||||
assertThat(parseWidgetThemeOverride("LIGHT")).isEqualTo(WidgetThemeMode.LIGHT)
|
||||
assertThat(parseWidgetThemeOverride("DARK")).isEqualTo(WidgetThemeMode.DARK)
|
||||
}
|
||||
|
||||
private fun readyWithTheme(appTheme: ThemeMode) = TaskWidgetData.Ready(
|
||||
filter = DEFAULT_WIDGET_FILTER,
|
||||
listNames = emptyMap(),
|
||||
rows = emptyList(),
|
||||
groupByList = false,
|
||||
dynamicColor = true,
|
||||
themeMode = appTheme,
|
||||
use24Hour = true,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `no override resolves to whatever the app's own theme means`() {
|
||||
assertThat(readyWithTheme(ThemeMode.DARK).effectiveThemeMode(null)).isEqualTo(WidgetThemeMode.DARK)
|
||||
assertThat(readyWithTheme(ThemeMode.SYSTEM).effectiveThemeMode(null)).isEqualTo(WidgetThemeMode.SYSTEM)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an override wins over the app's own theme`() {
|
||||
assertThat(readyWithTheme(ThemeMode.DARK).effectiveThemeMode(WidgetThemeMode.LIGHT)).isEqualTo(WidgetThemeMode.LIGHT)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unset row colour is Neutral, and round-trips`() {
|
||||
assertThat(parseWidgetRowColor(null)).isEqualTo(WidgetRowColor.NEUTRAL)
|
||||
WidgetRowColor.entries.forEach { assertThat(parseWidgetRowColor(it.name)).isEqualTo(it) }
|
||||
assertThat(parseWidgetRowColor("garbage")).isEqualTo(WidgetRowColor.NEUTRAL)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `overdue count only counts overdue rows`() {
|
||||
val ready = readyWithTheme(ThemeMode.SYSTEM).copy(
|
||||
rows = listOf(row(1, overdue = true), row(2, overdue = false), row(3, overdue = true)),
|
||||
)
|
||||
assertThat(ready.overdueCount).isEqualTo(2)
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.widget
|
||||
|
||||
import android.content.Intent
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.atStartOfDayIn
|
||||
import kotlinx.datetime.toInstant
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.hours
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** The "when is the next local midnight" arithmetic, especially where midnight is not 00:00. */
|
||||
class WidgetRolloverSchedulerTest {
|
||||
|
||||
private val berlin = TimeZone.of("Europe/Berlin")
|
||||
|
||||
private fun at(local: String, zone: TimeZone): Instant =
|
||||
LocalDateTime.parse(local).toInstant(zone)
|
||||
|
||||
private fun nextRollover(local: String, zone: TimeZone = berlin): Instant =
|
||||
WidgetRolloverScheduler.nextRolloverAt(at(local, zone), zone)
|
||||
|
||||
// --- the ordinary day ----------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `midday rolls over at the coming midnight`() {
|
||||
val next = nextRollover("2026-08-27T12:00:00")
|
||||
assertThat(next).isEqualTo(at("2026-08-28T00:00:05", berlin))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a second before midnight still targets tonight, not tomorrow night`() {
|
||||
val next = nextRollover("2026-08-27T23:59:59")
|
||||
assertThat(next).isEqualTo(at("2026-08-28T00:00:05", berlin))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `at midnight exactly the target is the next day, never the current instant`() {
|
||||
// Re-arming after a firing must move a whole day on, or the widget wakes
|
||||
// itself in a tight loop.
|
||||
val now = at("2026-08-28T00:00:00", berlin)
|
||||
val next = WidgetRolloverScheduler.nextRolloverAt(now, berlin)
|
||||
assertThat(next).isEqualTo(at("2026-08-29T00:00:05", berlin))
|
||||
assertThat(next - now).isGreaterThan(Duration.ZERO)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `re-arming from the slack instant itself moves a full day on`() {
|
||||
// What actually happens in practice: the receiver runs at midnight + slack.
|
||||
val now = at("2026-08-28T00:00:05", berlin)
|
||||
assertThat(WidgetRolloverScheduler.nextRolloverAt(now, berlin))
|
||||
.isEqualTo(at("2026-08-29T00:00:05", berlin))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the result is always in the future for every minute of a day`() {
|
||||
val zone = berlin
|
||||
// Spans Berlin's 2024 spring-forward: the likeliest source of a target
|
||||
// in the past, i.e. an alarm that fires immediately, forever.
|
||||
var probe = LocalDateTime.parse("2024-03-29T00:00:00").toInstant(zone)
|
||||
val end = LocalDateTime.parse("2024-04-01T00:00:00").toInstant(zone)
|
||||
while (probe < end) {
|
||||
assertThat(WidgetRolloverScheduler.nextRolloverAt(probe, zone)).isGreaterThan(probe)
|
||||
probe += 1.minutes
|
||||
}
|
||||
}
|
||||
|
||||
// --- daylight saving -----------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `spring forward keeps the rollover one day away, not one hour short`() {
|
||||
// Berlin skipped 02:00-03:00 on 31 March 2024, so that day was 23h long.
|
||||
// A rollover computed as "now + 24h" would land at 01:00 on 1 April.
|
||||
val now = at("2024-03-30T12:00:00", berlin)
|
||||
val next = WidgetRolloverScheduler.nextRolloverAt(now, berlin)
|
||||
assertThat(next).isEqualTo(at("2024-03-31T00:00:05", berlin))
|
||||
assertThat(next - now).isLessThan(24.hours)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fall back does not overshoot into the repeated hour`() {
|
||||
// Berlin repeated 02:00-03:00 on 27 October 2024: a 25h day, so
|
||||
// "now + 24h" would land at 23:00 on the 26th and never roll over.
|
||||
val now = at("2024-10-26T12:00:00", berlin)
|
||||
val next = WidgetRolloverScheduler.nextRolloverAt(now, berlin)
|
||||
assertThat(next).isEqualTo(at("2024-10-27T00:00:05", berlin))
|
||||
assertThat(next.toLocalDateTime(berlin).date).isEqualTo(LocalDate.parse("2024-10-27"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a zone that repeats midnight takes the first start of day`() {
|
||||
// Sao Paulo used to end DST by moving 00:00 back to 23:00, so the day
|
||||
// began twice. Pinned as the accepted trade: the widget runs an hour
|
||||
// ahead until the next redraw. No live zone does this since 2019.
|
||||
val saoPaulo = TimeZone.of("America/Sao_Paulo")
|
||||
val next = WidgetRolloverScheduler.nextRolloverAt(
|
||||
at("2018-02-16T12:00:00", saoPaulo), saoPaulo,
|
||||
)
|
||||
val local = next.toLocalDateTime(saoPaulo)
|
||||
assertThat(local.date).isEqualTo(LocalDate.parse("2018-02-17"))
|
||||
assertThat(local.hour).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a zone where midnight does not exist rolls over at the real start of day`() {
|
||||
// Cuba starts DST at 00:00, so 11 March 2018 began at 01:00 in Havana.
|
||||
// Targeting a literal 00:00 there would arm an instant on the wrong day.
|
||||
val havana = TimeZone.of("America/Havana")
|
||||
val next = WidgetRolloverScheduler.nextRolloverAt(at("2018-03-10T12:00:00", havana), havana)
|
||||
val local = next.toLocalDateTime(havana)
|
||||
assertThat(local.date).isEqualTo(LocalDate.parse("2018-03-11"))
|
||||
assertThat(local.hour).isEqualTo(1)
|
||||
assertThat(local.minute).isEqualTo(0)
|
||||
// And it is genuinely the first instant of that date, not a guess.
|
||||
assertThat(next).isEqualTo(
|
||||
LocalDate.parse("2018-03-11").atStartOfDayIn(havana) +
|
||||
WidgetRolloverScheduler.ROLLOVER_SLACK,
|
||||
)
|
||||
}
|
||||
|
||||
// --- timezone changes ----------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `the same instant rolls over at different times in different zones`() {
|
||||
// TIMEZONE_CHANGED must re-arm to the new local midnight: the arithmetic
|
||||
// follows the zone, not a cached offset.
|
||||
val instant = at("2026-08-27T12:00:00", berlin)
|
||||
val tokyo = TimeZone.of("Asia/Tokyo")
|
||||
val berlinNext = WidgetRolloverScheduler.nextRolloverAt(instant, berlin)
|
||||
val tokyoNext = WidgetRolloverScheduler.nextRolloverAt(instant, tokyo)
|
||||
assertThat(tokyoNext).isNotEqualTo(berlinNext)
|
||||
assertThat(tokyoNext).isLessThan(berlinNext)
|
||||
assertThat(tokyoNext.toLocalDateTime(tokyo).hour).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a half-hour offset zone still lands on its own midnight`() {
|
||||
val kathmandu = TimeZone.of("Asia/Kathmandu")
|
||||
val next = WidgetRolloverScheduler.nextRolloverAt(
|
||||
at("2026-08-27T12:00:00", kathmandu), kathmandu,
|
||||
)
|
||||
val local = next.toLocalDateTime(kathmandu)
|
||||
assertThat(local.date.toString()).isEqualTo("2026-08-28")
|
||||
assertThat(local.hour).isEqualTo(0)
|
||||
}
|
||||
|
||||
// --- the wiring ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `the receiver actually handles the action the alarm is sent with`() {
|
||||
// The single point where the whole fix would die silently: the alarm
|
||||
// fires, the receiver drops it on the action guard, nothing redraws.
|
||||
assertThat(WidgetUpdateReceiver.HANDLED_ACTIONS)
|
||||
.contains(WidgetUpdateReceiver.ACTION_ROLLOVER)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a language change redraws without re-arming`() {
|
||||
assertThat(WidgetUpdateReceiver.HANDLED_ACTIONS).contains(Intent.ACTION_LOCALE_CHANGED)
|
||||
assertThat(WidgetUpdateReceiver.REARM_ACTIONS).doesNotContain(Intent.ACTION_LOCALE_CHANGED)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `everything that loses the alarm re-arms it`() {
|
||||
assertThat(WidgetUpdateReceiver.REARM_ACTIONS).containsAtLeast(
|
||||
WidgetUpdateReceiver.ACTION_ROLLOVER,
|
||||
Intent.ACTION_BOOT_COMPLETED,
|
||||
Intent.ACTION_MY_PACKAGE_REPLACED,
|
||||
Intent.ACTION_TIME_CHANGED,
|
||||
Intent.ACTION_TIMEZONE_CHANGED,
|
||||
Intent.ACTION_DATE_CHANGED,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package de.jeanlucmakiola.agendula.widget
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
import de.jeanlucmakiola.agendula.domain.comparator
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
class WidgetStatsTest {
|
||||
|
||||
private val newYork = ZoneId.of("America/New_York")
|
||||
private val today = LocalDate.of(2026, 7, 20)
|
||||
private val comparator = TaskSortOrder.DUE.comparator()
|
||||
|
||||
private fun at(local: String, zone: ZoneId = newYork): Instant =
|
||||
Instant.fromEpochMilliseconds(LocalDateTime.parse(local).atZone(zone).toInstant().toEpochMilli())
|
||||
|
||||
private val now = at("2026-07-20T12:00:00")
|
||||
|
||||
// --- todayProgress ---------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `a task completed today counts as done, one completed yesterday does not`() {
|
||||
val completed = listOf(
|
||||
testTask(id = 1, status = TaskStatus.COMPLETED, completedAt = at("2026-07-20T09:00:00")),
|
||||
testTask(id = 2, status = TaskStatus.COMPLETED, completedAt = at("2026-07-19T23:00:00")),
|
||||
)
|
||||
val (done, _, _) = todayProgress(emptyList(), completed, comparator, now, today, newYork)
|
||||
assertThat(done).isEqualTo(1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an all-day task due today and an overdue timed task both count as remaining`() {
|
||||
val open = listOf(
|
||||
testTask(id = 1, due = allDayInstantOf(today), isAllDay = true),
|
||||
testTask(id = 2, due = at("2026-07-20T08:00:00")), // already past `now` (12:00)
|
||||
testTask(id = 3, due = at("2026-07-21T08:00:00")), // tomorrow, not remaining
|
||||
)
|
||||
val (_, remaining, _) = todayProgress(open, emptyList(), comparator, now, today, newYork)
|
||||
assertThat(remaining).isEqualTo(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an earlier-due remaining task sorts ahead of a later one`() {
|
||||
val open = listOf(
|
||||
testTask(id = 1, due = at("2026-07-20T11:00:00")), // overdue, closer to now
|
||||
testTask(id = 2, due = at("2026-07-20T07:00:00")), // more overdue, earliest
|
||||
)
|
||||
val (_, _, rows) = todayProgress(open, emptyList(), comparator, now, today, newYork)
|
||||
assertThat(rows.map { it.taskId }).containsExactly(2L, 1L).inOrder()
|
||||
}
|
||||
|
||||
// --- upcoming ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `upcoming sorts by due, overdue first, and skips undated ones`() {
|
||||
val open = listOf(
|
||||
testTask(id = 1, due = null),
|
||||
testTask(id = 2, due = at("2026-07-21T08:00:00")),
|
||||
testTask(id = 3, due = at("2026-07-20T08:00:00")), // overdue, earliest
|
||||
)
|
||||
assertThat(upcoming(open, now, today, newYork).map { it.taskId }).containsExactly(3L, 2L).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `upcoming is empty when nothing is dated`() {
|
||||
assertThat(upcoming(listOf(testTask(due = null)), now, today, newYork)).isEmpty()
|
||||
}
|
||||
|
||||
// --- weekDays ------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `today's bucket folds in overdue tasks from earlier days`() {
|
||||
val open = listOf(
|
||||
testTask(id = 1, due = at("2026-07-18T08:00:00")), // two days overdue
|
||||
testTask(id = 2, due = at("2026-07-20T08:00:00")), // due today, already past now
|
||||
)
|
||||
val week = weekDays(open, comparator, now, today, newYork)
|
||||
assertThat(week.first().date).isEqualTo(today)
|
||||
assertThat(week.first().count).isEqualTo(2)
|
||||
assertThat(week.first().overdueCount).isEqualTo(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a future day only counts tasks due that exact day`() {
|
||||
val open = listOf(
|
||||
testTask(id = 1, due = at("2026-07-22T08:00:00")),
|
||||
testTask(id = 2, due = at("2026-07-23T08:00:00")),
|
||||
)
|
||||
val week = weekDays(open, comparator, now, today, newYork)
|
||||
assertThat(week[2].count).isEqualTo(1) // today + 2 = 07-22
|
||||
assertThat(week[2].overdueCount).isEqualTo(0)
|
||||
assertThat(week[3].count).isEqualTo(1) // today + 3 = 07-23
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a day at the far edge of daylight saving still buckets by local date`() {
|
||||
// Spans the US spring-forward boundary; only exercised to confirm
|
||||
// calendarDate (not a raw day-of-year add) drives the bucketing.
|
||||
val dstToday = LocalDate.of(2026, 3, 7)
|
||||
val dstNow = at("2026-03-07T12:00:00")
|
||||
val open = listOf(testTask(id = 1, due = at("2026-03-08T08:00:00")))
|
||||
val week = weekDays(open, comparator, dstNow, dstToday, newYork)
|
||||
assertThat(week[1].date).isEqualTo(LocalDate.of(2026, 3, 8))
|
||||
assertThat(week[1].count).isEqualTo(1)
|
||||
}
|
||||
|
||||
// --- listTiles -------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun `listTiles counts open tasks per visible list and skips a subtask whose parent is also open`() {
|
||||
val lists = listOf(
|
||||
TaskList(1, "Home", 0, "a", "t", false, isVisible = true, owner = null),
|
||||
TaskList(2, "Hidden", 0, "a", "t", false, isVisible = false, owner = null),
|
||||
)
|
||||
val open = listOf(
|
||||
testTask(id = 1, listId = 1),
|
||||
testTask(id = 2, listId = 1, parentId = 1), // subtask of an open parent
|
||||
testTask(id = 3, listId = 2),
|
||||
)
|
||||
val tiles = listTiles(open, lists)
|
||||
assertThat(tiles).hasSize(1)
|
||||
assertThat(tiles.single().id).isEqualTo(1L)
|
||||
assertThat(tiles.single().openCount).isEqualTo(1)
|
||||
}
|
||||
}
|
||||
@@ -30,3 +30,5 @@ VTIMEZONE bodies, fold positions, parameter quoting).
|
||||
| `malformed-scalars.ics` | `PRIORITY:11`, `PERCENT-COMPLETE:150`, `SEQUENCE:x`, `STATUS:X-DEFERRED`, `CLASS:X-INTERNAL` — values no spec allows. Clamping or defaulting any of them is a silent rewrite of somebody's data |
|
||||
| `two-timezones.ics` | `DTSTART` and `DUE` in different zones. One `timezone` column cannot author both |
|
||||
| `folded-utf8.ics` | A line folded mid-emoji-adjacent, to prove folding counts octets and splits on character boundaries |
|
||||
| `categories-shapes.ics` | One `CATEGORIES` line with an escaped comma inside a value — the one shape the column claims, so it is re-authored and must come out identical |
|
||||
| `categories-split.ics` | One line per tag, a `LANGUAGE` parameter and a space after a comma. Read for display, but none of it is ours to rewrite |
|
||||
@@ -0,0 +1,10 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Several Clients//EN
|
||||
BEGIN:VTODO
|
||||
UID:categories-001
|
||||
DTSTAMP:20260901T120000Z
|
||||
SUMMARY:One line, an escaped comma
|
||||
CATEGORIES:Work,Home\, Garden
|
||||
END:VTODO
|
||||
END:VCALENDAR
|
||||
@@ -0,0 +1,12 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Several Clients//EN
|
||||
BEGIN:VTODO
|
||||
UID:categories-002
|
||||
DTSTAMP:20260901T120000Z
|
||||
SUMMARY:One line per tag, one with a language
|
||||
CATEGORIES:Errands
|
||||
CATEGORIES;LANGUAGE=de:Einkauf
|
||||
CATEGORIES:a, b
|
||||
END:VTODO
|
||||
END:VCALENDAR
|
||||
Reference in new issue
Block a user