Skip to content

Commit

Permalink
Merge pull request #80 from opatry/tasks-repo-unit-tests
Browse files Browse the repository at this point in the history
`TaskRepository` basic unit tests
  • Loading branch information
opatry authored Oct 28, 2024
2 parents b23d2ef + 68ffa8a commit 7f4684a
Show file tree
Hide file tree
Showing 10 changed files with 541 additions and 1 deletion.
3 changes: 3 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ androidx-room-compiler = { module = "androidx.room:room-compiler", version.ref =
androidx-room-common = { module = "androidx.room:room-common", version.ref = "room" }
androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "room" }
androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" }
androidx-room-testing = { module = "androidx.room:room-testing", version.ref = "room" }

jetbrains-lifecycle-viewmodel-compose = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose", version = "2.8.0" }
jetbrains-navigation-compose = { module = "org.jetbrains.androidx.navigation:navigation-compose", version = "2.8.0-alpha10" }
Expand Down Expand Up @@ -70,6 +71,8 @@ play-services-auth = { module = "com.google.android.gms:play-services-auth", ver

about-libraries-core = { module = "com.mikepenz:aboutlibraries-core", version.ref = "about-libraries" }

androidx-test-core = { module = "androidx.test:core", version = "1.6.1" }

[bundles]
ktor-server = ["ktor-server-core", "ktor-server-cio"]
ktor-client = [
Expand Down
11 changes: 10 additions & 1 deletion tasks-app-shared/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,20 @@ kotlin {

@OptIn(ExperimentalComposeLibrary::class)
implementation(compose.uiTest)

implementation(libs.ktor.client.mock)
implementation(libs.kotlinx.coroutines.test)
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.testing)
}

jvmTest.dependencies {
implementation(compose.desktop.currentOs)
}

androidInstrumentedTest.dependencies {
implementation(libs.androidx.test.core)
}
}
}

