summaryrefslogtreecommitdiff
path: root/formats/json-tests/commonTest/src/kotlinx/serialization/json/JsonOptionalTests.kt
blob: 679a972be9c238a8b2c1e18dcc5c5fa32a4c9103 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.serialization.json

import kotlinx.serialization.*
import kotlinx.serialization.test.*
import kotlin.test.*

class JsonOptionalTests : JsonTestBase() {

    @Suppress("EqualsOrHashCode")
    @Serializable
    internal class Data(@Required val a: Int = 0, val b: Int = 42) {

        var c = "Hello"

        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other == null || this::class != other::class) return false

            other as Data

            if (a != other.a) return false
            if (b != other.b) return false
            if (c != other.c) return false

            return true
        }
    }

    @Test
    fun testAll() = parametrizedTest { jsonTestingMode ->
        assertEquals("""{"a":0,"b":42,"c":"Hello"}""",
            default.encodeToString(Data.serializer(), Data(), jsonTestingMode))
        assertEquals(lenient.decodeFromString(Data.serializer(), "{a:0,b:43,c:Hello}", jsonTestingMode), Data(b = 43))
        assertEquals(lenient.decodeFromString(Data.serializer(), "{a:0,b:42,c:Hello}", jsonTestingMode), Data())
    }

    @Test
    fun testMissingOptionals() = parametrizedTest { jsonTestingMode ->
        assertEquals(default.decodeFromString(Data.serializer(), """{"a":0,"c":"Hello"}""", jsonTestingMode), Data())
        assertEquals(default.decodeFromString(Data.serializer(), """{"a":0}""", jsonTestingMode), Data())
    }

    @Test
    fun testThrowMissingField() = parametrizedTest { jsonTestingMode ->
        assertFailsWithMissingField {
            lenient.decodeFromString(Data.serializer(), "{b:0}", jsonTestingMode)
        }
    }
}