summaryrefslogtreecommitdiff
path: root/formats/json-tests/commonTest/src/kotlinx/serialization/features/JsonNamingStrategyTest.kt
blob: 9e2cf1d4f78eb49d2d9e6ab26ecbb88967374ff4 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package kotlinx.serialization.features

import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
import kotlinx.serialization.json.*
import kotlinx.serialization.test.*
import kotlin.test.*


class JsonNamingStrategyTest : JsonTestBase() {
    @Serializable
    data class Foo(
        val simple: String = "a",
        val oneWord: String = "b",
        val already_in_snake: String = "c",
        val aLotOfWords: String = "d",
        val FirstCapitalized: String = "e",
        val hasAcronymURL: Bar = Bar.BAZ,
        val hasDigit123AndPostfix: Bar = Bar.QUX,
        val coercionTest: Bar = Bar.QUX
    )

    enum class Bar { BAZ, QUX }

    val jsonWithNaming = Json(default) {
        namingStrategy = JsonNamingStrategy.SnakeCase
        decodeEnumsCaseInsensitive = true // check that related feature does not break anything
    }

    @Test
    fun testJsonNamingStrategyWithAlternativeNames() = doTest(Json(jsonWithNaming) {
        useAlternativeNames = true
    })

    @Test
    fun testJsonNamingStrategyWithoutAlternativeNames() = doTest(Json(jsonWithNaming) {
        useAlternativeNames = false
    })

    private fun doTest(json: Json) {
        val foo = Foo()
        assertJsonFormAndRestored(
            Foo.serializer(),
            foo,
            """{"simple":"a","one_word":"b","already_in_snake":"c","a_lot_of_words":"d","first_capitalized":"e","has_acronym_url":"BAZ","has_digit123_and_postfix":"QUX","coercion_test":"QUX"}""",
            json
        )
    }

    @Test
    fun testNamingStrategyWorksWithCoercing() {
        val j = Json(jsonWithNaming) {
            coerceInputValues = true
            useAlternativeNames = false
        }
        assertEquals(
            Foo(),
            j.decodeFromString("""{"simple":"a","one_word":"b","already_in_snake":"c","a_lot_of_words":"d","first_capitalized":"e","has_acronym_url":"baz","has_digit123_and_postfix":"qux","coercion_test":"invalid"}""")
        )
    }

    @Test
    fun testSnakeCaseStrategy() {
        fun apply(name: String) =
            JsonNamingStrategy.SnakeCase.serialNameForJson(String.serializer().descriptor, 0, name)

        val cases = mapOf<String, String>(
            "" to "",
            "_" to "_",
            "___" to "___",
            "a" to "a",
            "A" to "a",
            "_1" to "_1",
            "_a" to "_a",
            "_A" to "_a",
            "property" to "property",
            "twoWords" to "two_words",
            "threeDistinctWords" to "three_distinct_words",
            "ThreeDistinctWords" to "three_distinct_words",
            "Oneword" to "oneword",
            "camel_Case_Underscores" to "camel_case_underscores",
            "_many____underscores__" to "_many____underscores__",
            "URLmapping" to "ur_lmapping",
            "URLMapping" to "url_mapping",
            "IOStream" to "io_stream",
            "IOstream" to "i_ostream",
            "myIo2Stream" to "my_io2_stream",
            "myIO2Stream" to "my_io2_stream",
            "myIO2stream" to "my_io2stream",
            "myIO2streamMax" to "my_io2stream_max",
            "InURLBetween" to "in_url_between",
            "myHTTP2APIKey" to "my_http2_api_key",
            "myHTTP2fastApiKey" to "my_http2fast_api_key",
            "myHTTP23APIKey" to "my_http23_api_key",
            "myHttp23ApiKey" to "my_http23_api_key",
            "theWWW" to "the_www",
            "theWWW_URL_xxx" to "the_www_url_xxx",
            "hasDigit123AndPostfix" to "has_digit123_and_postfix"
        )

        cases.forEach { (input, expected) ->
            assertEquals(expected, apply(input))
        }
    }