Expand All @@ -133,7 +142,7 @@ android {
testOptions {
unitTests {
all {
it.exclude("**/ui/**")
it.exclude("**/ui/**", "**/data/**")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2024 Olivier Patry
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package net.opatry.tasks.data.util

import android.content.Context
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.test.core.app.ApplicationProvider
import net.opatry.tasks.data.TasksAppDatabase

actual fun inMemoryTasksAppDatabaseBuilder(): RoomDatabase.Builder<TasksAppDatabase> {
val context = ApplicationProvider.getApplicationContext<Context>()
return Room.inMemoryDatabaseBuilder(context, TasksAppDatabase::class.java)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2024 Olivier Patry
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package net.opatry.tasks.data.util

import androidx.room.RoomDatabase
import net.opatry.tasks.data.TasksAppDatabase

actual fun inMemoryTasksAppDatabaseBuilder(): RoomDatabase.Builder<TasksAppDatabase> {
// not expected to run as Android unit test any time soon
// can only rely on Android context in either Robolectric or Instrumentation tests
TODO()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
* Copyright (c) 2024 Olivier Patry
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package net.opatry.tasks.data

import kotlinx.coroutines.flow.firstOrNull
import net.opatry.tasks.data.model.TaskDataModel
import net.opatry.tasks.data.model.TaskListDataModel
import net.opatry.tasks.data.util.runTaskRepositoryTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

private suspend fun TaskRepository.createAndGetTaskList(title: String): TaskListDataModel {
createTaskList(title)
return getTaskLists().firstOrNull()?.firstOrNull() ?: error("Task list not found")
}

private suspend fun TaskRepository.createAndGetTask(taskListId: Long, taskTitle: String): TaskDataModel {
createTask(taskListId, taskTitle)
return getTaskLists().firstOrNull()
?.firstOrNull { it.id == taskListId }
?.tasks
?.firstOrNull { it.title == taskTitle }
?: error("Task not found")
}

private suspend fun TaskRepository.createAndGetTask(taskListTitle: String, taskTitle: String): Pair<TaskListDataModel, TaskDataModel> {
val taskList = createAndGetTaskList(taskListTitle)
return taskList to createAndGetTask(taskList.id, taskTitle)
}

class TaskRepositoryCRUDTest {

@Test
fun `create task list`() = runTaskRepositoryTest { repository ->
repository.createTaskList("My tasks")

val taskLists = repository.getTaskLists().firstOrNull()
assertEquals(1, taskLists?.size)
assertEquals("My tasks", taskLists?.first()?.title)
}

@Test
fun `rename task list`() = runTaskRepositoryTest { repository ->
val taskList = repository.createAndGetTaskList("My tasks")

repository.renameTaskList(taskList.id, "My renamed list")
val taskListRenamed = repository.getTaskLists().firstOrNull()?.firstOrNull()
assertEquals("My renamed list", taskListRenamed?.title, "Updated name is invalid")
}

@Test
fun `delete task list`() = runTaskRepositoryTest { repository ->
val taskList = repository.createAndGetTaskList("My tasks")

repository.deleteTaskList(taskList.id)
val taskLists = repository.getTaskLists().firstOrNull()
assertEquals(0, taskLists?.size, "No task list expected")
}

@Test
fun `create task`() = runTaskRepositoryTest { repository ->
val taskList = repository.createAndGetTaskList("My tasks")

repository.createTask(taskList.id, "My task")
val tasks = repository.getTaskLists().firstOrNull()?.firstOrNull()?.tasks
assertEquals(1, tasks?.size)
assertEquals("My task", tasks?.first()?.title)
assertFalse(tasks?.first()?.isCompleted ?: true)
}

@Test
fun `rename task`() = runTaskRepositoryTest { repository ->
val (_, task) = repository.createAndGetTask("My tasks", "My task")

repository.updateTaskTitle(task.id, "My renamed task")
val tasks = repository.getTaskLists().firstOrNull()?.firstOrNull()?.tasks
assertEquals("My renamed task", tasks?.first()?.title)
}

@Test
fun `edit task notes`() = runTaskRepositoryTest { repository ->
val (_, task) = repository.createAndGetTask("My tasks", "My task")

repository.updateTaskNotes(task.id, "These are some notes")
val tasks = repository.getTaskLists().firstOrNull()?.firstOrNull()?.tasks
assertEquals("These are some notes", tasks?.first()?.notes)
}

@Test
fun `complete task`() = runTaskRepositoryTest { repository ->
val (_, task) = repository.createAndGetTask("My tasks", "My task")

repository.toggleTaskCompletionState(task.id)
val tasks = repository.getTaskLists().firstOrNull()?.firstOrNull()?.tasks
assertTrue(tasks?.first()?.isCompleted ?: false)
}

@Test
fun `delete task`() = runTaskRepositoryTest { repository ->
val (_, task) = repository.createAndGetTask("My tasks", "My task")

repository.deleteTask(task.id)
val tasks = repository.getTaskLists().firstOrNull()?.firstOrNull()?.tasks
assertEquals(0, tasks?.size, "Task should have been deleted")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
* Copyright (c) 2024 Olivier Patry
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package net.opatry.tasks.data

import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respondError
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import kotlinx.coroutines.flow.firstOrNull
import net.opatry.tasks.data.model.TaskListDataModel
import net.opatry.tasks.data.util.respondNoNetwork
import net.opatry.tasks.data.util.respondWithTaskLists
import net.opatry.tasks.data.util.respondWithTasks
import net.opatry.tasks.data.util.runTaskRepositoryTest
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.fail


class TaskRepositorySyncTest {
@Test
fun `sync remote task lists`() {
MockEngine { request ->
when (val encodedPath = request.url.encodedPath) {
"/tasks/v1/users/@me/lists" -> respondWithTaskLists(
"MTAwNDEyMDI1NDY0NDEwNzQ0NDI6MDow" to "My tasks",
"OXl0d1JibXgyeW1zWWFIMw" to "Other tasks"
)

"/tasks/v1/lists/MTAwNDEyMDI1NDY0NDEwNzQ0NDI6MDow/tasks" -> respondWithTasks("dnBVd2IwZUlMcjZWNU84YQ" to "First task TODO")
"/tasks/v1/lists/OXl0d1JibXgyeW1zWWFIMw/tasks" -> respondWithTasks("M3R6eUVFQzJJUzQzZC12Qg" to "Another task")
else -> fail("Unexpected request: $request ($encodedPath)")
}
}.use { mockEngine ->
runTaskRepositoryTest(mockEngine) { repository ->
val initialTaskLists = repository.getTaskLists().firstOrNull()
assertEquals(0, initialTaskLists?.size, "There shouldn't be any task list at start")
repository.sync()

val taskLists = repository.getTaskLists().firstOrNull()
assertEquals(2, taskLists?.size)
assertContentEquals(listOf("My tasks", "Other tasks"), taskLists?.map(TaskListDataModel::title))

val firstTaskListTasks = taskLists?.get(0)?.tasks
assertEquals(1, firstTaskListTasks?.size)
assertEquals("First task TODO", firstTaskListTasks?.firstOrNull()?.title)

val secondTaskListTasks = taskLists?.get(1)?.tasks
assertEquals(1, secondTaskListTasks?.size)
assertEquals("Another task", secondTaskListTasks?.firstOrNull()?.title)
}
}
}

@Test
fun `backend error while syncing should do nothing`() {
MockEngine {
respondError(HttpStatusCode.Forbidden)
}.use { mockEngine ->
runTaskRepositoryTest(mockEngine) { repository ->
repository.sync()
assertEquals(0, repository.getTaskLists().firstOrNull()?.size)
}

assertEquals(1, mockEngine.responseHistory.size)
assertEquals(HttpStatusCode.Forbidden, mockEngine.responseHistory.first().statusCode)
}
}

@Test
fun `task CRUD without network should create a local only task`() {
MockEngine {
respondNoNetwork()
}.use { mockEngine ->
runTaskRepositoryTest(mockEngine) { repository ->
repository.createTaskList("Task list")
assertEquals(1, repository.getTaskLists().firstOrNull()?.size)
}

assertEquals(0, mockEngine.responseHistory.size)
}
}

@Test
fun `local only tasks are synced at next sync`() {
var requestCount = 0
MockEngine { request ->
++requestCount
when {
requestCount == 1
&& request.method == HttpMethod.Post
&& request.url.encodedPath == "/tasks/v1/users/@me/lists"
-> respondNoNetwork()

requestCount == 2
&& request.method == HttpMethod.Get
&& request.url.encodedPath == "/tasks/v1/users/@me/lists"
-> respondWithTaskLists()

requestCount == 3
&& request.method == HttpMethod.Post
&& request.url.encodedPath == "/tasks/v1/users/@me/lists"
-> respondWithTaskLists("MTAwNDEyMDI1NDY0NDEwNzQ0NDI6MDow" to "Task list")

else -> fail("Unexpected request: $request")
}
}.use { mockEngine ->
runTaskRepositoryTest(mockEngine) { repository ->
// for first request, no network
repository.createTaskList("Task list")
val taskList = repository.getTaskLists().firstOrNull()?.firstOrNull()
assertNotNull(taskList)
assertEquals(0, mockEngine.responseHistory.size)

// network is considered back, sync should trigger fetch & push requests
repository.sync()
assertEquals(2, mockEngine.responseHistory.size)
}
}
}
}
Loading

0 comments on commit 7f4684a

Please sign in to comment.