Skip to content

Commit

Permalink
test(model): Factor out toJson()
Browse files Browse the repository at this point in the history
Add an analog function to `toYaml()` for readability, and for re-use in
upcoming changes.

Note: Use `true` as default value for `prettyPrint`, because that best
matches the YAML output which is inherently pretty, and also because
the function is primarily used in tests where a pretty JSON is easier to
read in diffs.

Signed-off-by: Frank Viernau <[email protected]>
  • Loading branch information
fviernau committed Jan 17, 2025
1 parent 255d294 commit 7d817f8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
10 changes: 10 additions & 0 deletions model/src/main/kotlin/Mappers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,14 @@ inline fun <reified T> String.fromYaml(): T = yamlMapper.readValue(this)

fun Any?.toYaml(): String = yamlMapper.writeValueAsString(this)

fun Any?.toJson(prettyPrint: Boolean = true): String {
val writer = if (prettyPrint) {
jsonMapper.writerWithDefaultPrettyPrinter()
} else {
jsonMapper.writer()
}

return writer.writeValueAsString(this)
}

fun String.readJsonTree(): JsonNode = jsonMapper.readTree(this)
6 changes: 3 additions & 3 deletions model/src/test/kotlin/ProvenanceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import org.ossreviewtoolkit.utils.common.normalizeLineBreaks
class ProvenanceTest : WordSpec({
"UnknownProvenance" should {
val provenance = UnknownProvenance
val json = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(provenance)
val json = provenance.toJson()

"be serializable" {
json shouldBe "{ }"
Expand All @@ -52,7 +52,7 @@ class ProvenanceTest : WordSpec({
)
)

val json = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(provenance)
val json = provenance.toJson()

"be serializable" {
json.normalizeLineBreaks() shouldBe """
Expand Down Expand Up @@ -92,7 +92,7 @@ class ProvenanceTest : WordSpec({
resolvedRevision = "resolvedRevision"
)

val json = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(provenance)
val json = provenance.toJson()

"be serializable" {
json.normalizeLineBreaks() shouldBe """
Expand Down

0 comments on commit 7d817f8

Please sign in to comment.