package eu.friedcutlet.yokan.architecture import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelStore import eu.friedcutlet.yokan.services.files.LocalEntry import eu.friedcutlet.yokan.services.files.LocalFileEntry import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import kotlin.coroutines.ContinuationInterceptor import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @OptIn(ExperimentalCoroutinesApi::class) internal abstract class GuidedViewModelFixture { protected val main = StandardTestDispatcher() private val owners = ViewModelStore() private var nextOwner = 0 @BeforeTest fun prepareMain() { Dispatchers.setMain(main) } @AfterTest fun closeOwners() { try { owners.clear() } finally { Dispatchers.resetMain() } } protected fun own(viewModel: T): T = viewModel.also { owners.put("guided-${nextOwner++}", it) } protected val unusedHttp = object : HttpService { override suspend fun request(request: HttpRequest): HttpResponse = error("No HTTP expected") } protected class Files : LocalFileService { override val downloadRoot = "/downloads" override val backupRoot = "/backups" override val cacheRoot = "/cache" val asyncReadContexts = mutableListOf() val writes = mutableListOf() val revealed = mutableListOf() var deletions = 0 var readAsync: suspend (String) -> ByteArray = { "log".encodeToByteArray() } var onDelete: () -> Boolean = { true } override fun writeBytes(path: String, bytes: ByteArray) { writes += path } override suspend fun writeBytesAsync(path: String, bytes: ByteArray) { writes += path } override fun readBytes(path: String) = "crash".encodeToByteArray() override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray { asyncReadContexts += currentCoroutineContext()[ContinuationInterceptor] return readAsync(path) } override fun canonicalPath(path: String) = path override fun exists(path: String) = false override fun deleteRecursively(path: String): Boolean { deletions++; return onDelete() } override fun directorySize(path: String) = 0L override fun openLocation(path: String): Boolean { revealed += path; return true } override fun listLocalEntries(root: String): List = emptyList() override fun listFiles(root: String): List = emptyList() } }