Skip to content

Commit

Permalink
Update Ktlint + Ktlint plugin + fix formatting after update
Browse files Browse the repository at this point in the history
  • Loading branch information
findjigar committed Sep 29, 2023
1 parent af61b5a commit 93f6080
Show file tree
Hide file tree
Showing 16 changed files with 114 additions and 60 deletions.
2 changes: 2 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[*.{kt,kts}]
ktlint_code_style = android_studio
2 changes: 0 additions & 2 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ subprojects {
apply(plugin = rootProject.libs.plugins.ktlint.get().pluginId)

configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
version.set("1.0.0")
enableExperimentalRules.set(true)
verbose.set(true)
filter {
Expand Down
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ compileSdk = "34"
kotlin = "1.9.10"

android-gradle-plugin = "8.1.1"
ktlint-gradle = "11.4.2"
ktlint-gradle = "11.6.0"

compose = "1.5.2"
composeCompiler = "1.5.3"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import android.content.Context
import androidx.test.core.app.ApplicationProvider.getApplicationContext
import androidx.test.ext.junit.runners.AndroidJUnit4
import co.touchlab.kermit.Logger
import kotlin.test.AfterTest
import kotlin.test.Test
import org.junit.experimental.categories.Category
import org.junit.runner.RunWith
import org.koin.core.context.stopKoin
Expand All @@ -13,8 +15,6 @@ import org.koin.dsl.module
import org.koin.test.category.CheckModuleTest
import org.koin.test.check.checkModules
import org.robolectric.annotation.Config
import kotlin.test.AfterTest
import kotlin.test.Test

@RunWith(AndroidJUnit4::class)
@Category(CheckModuleTest::class)
Expand Down
22 changes: 10 additions & 12 deletions shared/src/commonMain/kotlin/co/touchlab/kampkit/DatabaseHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@ class DatabaseHelper(
) {
private val dbRef: KaMPKitDb = KaMPKitDb(sqlDriver)

fun selectAllItems(): Flow<List<Breed>> =
dbRef.tableQueries
.selectAll()
.asFlow()
.mapToList(Dispatchers.Default)
.flowOn(backgroundDispatcher)
fun selectAllItems(): Flow<List<Breed>> = dbRef.tableQueries
.selectAll()
.asFlow()
.mapToList(Dispatchers.Default)
.flowOn(backgroundDispatcher)

suspend fun insertBreeds(breeds: List<String>) {
log.d { "Inserting ${breeds.size} breeds into database" }
Expand All @@ -35,12 +34,11 @@ class DatabaseHelper(
}
}

fun selectById(id: Long): Flow<List<Breed>> =
dbRef.tableQueries
.selectById(id)
.asFlow()
.mapToList(Dispatchers.Default)
.flowOn(backgroundDispatcher)
fun selectById(id: Long): Flow<List<Breed>> = dbRef.tableQueries
.selectById(id)
.asFlow()
.mapToList(Dispatchers.Default)
.flowOn(backgroundDispatcher)

suspend fun deleteAll() {
log.i { "Database Cleared" }
Expand Down
3 changes: 2 additions & 1 deletion shared/src/commonMain/kotlin/co/touchlab/kampkit/Koin.kt
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ private val coreModule = module {
// uses you *may* want to have a more robust configuration from the native platform. In KaMP Kit,
// that would likely go into platformModule expect/actual.
// See https://github.com/touchlab/Kermit
val baseLogger = Logger(config = StaticConfig(logWriterList = listOf(platformLogWriter())), "KampKit")
val baseLogger =
Logger(config = StaticConfig(logWriterList = listOf(platformLogWriter())), "KampKit")
factory { (tag: String?) -> if (tag != null) baseLogger.withTag(tag) else baseLogger }

single {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
package co.touchlab.kampkit.ktor

import co.touchlab.kampkit.response.BreedResult
import co.touchlab.kermit.Logger as KermitLogger
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger as KtorLogger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.get
import io.ktor.http.encodedPath
import io.ktor.http.takeFrom
import io.ktor.serialization.kotlinx.json.json
import co.touchlab.kermit.Logger as KermitLogger
import io.ktor.client.plugins.logging.Logger as KtorLogger

class DogApiImpl(private val log: KermitLogger, engine: HttpClientEngine) : DogApi {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,14 @@ class BreedViewModel(
log.e(throwable) { "Error downloading breed list" }
mutableBreedState.update {
when (it) {
is BreedViewState.Content -> it.copy(isLoading = false) // Just let it fail silently if we have a cache
is BreedViewState.Content -> it.copy(
isLoading = false
) // Just let it fail silently if we have a cache
is BreedViewState.Empty,
is BreedViewState.Error,
is BreedViewState.Initial -> BreedViewState.Error(error = "Unable to refresh breed list")
is BreedViewState.Initial -> BreedViewState.Error(
error = "Unable to refresh breed list"
)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package co.touchlab.kampkit.sqldelight

import app.cash.sqldelight.Transacter
import app.cash.sqldelight.TransactionWithoutReturn
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.withContext

suspend fun Transacter.transactionWithContext(
coroutineContext: CoroutineContext,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import co.touchlab.kampkit.models.BreedRepository
import co.touchlab.kermit.Logger
import co.touchlab.kermit.StaticConfig
import com.russhwolf.settings.MapSettings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.runTest
import kotlinx.datetime.Clock
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.time.Duration.Companion.hours
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.runTest
import kotlinx.datetime.Clock

class BreedRepositoryTest {

Expand All @@ -32,7 +32,8 @@ class BreedRepositoryTest {
// Need to start at non-zero time because the default value for db timestamp is 0
private val clock = ClockMock(Clock.System.now())

private val repository: BreedRepository = BreedRepository(dbHelper, settings, ktorApi, kermit, clock)
private val repository: BreedRepository =
BreedRepository(dbHelper, settings, ktorApi, kermit, clock)

companion object {
private val appenzeller = Breed(1, "appenzeller", false)
Expand Down Expand Up @@ -60,7 +61,9 @@ class BreedRepositoryTest {
@Test
fun `Get updated breeds with cache and preserve favorites`() = runTest {
val successResult = ktorApi.successResult()
val resultWithExtraBreed = successResult.copy(message = successResult.message + ("extra" to emptyList()))
val resultWithExtraBreed = successResult.copy(
message = successResult.message + ("extra" to emptyList())
)
ktorApi.prepareResult(resultWithExtraBreed)

dbHelper.insertBreeds(breedNames)
Expand All @@ -78,10 +81,15 @@ class BreedRepositoryTest {

@Test
fun `Get updated breeds when stale and preserve favorites`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, (clock.currentInstant - 2.hours).toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
(clock.currentInstant - 2.hours).toEpochMilliseconds()
)

val successResult = ktorApi.successResult()
val resultWithExtraBreed = successResult.copy(message = successResult.message + ("extra" to emptyList()))
val resultWithExtraBreed = successResult.copy(
message = successResult.message + ("extra" to emptyList())
)
ktorApi.prepareResult(resultWithExtraBreed)

dbHelper.insertBreeds(breedNames)
Expand Down Expand Up @@ -110,7 +118,10 @@ class BreedRepositoryTest {

@Test
fun `No web call if data is not stale`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, clock.currentInstant.toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
clock.currentInstant.toEpochMilliseconds()
)
ktorApi.prepareResult(ktorApi.successResult())

repository.refreshBreedsIfStale()
Expand All @@ -132,7 +143,10 @@ class BreedRepositoryTest {

@Test
fun `Rethrow on API error when stale`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, (clock.currentInstant - 2.hours).toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
(clock.currentInstant - 2.hours).toEpochMilliseconds()
)
ktorApi.throwOnCall(RuntimeException("Test error"))

val throwable = assertFails {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ import co.touchlab.kampkit.response.BreedResult
import co.touchlab.kermit.Logger
import co.touchlab.kermit.StaticConfig
import com.russhwolf.settings.MapSettings
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Duration.Companion.hours
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import kotlinx.datetime.Clock
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Duration.Companion.hours

class BreedViewModelTest {
private var kermit = Logger(StaticConfig())
Expand All @@ -39,7 +39,8 @@ class BreedViewModelTest {
// Need to start at non-zero time because the default value for db timestamp is 0
private val clock = ClockMock(Clock.System.now())

private val repository: BreedRepository = BreedRepository(dbHelper, settings, ktorApi, kermit, clock)
private val repository: BreedRepository =
BreedRepository(dbHelper, settings, ktorApi, kermit, clock)

private val viewModel by lazy {
BreedViewModel(repository, kermit)
Expand Down Expand Up @@ -96,10 +97,15 @@ class BreedViewModelTest {

@Test
fun `Get updated breeds with cache and preserve favorites`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, clock.currentInstant.toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
clock.currentInstant.toEpochMilliseconds()
)

val successResult = ktorApi.successResult()
val resultWithExtraBreed = successResult.copy(message = successResult.message + ("extra" to emptyList()))
val resultWithExtraBreed = successResult.copy(
message = successResult.message + ("extra" to emptyList())
)
ktorApi.prepareResult(resultWithExtraBreed)

dbHelper.insertBreeds(breedNames)
Expand All @@ -112,18 +118,25 @@ class BreedViewModelTest {
viewModel.refreshBreeds()
// id is 5 here because it incremented twice when trying to insert duplicate breeds
assertEquals(
BreedViewState.Content(breedViewStateSuccessFavorite.breeds + Breed(5, "extra", false)),
BreedViewState.Content(
breedViewStateSuccessFavorite.breeds + Breed(5, "extra", false)
),
awaitItemPrecededBy(breedViewStateSuccessFavorite.copy(isLoading = true))
)
}
}

@Test
fun `Get updated breeds when stale and preserve favorites`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, (clock.currentInstant - 2.hours).toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
(clock.currentInstant - 2.hours).toEpochMilliseconds()
)

val successResult = ktorApi.successResult()
val resultWithExtraBreed = successResult.copy(message = successResult.message + ("extra" to emptyList()))
val resultWithExtraBreed = successResult.copy(
message = successResult.message + ("extra" to emptyList())
)
ktorApi.prepareResult(resultWithExtraBreed)

dbHelper.insertBreeds(breedNames)
Expand All @@ -132,15 +145,20 @@ class BreedViewModelTest {
viewModel.breedState.test {
// id is 5 here because it incremented twice when trying to insert duplicate breeds
assertEquals(
BreedViewState.Content(breedViewStateSuccessFavorite.breeds + Breed(5, "extra", false)),
BreedViewState.Content(
breedViewStateSuccessFavorite.breeds + Breed(5, "extra", false)
),
awaitItemPrecededBy(BreedViewState.Initial, breedViewStateSuccessFavorite)
)
}
}

@Test
fun `Toggle favorite cached breed`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, clock.currentInstant.toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
clock.currentInstant.toEpochMilliseconds()
)

dbHelper.insertBreeds(breedNames)
dbHelper.updateFavorite(australianLike.id, true)
Expand All @@ -159,12 +177,18 @@ class BreedViewModelTest {

@Test
fun `No web call if data is not stale`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, clock.currentInstant.toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
clock.currentInstant.toEpochMilliseconds()
)
ktorApi.prepareResult(ktorApi.successResult())
dbHelper.insertBreeds(breedNames)

viewModel.breedState.test {
assertEquals(breedViewStateSuccessNoFavorite, awaitItemPrecededBy(BreedViewState.Initial))
assertEquals(
breedViewStateSuccessNoFavorite,
awaitItemPrecededBy(BreedViewState.Initial)
)
assertEquals(0, ktorApi.calledCount)
expectNoEvents()

Expand Down Expand Up @@ -192,7 +216,10 @@ class BreedViewModelTest {
@Test
fun `Ignore API error with cache`() = runTest {
dbHelper.insertBreeds(breedNames)
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, (clock.currentInstant - 2.hours).toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
(clock.currentInstant - 2.hours).toEpochMilliseconds()
)
ktorApi.throwOnCall(RuntimeException("Test error"))

viewModel.breedState.test {
Expand Down Expand Up @@ -235,7 +262,10 @@ class BreedViewModelTest {

@Test
fun `Show API error on refresh without cache`() = runTest {
settings.putLong(BreedRepository.DB_TIMESTAMP_KEY, clock.currentInstant.toEpochMilliseconds())
settings.putLong(
BreedRepository.DB_TIMESTAMP_KEY,
clock.currentInstant.toEpochMilliseconds()
)
ktorApi.throwOnCall(RuntimeException("Test error"))

viewModel.breedState.test {
Expand All @@ -253,7 +283,9 @@ class BreedViewModelTest {

// There's a race condition where intermediate states can get missed if the next state comes too fast.
// This function addresses that by awaiting an item that may or may not be preceded by the specified other items
private suspend fun ReceiveTurbine<BreedViewState>.awaitItemPrecededBy(vararg items: BreedViewState): BreedViewState {
private suspend fun ReceiveTurbine<BreedViewState>.awaitItemPrecededBy(
vararg items: BreedViewState
): BreedViewState {
var nextItem = awaitItem()
for (item in items) {
if (item == nextItem) {
Expand Down
Loading

0 comments on commit 93f6080

Please sign in to comment.