• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017-2020 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.json.internal.*
9 import kotlinx.serialization.test.*
10 import kotlin.test.*
11 
12 class SpecialFloatingPointValuesTest : JsonTestBase() {
13 
14     @Serializable
15     data class Box(val d: Double, val f: Float) {
equalsnull16         override fun equals(other: Any?): Boolean {
17             if (this === other) return true
18             if (other == null || this::class != other::class) return false
19             other as Box
20             if (d != other.d && !(d.isNaN() && other.d.isNaN())) return false
21             if (f != other.f && !(f.isNaN() && other.f.isNaN())) return false
22             return true
23         }
24 
hashCodenull25         override fun hashCode(): Int {
26             var result = d.hashCode()
27             result = 31 * result + f.hashCode()
28             return result
29         }
30     }
31 
<lambda>null32     val json = Json { allowSpecialFloatingPointValues = true }
33 
34     @Test
<lambda>null35     fun testNans() = parametrizedTest {
36         test(Box(Double.NaN, Float.NaN), """{"d":NaN,"f":NaN}""", it)
37         noJs { // Number formatting
38             test(Box(0.0, Float.NaN), """{"d":0.0,"f":NaN}""", it)
39             test(Box(Double.NaN, 0.0f), """{"d":NaN,"f":0.0}""", it)
40         }
41     }
42 
43     @Test
<lambda>null44     fun testInfinities() = parametrizedTest {
45         test(Box(Double.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY), """{"d":-Infinity,"f":Infinity}""", it)
46         test(Box(Double.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), """{"d":Infinity,"f":-Infinity}""", it)
47     }
48 
testnull49     private fun test(box: Box, expected: String, jsonTestingMode: JsonTestingMode) {
50         assertFailsWithSerialMessage("JsonEncodingException", "Unexpected special floating-point value") { default.encodeToString(Box.serializer(), box, jsonTestingMode) }
51         assertEquals(expected, json.encodeToString(Box.serializer(), box, jsonTestingMode))
52         assertEquals(box, json.decodeFromString(Box.serializer(), expected, jsonTestingMode))
53         assertFailsWithSerialMessage("JsonDecodingException", "Unexpected special floating-point value") { default.decodeFromString(Box.serializer(), expected, jsonTestingMode) }
54     }
55 }
56