• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.serialization.json
6 
7 import kotlinx.serialization.*
8 import kotlinx.serialization.features.*
9 import kotlinx.serialization.test.*
10 import kotlin.test.*
11 
12 
13 class JsonNamesDynamicTest {
14     private val inputString1 = js("""{"foo":"foo"}""")
15     private val inputString2 = js("""{"_foo":"foo"}""")
16 
17     private fun parameterizedCoercingTest(test: (json: Json, msg: String) -> Unit) {
18         for (coercing in listOf(true, false)) {
19             val json = Json {
20                 coerceInputValues = coercing
21                 useAlternativeNames = true
22             }
23 
24             test(
25                 json,
26                 "Failed test with coercing=$coercing"
27             )
28         }
29     }
30 
31     @Test
32     fun testParsesAllAlternativeNamesDynamic() {
33         for (input in listOf(inputString1, inputString2)) {
34             parameterizedCoercingTest { json, msg ->
35                 val data = json.decodeFromDynamic(JsonNamesTest.WithNames.serializer(), input)
36                 assertEquals("foo", data.data, msg + "and input '$input'")
37             }
38         }
39     }
40 
41     @Test
42     fun testEnumSupportsAlternativeNames() {
43         val input = js("""{"enumList":["VALUE_A", "someValue", "some_value", "VALUE_B"], "checkCoercion":"someValue"}""")
44         val expected = JsonNamesTest.WithEnumNames(
45             listOf(
46                 JsonNamesTest.AlternateEnumNames.VALUE_A,
47                 JsonNamesTest.AlternateEnumNames.VALUE_A,
48                 JsonNamesTest.AlternateEnumNames.VALUE_A,
49                 JsonNamesTest.AlternateEnumNames.VALUE_B
50             ), JsonNamesTest.AlternateEnumNames.VALUE_A
51         )
52         parameterizedCoercingTest { json, msg ->
53             assertEquals(expected, json.decodeFromDynamic(input), msg)
54         }
55     }
56 
57     @Test
58     fun topLevelEnumSupportAlternativeNames() {
59         parameterizedCoercingTest { json, msg ->
60             assertEquals(JsonNamesTest.AlternateEnumNames.VALUE_A, json.decodeFromDynamic(js("\"someValue\"")), msg)
61         }
62     }
63 
64     @Test
65     fun testThrowsAnErrorOnDuplicateNames2() {
66         val serializer = JsonNamesTest.CollisionWithAlternate.serializer()
67         parameterizedCoercingTest { json, _ ->
68             assertFailsWithMessage<SerializationException>(
69                 """The suggested name '_foo' for property foo is already one of the names for property data""",
70                 "Class ${serializer.descriptor.serialName} did not fail"
71             ) {
72                 json.decodeFromDynamic(
73                     serializer, inputString2,
74                 )
75             }
76         }
77     }
78 
79 }
80