From af306084cfbcf793b032fd852b9b895a42936975 Mon Sep 17 00:00:00 2001 From: Alexander Nozik Date: Sun, 22 Nov 2020 19:16:08 +0300 Subject: [PATCH] Test for #65 --- .../kotlin/kscience/kmath/stat/MCScopeTest.kt | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 kmath-stat/src/jvmTest/kotlin/kscience/kmath/stat/MCScopeTest.kt diff --git a/kmath-stat/src/jvmTest/kotlin/kscience/kmath/stat/MCScopeTest.kt b/kmath-stat/src/jvmTest/kotlin/kscience/kmath/stat/MCScopeTest.kt new file mode 100644 index 000000000..c2304070f --- /dev/null +++ b/kmath-stat/src/jvmTest/kotlin/kscience/kmath/stat/MCScopeTest.kt @@ -0,0 +1,85 @@ +package kscience.kmath.stat + +import kotlinx.coroutines.* +import java.util.* +import kotlin.collections.HashSet +import kotlin.test.Test +import kotlin.test.assertEquals + +data class RandomResult(val branch: String, val order: Int, val value: Int) + +typealias ATest = suspend CoroutineScope.() -> Set + +class MCScopeTest { + val simpleTest: ATest = { + mcScope(1111) { + val res = Collections.synchronizedSet(HashSet()) + + launch { + //println(random) + repeat(10) { + delay(10) + res.add(RandomResult("first", it, random.nextInt())) + } + launch { + //empty fork + } + } + + launch { + //println(random) + repeat(10) { + delay(10) + res.add(RandomResult("second", it, random.nextInt())) + } + } + + + res + } + } + + val testWithJoin: ATest = { + mcScope(1111) { + val res = Collections.synchronizedSet(HashSet()) + + val job = launch { + repeat(10) { + delay(10) + res.add(RandomResult("first", it, random.nextInt())) + } + } + launch { + repeat(10) { + delay(10) + if (it == 4) job.join() + res.add(RandomResult("second", it, random.nextInt())) + } + } + + res + } + } + + + fun compareResult(test: ATest) { + val res1 = runBlocking(Dispatchers.Default) { test() } + val res2 = runBlocking(newSingleThreadContext("test")) { test() } + assertEquals( + res1.find { it.branch == "first" && it.order == 7 }?.value, + res2.find { it.branch == "first" && it.order == 7 }?.value + ) + assertEquals(res1, res2) + } + + @Test + fun testParallel() { + compareResult(simpleTest) + } + + + @Test + fun testConditionalJoin() { + compareResult(testWithJoin) + } +} \ No newline at end of file