<lambda>null1 package kotlinx.serialization.json
2
3 import kotlinx.coroutines.*
4 import kotlinx.serialization.Serializable
5 import kotlinx.serialization.builtins.*
6 import org.junit.Test
7 import java.io.ByteArrayInputStream
8 import java.io.ByteArrayOutputStream
9 import kotlin.random.*
10 import kotlin.test.*
11
12 // Stresses out that JSON decoded in parallel does not interfere (mostly via caching of various buffers)
13 class JsonConcurrentStressTest : JsonTestBase() {
14 private val charset = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789"
15
16 @Test
17 fun testDecodeInParallelSimpleList() = doTest(100) { mode ->
18 val value = (1..10000).map { Random.nextDouble() }
19 val string = Json.encodeToString(ListSerializer(Double.serializer()), value, mode)
20 assertEquals(value, Json.decodeFromString(ListSerializer(Double.serializer()), string, mode))
21 }
22
23 @Serializable
24 data class Foo(val s: String, val f: Foo?)
25
26 @Test
27 fun testDecodeInParallelListOfPojo() = doTest(1_000) { mode ->
28 val value = (1..100).map {
29 val randomString = getRandomString()
30 val nestedFoo = Foo("null抢\u000E鋽윝䑜厼\uF70A紲ᢨ䣠null⛾䉻嘖緝ᯧnull쎶\u0005null" + randomString, null)
31 Foo(getRandomString(), nestedFoo)
32 }
33 val string = Json.encodeToString(ListSerializer(Foo.serializer()), value, mode)
34 assertEquals(value, Json.decodeFromString(ListSerializer(Foo.serializer()), string, mode))
35 }
36
37 @Test
38 fun testDecodeInParallelPojo() = doTest(100_000) { mode ->
39 val randomString = getRandomString()
40 val nestedFoo = Foo("null抢\u000E鋽윝䑜厼\uF70A紲ᢨ䣠null⛾䉻嘖緝ᯧnull쎶\u0005null" + randomString, null)
41 val randomFoo = Foo(getRandomString(), nestedFoo)
42 val string = Json.encodeToString(Foo.serializer(), randomFoo, mode)
43 assertEquals(randomFoo, Json.decodeFromString(Foo.serializer(), string, mode))
44 }
45
46 @Test
47 fun testDecodeInParallelSequencePojo() = runBlocking<Unit> {
48 for (i in 1 until 1_000) {
49 launch(Dispatchers.Default) {
50 val values = (1..100).map {
51 val randomString = getRandomString()
52 val nestedFoo = Foo("null抢\u000E鋽윝䑜厼\uF70A紲ᢨ䣠null⛾䉻嘖緝ᯧnull쎶\u0005null" + randomString, null)
53 Foo(getRandomString(), nestedFoo)
54 }
55 val baos = ByteArrayOutputStream()
56 for (value in values) {
57 Json.encodeToStream(Foo.serializer(), value, baos)
58 }
59 val bais = ByteArrayInputStream(baos.toByteArray())
60 assertEquals(values, Json.decodeToSequence(bais, Foo.serializer()).toList())
61 }
62 }
63 }
64
65 private fun getRandomString() = (1..Random.nextInt(0, charset.length)).map { charset[it] }.joinToString(separator = "")
66
67 private fun doTest(iterations: Int, block: (JsonTestingMode) -> Unit) {
68 runBlocking<Unit> {
69 for (i in 1 until iterations) {
70 launch(Dispatchers.Default) {
71 parametrizedTest {
72 block(it)
73 }
74 }
75 }
76 }
77 }
78 }
79