11package com.powersync.testutils
22
3+ import co.touchlab.kermit.ExperimentalKermitApi
34import co.touchlab.kermit.LogWriter
5+ import co.touchlab.kermit.Logger
46import co.touchlab.kermit.Severity
7+ import co.touchlab.kermit.TestConfig
8+ import co.touchlab.kermit.TestLogWriter
59import com.powersync.DatabaseDriverFactory
10+ import kotlinx.coroutines.CoroutineScope
11+ import kotlinx.coroutines.Job
12+ import kotlinx.coroutines.currentCoroutineContext
13+ import kotlinx.coroutines.job
14+ import kotlinx.coroutines.launch
15+ import kotlinx.coroutines.test.TestScope
16+ import kotlinx.coroutines.test.runTest
17+ import kotlinx.coroutines.withContext
18+ import kotlinx.io.files.Path
19+ import kotlinx.io.files.SystemFileSystem
20+ import kotlin.coroutines.CoroutineContext
621
722expect val factory: DatabaseDriverFactory
823
@@ -21,3 +36,46 @@ fun generatePrintLogWriter() =
2136 println (" [$severity :$tag ] - $message " )
2237 }
2338 }
39+
40+ @OptIn(ExperimentalKermitApi ::class )
41+ class DatabaseTestScope : CoroutineContext .Element {
42+ val logWriter =
43+ TestLogWriter (
44+ loggable = Severity .Debug ,
45+ )
46+ val logger =
47+ Logger (
48+ TestConfig (
49+ minSeverity = Severity .Debug ,
50+ logWriterList = listOf (logWriter, generatePrintLogWriter()),
51+ ),
52+ )
53+
54+ val testDirectory by lazy {
55+ getTempDir() ? : SystemFileSystem .resolve(Path (" ." )).name
56+ }
57+
58+ val databaseName by lazy {
59+ val allowedChars = (' A' .. ' Z' ) + (' a' .. ' z' ) + (' 0' .. ' 9' )
60+ CharArray (8 ) { allowedChars.random() }.concatToString()
61+ }
62+
63+ private val cleanupItems: MutableList < suspend () -> Unit > = mutableListOf ()
64+
65+ override val key: CoroutineContext .Key <* >
66+ get() = Companion
67+
68+ companion object : CoroutineContext .Key <DatabaseTestScope >
69+ }
70+
71+ val CoroutineContext .database: DatabaseTestScope get() = get(DatabaseTestScope ) ? : error(" Not in PowerSync test: $this " )
72+
73+ fun databaseTest (
74+ testBody : suspend TestScope .() -> Unit
75+ ) = runTest {
76+ val test = DatabaseTestScope ()
77+
78+ withContext(test) {
79+ testBody()
80+ }
81+ }
0 commit comments