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

package kotlinx.serialization

import kotlin.test.*

internal inline fun <reified T : Any> assertSerializedToBinaryAndRestored(
    original: T,
    serializer: KSerializer<T>,
    format: BinaryFormat,
    printResult: Boolean = false,
    hexResultToCheck: String? = null
) {
    val bytes = format.encodeToByteArray(serializer, original)
    val hexString = HexConverter.printHexBinary(bytes, lowerCase = true)
    if (printResult) {
        println("[Serialized form] $hexString")
    }
    if (hexResultToCheck != null) {
        assertEquals(
            hexResultToCheck.lowercase(),
            hexString,
            "Expected serialized binary to be equal in hex representation"
        )
    }
    val restored = format.decodeFromByteArray(serializer, bytes)
    if (printResult) println("[Restored form] $restored")
    assertEquals(original, restored)
}

inline fun <reified T : Throwable> assertFailsWithMessage(message: String, block: () -> Unit) {
    val exception = assertFailsWith(T::class, null, block)
    assertTrue(exception.message!!.contains(message), "Expected message '${exception.message}' to contain substring '$message'")
}