From: David ‘Bombe’ Roden Date: Thu, 4 Apr 2024 15:50:54 +0000 (+0200) Subject: 🚧 Add state for JSON objects X-Git-Tag: v2~4 X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=6cc668aa117e70ac390e5a669d5e6ceb8822b3a7;p=rhynodge.git 🚧 Add state for JSON objects --- diff --git a/build.gradle b/build.gradle index 20219b8..85cf007 100644 --- a/build.gradle +++ b/build.gradle @@ -57,6 +57,7 @@ dependencies { testImplementation group: "junit", name: "junit", version: "4.13.2" testImplementation group: "org.hamcrest", name: "hamcrest-library", version: "1.3" testImplementation group: "org.mockito", name: "mockito-core", version: "5.11.0" + testImplementation group: "com.spotify", name: "hamcrest-jackson", version: "1.3.2" } task fatJar(type: Jar) { diff --git a/src/main/kotlin/net/pterodactylus/rhynodge/states/JsonState.kt b/src/main/kotlin/net/pterodactylus/rhynodge/states/JsonState.kt new file mode 100644 index 0000000..8824729 --- /dev/null +++ b/src/main/kotlin/net/pterodactylus/rhynodge/states/JsonState.kt @@ -0,0 +1,10 @@ +package net.pterodactylus.rhynodge.states + +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.JsonNode + +class JsonState(@JsonProperty("json") val jsonNode: JsonNode) : AbstractState(true) { + + override fun plainText() = jsonNode.toPrettyString()!! + +} diff --git a/src/test/kotlin/net/pterodactylus/rhynodge/states/JsonStateTest.kt b/src/test/kotlin/net/pterodactylus/rhynodge/states/JsonStateTest.kt new file mode 100644 index 0000000..b21095e --- /dev/null +++ b/src/test/kotlin/net/pterodactylus/rhynodge/states/JsonStateTest.kt @@ -0,0 +1,37 @@ +package net.pterodactylus.rhynodge.states + +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import com.spotify.hamcrest.jackson.JsonMatchers.jsonObject +import org.hamcrest.MatcherAssert.assertThat +import org.junit.Test +import java.io.StringWriter + +class JsonStateTest { + + @Test + fun `json state can be serialized`() { + val jsonState = JsonState(jsonObject) + StringWriter().use { stringWriter -> + objectMapper.writeValue(stringWriter, jsonState) + val deserializedState = objectMapper.readValue(stringWriter.toString(), AbstractState::class.java) as JsonState + assertThat(deserializedState.jsonNode, jsonObject(jsonObject)) + } + } + + private val jsonObject = objectMapper.createObjectNode() + .put("state", "foo") + .also { + it.putArray("list") + .add("value1") + .add("value2") + }.also { + it.putObject("object") + .put("foo", true) + .put("bar", "yes") + .put("baz", 1.5) + .putNull("qux") + } + +} + +private val objectMapper = jacksonObjectMapper()