-
Notifications
You must be signed in to change notification settings - Fork 636
/
Copy pathInstantSerializationTest.kt
69 lines (62 loc) · 2.8 KB
/
InstantSerializationTest.kt
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
/*
* Copyright 2025-2025 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.builtins.*
import kotlin.time.*
import kotlin.test.*
@OptIn(ExperimentalTime::class)
class InstantSerializationTest {
private fun iso8601Serialization(serializer: KSerializer<Instant>) {
for ((instant, json) in listOf(
Pair(Instant.fromEpochSeconds(1607505416, 124000),
"\"2020-12-09T09:16:56.000124Z\""),
Pair(Instant.fromEpochSeconds(-1607505416, -124000),
"\"1919-01-23T14:43:03.999876Z\""),
Pair(Instant.fromEpochSeconds(987654321, 123456789),
"\"2001-04-19T04:25:21.123456789Z\""),
Pair(Instant.fromEpochSeconds(987654321, 0),
"\"2001-04-19T04:25:21Z\""),
)) {
assertEquals(json, Json.encodeToString(serializer, instant))
assertEquals(instant, Json.decodeFromString(serializer, json))
}
}
private fun componentSerialization(serializer: KSerializer<Instant>) {
for ((instant, json) in listOf(
Pair(Instant.fromEpochSeconds(1607505416, 124000),
"{\"epochSeconds\":1607505416,\"nanosecondsOfSecond\":124000}"),
Pair(Instant.fromEpochSeconds(-1607505416, -124000),
"{\"epochSeconds\":-1607505417,\"nanosecondsOfSecond\":999876000}"),
Pair(Instant.fromEpochSeconds(987654321, 123456789),
"{\"epochSeconds\":987654321,\"nanosecondsOfSecond\":123456789}"),
Pair(Instant.fromEpochSeconds(987654321, 0),
"{\"epochSeconds\":987654321}"),
)) {
assertEquals(json, Json.encodeToString(serializer, instant))
assertEquals(instant, Json.decodeFromString(serializer, json))
}
// check that having a `"nanosecondsOfSecond": 0` field doesn't break deserialization
assertEquals(Instant.fromEpochSeconds(987654321, 0),
Json.decodeFromString(serializer,
"{\"epochSeconds\":987654321,\"nanosecondsOfSecond\":0}"))
// "epochSeconds" should always be present
assertFailsWith<SerializationException> { Json.decodeFromString(serializer, "{}") }
assertFailsWith<SerializationException> { Json.decodeFromString(serializer, "{\"nanosecondsOfSecond\":3}") }
}
@Test
fun testIso8601Serialization() {
iso8601Serialization(Instant.serializer())
}
@Test
fun testComponentSerialization() {
componentSerialization(InstantComponentSerializer)
}
@Test
fun testDefaultSerializers() {
// should be the same as the ISO 8601
iso8601Serialization(Json.serializersModule.serializer())
}
}