blob: e6fbecb9cb4a18b5067c91a03e21b6a05361e4f8 (
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
|
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization
import kotlinx.coroutines.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.json.*
import kotlinx.serialization.json.internal.*
import kotlinx.serialization.modules.*
import kotlin.test.*
class StacktraceRecoveryTest {
@Serializable
private class Data(val s: String)
private class BadDecoder : AbstractDecoder() {
override val serializersModule: SerializersModule = EmptySerializersModule
override fun decodeElementIndex(descriptor: SerialDescriptor): Int = 42
}
@Test
fun testJsonDecodingException() = checkRecovered<JsonDecodingException> {
Json.decodeFromString<String>("42")
}
@Test
fun testJsonEncodingException() = checkRecovered<JsonEncodingException> {
Json.encodeToString(Double.NaN)
}
@Test
// checks simple name because UFE is internal class
fun testUnknownFieldException() = checkRecovered("UnknownFieldException") {
val serializer = Data.serializer()
serializer.deserialize(BadDecoder())
}
@Test
// checks simple name because MFE is internal class
fun testMissingFieldException() = checkRecovered("MissingFieldException") {
Json.decodeFromString<Data>("{}")
}
private fun checkRecovered(exceptionClassSimpleName: String, block: () -> Unit) = runBlocking {
val result = runCatching {
callBlockWithRecovery(block)
}
assertTrue(result.isFailure, "Block should have failed")
val e = result.exceptionOrNull()!!
assertEquals(exceptionClassSimpleName, e::class.simpleName!!)
val cause = e.cause
assertNotNull(cause, "Exception should have cause: $e")
assertEquals(e.message, cause.message)
assertEquals(exceptionClassSimpleName, e::class.simpleName!!)
}
private inline fun <reified E : Exception> checkRecovered(noinline block: () -> Unit) = runBlocking {
val result = runCatching {
callBlockWithRecovery(block)
}
assertTrue(result.isFailure, "Block should have failed")
val e = result.exceptionOrNull()!!
assertEquals(E::class, e::class)
val cause = e.cause
assertNotNull(cause, "Exception should have cause: $e")
assertEquals(e.message, cause.message)
assertEquals(E::class, cause::class)
}
// KLUDGE: A separate function with state-machine to ensure coroutine DebugMetadata is generated. See KT-41789
private suspend fun callBlockWithRecovery(block: () -> Unit) {
yield()
// use withContext to perform switch between coroutines and thus trigger exception recovery machinery
withContext(NonCancellable) {
block()
}
}
}
|