• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 @file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
6 
7 package kotlinx.serialization.test
8 
9 import kotlinx.serialization.*
10 import kotlinx.serialization.descriptors.*
11 import kotlinx.serialization.json.internal.ESCAPE_STRINGS
12 import kotlin.random.Random
13 import kotlin.random.nextInt
14 import kotlin.test.*
15 
assertDescriptorEqualsTonull16 fun SerialDescriptor.assertDescriptorEqualsTo(other: SerialDescriptor) {
17     assertEquals(serialName, other.serialName)
18     assertEquals(elementsCount, other.elementsCount)
19     assertEquals(isNullable, other.isNullable)
20     assertEquals(annotations, other.annotations)
21     assertEquals(kind, other.kind)
22     for (i in 0 until elementsCount) {
23         getElementDescriptor(i).assertDescriptorEqualsTo(other.getElementDescriptor(i))
24         val name = getElementName(i)
25         val otherName = other.getElementName(i)
26         assertEquals(name, otherName)
27         assertEquals(getElementAnnotations(i), other.getElementAnnotations(i))
28         assertEquals(name, otherName)
29         assertEquals(isElementOptional(i), other.isElementOptional(i))
30     }
31 }
32 
noJsnull33 inline fun noJs(test: () -> Unit) {
34     if (!isJs()) test()
35 }
36 
jvmOnlynull37 inline fun jvmOnly(test: () -> Unit) {
38     if (isJvm()) test()
39 }
40 
assertFailsWithMissingFieldnull41 inline fun assertFailsWithMissingField(block: () -> Unit) {
42     val e = assertFailsWith<SerializationException>(block = block)
43     assertTrue(e.message?.contains("but it was missing") ?: false)
44 }
45 
generateRandomUnicodeStringnull46 fun generateRandomUnicodeString(size: Int): String {
47     return buildString(size) {
48         repeat(size) {
49             val pickEscape = Random.nextBoolean()
50             if (pickEscape) {
51                 // Definitely an escape symbol
52                 append(ESCAPE_STRINGS.random().takeIf { it != null } ?: 'N')
53             } else {
54                 // Any symbol, including escaping one
55                 append(Char(Random.nextInt(Char.MIN_VALUE.code..Char.MAX_VALUE.code)).takeIf { it.isDefined() && !it.isSurrogate()} ?: 'U')
56             }
57         }
58     }
59 }
60