summaryrefslogtreecommitdiff
path: root/formats/protobuf/commonTest/src/kotlinx/serialization/protobuf/ProtobufNullAndDefaultTest.kt
blob: 88450aad839d65548aa9246e9a3cdfc70e850e57 (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
/*
 * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.serialization.protobuf

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

class ProtobufNullAndDefaultTest {
    @Serializable
    class ProtoWithNullDefault(val s: String? = null)

    @Serializable
    class ProtoWithNullDefaultAlways(@EncodeDefault val s: String? = null)

    @Serializable
    class ProtoWithNullDefaultNever(@EncodeDefault(EncodeDefault.Mode.NEVER) val s: String? = null)

    @Test
    fun testProtobufDropDefaults() {
        val proto = ProtoBuf { encodeDefaults = false }
        assertEquals(0, proto.encodeToByteArray(ProtoWithNullDefault()).size)
        if (isJsLegacy()) return // because of @EncodeDefault
        assertFailsWith<SerializationException> { proto.encodeToByteArray(ProtoWithNullDefaultAlways()) }
        assertEquals(0, proto.encodeToByteArray(ProtoWithNullDefaultNever()).size)
    }

    @Test
    fun testProtobufEncodeDefaults() {
        val proto = ProtoBuf { encodeDefaults = true }
        assertFailsWith<SerializationException> { proto.encodeToByteArray(ProtoWithNullDefault()) }
        if (isJsLegacy()) return // because of @EncodeDefault
        assertFailsWith<SerializationException> { proto.encodeToByteArray(ProtoWithNullDefaultAlways()) }
        assertEquals(0, proto.encodeToByteArray(ProtoWithNullDefaultNever()).size)
    }
}