diff --git a/repos/inmemory/src/commonTest/kotlin/MapCRUDRepoTest.kt b/repos/inmemory/src/commonTest/kotlin/MapCRUDRepoTest.kt new file mode 100644 index 00000000000..fc386c3971c --- /dev/null +++ b/repos/inmemory/src/commonTest/kotlin/MapCRUDRepoTest.kt @@ -0,0 +1,100 @@ +import dev.inmo.micro_utils.repos.MapCRUDRepo +import dev.inmo.micro_utils.repos.create +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals + +data class TestModel( + val testery: String, + val isTestery: Boolean, + val testeryAmount: Int +) + +class MapCRUDRepoTest { + /** + * A utility function used for generating non-intersecting ranges in cyclic environment, like [repeat] + * or for-loops + */ + private fun getIdRange(start: Int, base: Int) = (start * base)..(start * base + (base - 1)) + + @Test + fun mapCrudRepoTest() = runTest { + val base = 200 // define a bigger number to increase test intensity + val targetMap = mutableMapOf() + + // filling the map + val jobs = List(base) { id -> + launch(Dispatchers.Default) { // to make delays work + println("launching job $id") + delay((1..5).random().toLong()) + + val idsList = getIdRange(id, base).toMutableList() + println("created ids list $idsList") + val mapCRUDRepo = MapCRUDRepo( + targetMap, + createCallback = { new -> + val newObject = idsList.first() to new + idsList.remove(newObject.first) + println("created $newObject in map") + newObject + }, + updateCallback = { new, id, old -> + println("updated object at $id from $old to $new") + new + } + ) + for (i in getIdRange(id, base)) { + val newModel = TestModel( + testery = "testery$i", + isTestery = i % 2 == 0, + testeryAmount = i + ) + mapCRUDRepo.create(newModel) + } + } + } + + jobs.forEach { + println("joining job ${it.hashCode()}") + it.join() + } + + // validating the map + val validationJobs = List(base) { id -> + launch { + val idsList = getIdRange(id, base).toMutableList() + val mapCRUDRepo = MapCRUDRepo( + targetMap, + // these will not be used + createCallback = { new -> + val newObject = idsList.first() to new + idsList.remove(newObject.first) + println("created $newObject in map") + newObject + }, + updateCallback = { new, id, old -> + println("updated object at $id from $old to $new") + new + } + ) + for (i in getIdRange(id, base)) { + val newModel = TestModel( + testery = "testery$i", + isTestery = i % 2 == 0, + testeryAmount = i + ) + val oldModel = mapCRUDRepo.getById(i) + assertEquals(newModel, oldModel) + } + } + } + + validationJobs.forEach { + println("joining validation job ${it.hashCode()}") + it.join() + } + } +} \ No newline at end of file