• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright 2017-2019 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.test.*
9 import kotlin.test.*
10 
11 class JsonOptionalTests : JsonTestBase() {
12 
13     @Suppress("EqualsOrHashCode")
14     @Serializable
15     internal class Data(@Required val a: Int = 0, val b: Int = 42) {
16 
17         var c = "Hello"
18 
19         override fun equals(other: Any?): Boolean {
20             if (this === other) return true
21             if (other == null || this::class != other::class) return false
22 
23             other as Data
24 
25             if (a != other.a) return false
26             if (b != other.b) return false
27             if (c != other.c) return false
28 
29             return true
30         }
31     }
32 
33     @Test
34     fun testAll() = parametrizedTest { jsonTestingMode ->
35         assertEquals("""{"a":0,"b":42,"c":"Hello"}""",
36             default.encodeToString(Data.serializer(), Data(), jsonTestingMode))
37         assertEquals(lenient.decodeFromString(Data.serializer(), "{a:0,b:43,c:Hello}", jsonTestingMode), Data(b = 43))
38         assertEquals(lenient.decodeFromString(Data.serializer(), "{a:0,b:42,c:Hello}", jsonTestingMode), Data())
39     }
40 
41     @Test
42     fun testMissingOptionals() = parametrizedTest { jsonTestingMode ->
43         assertEquals(default.decodeFromString(Data.serializer(), """{"a":0,"c":"Hello"}""", jsonTestingMode), Data())
44         assertEquals(default.decodeFromString(Data.serializer(), """{"a":0}""", jsonTestingMode), Data())
45     }
46 
47     @Test
48     fun testThrowMissingField() = parametrizedTest { jsonTestingMode ->
49         assertFailsWithMissingField {
50             lenient.decodeFromString(Data.serializer(), "{b:0}", jsonTestingMode)
51         }
52     }
53 }
54