    @Test
    fun testKebabCaseStrategy() {
        fun apply(name: String) =
            JsonNamingStrategy.KebabCase.serialNameForJson(String.serializer().descriptor, 0, name)

        val cases = mapOf<String, String>(
            "" to "",
            "_" to "_",
            "-" to "-",
            "___" to "___",
            "---" to "---",
            "a" to "a",
            "A" to "a",
            "-1" to "-1",
            "-a" to "-a",
            "-A" to "-a",
            "property" to "property",
            "twoWords" to "two-words",
            "threeDistinctWords" to "three-distinct-words",
            "ThreeDistinctWords" to "three-distinct-words",
            "Oneword" to "oneword",
            "camel-Case-WithDashes" to "camel-case-with-dashes",
            "_many----dashes--" to "_many----dashes--",
            "URLmapping" to "ur-lmapping",
            "URLMapping" to "url-mapping",
            "IOStream" to "io-stream",
            "IOstream" to "i-ostream",
            "myIo2Stream" to "my-io2-stream",
            "myIO2Stream" to "my-io2-stream",
            "myIO2stream" to "my-io2stream",
            "myIO2streamMax" to "my-io2stream-max",
            "InURLBetween" to "in-url-between",
            "myHTTP2APIKey" to "my-http2-api-key",
            "myHTTP2fastApiKey" to "my-http2fast-api-key",
            "myHTTP23APIKey" to "my-http23-api-key",
            "myHttp23ApiKey" to "my-http23-api-key",
            "theWWW" to "the-www",
            "theWWW-URL-xxx" to "the-www-url-xxx",
            "hasDigit123AndPostfix" to "has-digit123-and-postfix"
        )

        cases.forEach { (input, expected) ->
            assertEquals(expected, apply(input))
        }
    }

    @Serializable
    data class DontUseOriginal(val testCase: String)

    @Test
    fun testNamingStrategyOverridesOriginal() {
        val json = Json(jsonWithNaming) {
            ignoreUnknownKeys = true
        }
        parametrizedTest { mode ->
            assertEquals(DontUseOriginal("a"), json.decodeFromString("""{"test_case":"a","testCase":"b"}""", mode))
        }

        val jsonThrows = Json(jsonWithNaming) {
            ignoreUnknownKeys = false
        }
        parametrizedTest { mode ->
            assertFailsWithMessage<SerializationException>("Encountered an unknown key 'testCase'") {
                jsonThrows.decodeFromString<DontUseOriginal>("""{"test_case":"a","testCase":"b"}""", mode)
            }
        }
    }

    @Serializable
    data class CollisionCheckPrimary(val testCase: String, val test_case: String)

    @Serializable
    data class CollisionCheckAlternate(val testCase: String, @JsonNames("test_case") val testCase2: String)

    @Test
    fun testNamingStrategyPrioritizesOverAlternative() {
        val json = Json(jsonWithNaming) {
            ignoreUnknownKeys = true
        }
        parametrizedTest { mode ->
            assertFailsWithMessage<SerializationException>("The suggested name 'test_case' for property test_case is already one of the names for property testCase") {
                json.decodeFromString<CollisionCheckPrimary>("""{"test_case":"a"}""", mode)
            }
        }
        parametrizedTest { mode ->
            assertFailsWithMessage<SerializationException>("The suggested name 'test_case' for property testCase2 is already one of the names for property testCase") {
                json.decodeFromString<CollisionCheckAlternate>("""{"test_case":"a"}""", mode)
            }
        }
    }


    @Serializable
    data class OriginalAsFallback(@JsonNames("testCase") val testCase: String)

    @Test
    fun testCanUseOriginalNameAsAlternative() {
        val json = Json(jsonWithNaming) {
            ignoreUnknownKeys = true
        }
        parametrizedTest { mode ->
            assertEquals(OriginalAsFallback("b"), json.decodeFromString("""{"testCase":"b"}""", mode))
        }
    }

    @Serializable
    sealed interface SealedBase {
        @Serializable
        @JsonClassDiscriminator("typeSub")
        sealed class SealedMid : SealedBase {
            @Serializable
            @SerialName("SealedSub1")
            object SealedSub1 : SealedMid()
        }

        @Serializable
        @SerialName("SealedSub2")
        data class SealedSub2(val testCase: Int = 0) : SealedBase
    }

    @Serializable
    data class Holder(val testBase: SealedBase, val testMid: SealedBase.SealedMid)

    @Test
    fun testNamingStrategyDoesNotAffectPolymorphism() {
        val json = Json(jsonWithNaming) {
            classDiscriminator = "typeBase"
        }
        val holder = Holder(SealedBase.SealedSub2(), SealedBase.SealedMid.SealedSub1)
        assertJsonFormAndRestored(
            Holder.serializer(),
            holder,
            """{"test_base":{"typeBase":"SealedSub2","test_case":0},"test_mid":{"typeSub":"SealedSub1"}}""",
            json
        )
    }
}