Skip to content

Commit

Permalink
Merge pull request #7 from ekino/single-json-object
Browse files Browse the repository at this point in the history
Support single json object in validation
  • Loading branch information
MrAolen authored Jan 16, 2020
2 parents a73960a + 8e55312 commit 9f553bb
Show file tree
Hide file tree
Showing 11 changed files with 88 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@ import com.ekino.oss.jcv.db.model.TableModel
import com.ekino.oss.jcv.db.util.ConverterUtil
import com.ekino.oss.jcv.db.util.JsonConverter
import com.ekino.oss.jcv.db.util.JsonConverter.compareJsonAndLogResult
import com.ekino.oss.jcv.db.util.takeIfIsJson
import com.ekino.oss.jcv.db.util.JsonConverter.formatInput
import org.assertj.core.api.AbstractAssert
import org.assertj.db.type.Source
import org.assertj.db.type.Table
import org.json.JSONArray
import org.json.JSONException
import org.skyscreamer.jsonassert.JSONCompareMode
import java.io.IOException
import java.io.InputStream
import java.sql.DriverManager
import java.util.HashMap
Expand Down Expand Up @@ -65,12 +64,11 @@ class DbComparatorAssertJ(
mapper
)

fun isValidAgainst(input: String) = input.takeIfIsJson()?.let { compareActualAndExcepted(it as JSONArray) } ?: throw DbAssertException(
"Unable to parse pg object to json"
fun isValidAgainst(input: String) = formatInput(input)?.let { compareActualAndExcepted(it) } ?: throw DbAssertException(
"Unable to parse expected result from string to json"
)

@Throws(IOException::class)
fun isValidAgainst(inputStream: InputStream) = compareActualAndExcepted(JsonConverter.loadJson(inputStream))
fun isValidAgainst(inputStream: InputStream) = isValidAgainst(JsonConverter.loadFileAsString(inputStream))

private fun compareActualAndExcepted(expected: JSONArray) {
isNotNull
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ import com.ekino.oss.jcv.db.cassandra.util.QueryConverter
import com.ekino.oss.jcv.db.exception.DbAssertException
import com.ekino.oss.jcv.db.util.JsonConverter
import com.ekino.oss.jcv.db.util.JsonConverter.compareJsonAndLogResult
import com.ekino.oss.jcv.db.util.takeIfIsJson
import org.json.JSONArray
import org.skyscreamer.jsonassert.JSONCompareMode
import java.io.IOException
import java.io.InputStream

class DbComparatorCassandra(
Expand All @@ -31,12 +29,11 @@ class DbComparatorCassandra(
fun assertThatQuery(select: Select) = DBComparatorBuilder.create().build(select.asCql())
}

fun isValidAgainst(input: String) = input.takeIfIsJson()?.let { compareActualAndExcepted(it as JSONArray) } ?: throw DbAssertException(
"Unable to parse expected result from string to json array"
fun isValidAgainst(input: String) = JsonConverter.formatInput(input)?.let { compareActualAndExcepted(it) } ?: throw DbAssertException(
"Unable to parse expected result from string to json"
)

@Throws(IOException::class)
fun isValidAgainst(inputStream: InputStream) = compareActualAndExcepted(JsonConverter.loadJson(inputStream))
fun isValidAgainst(inputStream: InputStream) = isValidAgainst(JsonConverter.loadFileAsString(inputStream))

private fun compareActualAndExcepted(expected: JSONArray) {
val actualJson = queryConverter.fromQueryToTableModel(query).getTableModelAsJson(mapper)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ import com.ekino.oss.jcv.db.exception.DbAssertException
import com.ekino.oss.jcv.db.model.RowModel
import com.ekino.oss.jcv.db.model.TableModel
import com.ekino.oss.jcv.db.util.JsonConverter
import com.ekino.oss.jcv.db.util.takeIfIsJson
import org.json.JSONArray
import org.skyscreamer.jsonassert.JSONCompareMode
import java.io.IOException
import java.io.InputStream

class DbComparatorAssert(private val actualJson: JSONArray, private val jsonComparator: JsonComparator) {
Expand All @@ -34,12 +32,11 @@ class DbComparatorAssert(private val actualJson: JSONArray, private val jsonComp
}
}

fun isValidAgainst(input: String) = input.takeIfIsJson()?.let { compareActualAndExcepted(it as JSONArray) } ?: throw DbAssertException(
"Unable to parse pg object to json"
fun isValidAgainst(input: String) = JsonConverter.formatInput(input)?.let { compareActualAndExcepted(it) } ?: throw DbAssertException(
"Unable to parse expected result from string to json"
)

@Throws(IOException::class)
fun isValidAgainst(inputStream: InputStream) = compareActualAndExcepted(JsonConverter.loadJson(inputStream))
fun isValidAgainst(inputStream: InputStream) = isValidAgainst(JsonConverter.loadFileAsString(inputStream))

private fun compareActualAndExcepted(expected: JSONArray) {
JsonConverter.compareJsonAndLogResult(actualJson, expected, jsonComparator)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.ekino.oss.jcv.db.util

import com.ekino.oss.jcv.core.JsonComparator
import com.ekino.oss.jcv.db.exception.DbAssertException
import com.fasterxml.jackson.databind.ObjectMapper
import org.json.JSONArray
import org.json.JSONException
Expand All @@ -21,31 +20,25 @@ object JsonConverter {
?.also { fail(it.fail("", expected, actual).message) }
}

@Throws(IOException::class)
fun loadJson(inputStream: InputStream): JSONArray {
val fileContent = fromInputStreamToString(inputStream).takeIfIsJson()
if (fileContent is JSONArray) {
return fileContent
} else {
throw DbAssertException("Unable to load JSON Array from input stream")
}
fun formatInput(input: String) = when (val json = input.takeIfIsJson()) {
is JSONObject -> JSONArray().put(json)
is JSONArray -> json
else -> null
}

@Throws(IOException::class)
private fun fromInputStreamToString(inputStream: InputStream) = inputStream.bufferedReader().use(BufferedReader::readText)
fun loadFileAsString(inputStream: InputStream) = inputStream.bufferedReader().use(BufferedReader::readText)
}

fun Any.toJsonObject() = JSONObject(ObjectMapper().writeValueAsString(this))
fun Any.toJsonArray() = JSONArray(ObjectMapper().writeValueAsString(this))

fun String.takeIfIsJson(): Any? {
try {
val jsonObject = JSONTokener(this).nextValue()
if (jsonObject is String && jsonObject == this) {
return null
}
return jsonObject
} catch (e: JSONException) {
return null
fun String.takeIfIsJson() = try {
when (val json = JSONTokener(this).nextValue()) {
is String -> null
is JSONObject, is JSONArray -> json
else -> null
}
} catch (e: JSONException) {
null
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ package com.ekino.oss.jcv.db.util

import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isFailure
import assertk.assertions.isNull
import com.ekino.oss.jcv.db.mapper.TypeMapper
import com.ekino.oss.jcv.db.model.RowModel
import com.ekino.oss.jcv.db.model.TableModel
import com.ekino.oss.jcv.db.util.JsonConverter.loadJson
import com.ekino.oss.jcv.db.util.JsonConverter.formatInput
import org.json.JSONArray
import org.json.JSONObject
import org.junit.jupiter.api.Test
import java.io.BufferedReader

class JsonConverterTest {

Expand All @@ -31,18 +31,22 @@ class JsonConverterTest {

@Test
fun `Should load file and return a json array`() {
val expectedJsonArray = JSONArray("""[{ "id" : 1 }]""")
assertThat(loadJson(this::class.java.classLoader.getResourceAsStream("test-file.json")!!).toString()).isEqualTo(expectedJsonArray.toString())
val expectedResult = JSONArray("""[{"id":1}]""")
val inputString = this::class.java.classLoader.getResourceAsStream("test-file.json")!!.bufferedReader().use(BufferedReader::readText)
assertThat(formatInput(inputString).toString()).isEqualTo(expectedResult.toString())
}

@Test
fun `Should get an error when trying to load a json object`() {
assertThat { loadJson(this::class.java.classLoader.getResourceAsStream("test-file-object.json")!!) }.isFailure()
val expectedResult = JSONArray("""[{"id":1}]""")
val inputString = this::class.java.classLoader.getResourceAsStream("test-file-object.json")!!.bufferedReader().use(BufferedReader::readText)
assertThat(formatInput(inputString).toString()).isEqualTo(expectedResult.toString())
}

@Test
fun `Should get an error when trying to load an invalid json`() {
assertThat { loadJson(this::class.java.classLoader.getResourceAsStream("test-file-invalid.json")!!) }.isFailure()
val inputString = this::class.java.classLoader.getResourceAsStream("test-file-invalid.json")!!.bufferedReader().use(BufferedReader::readText)
assertThat(formatInput(inputString)).isNull()
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@ import com.ekino.oss.jcv.db.jdbc.util.DBComparatorBuilder
import com.ekino.oss.jcv.db.jdbc.util.QueryConverter
import com.ekino.oss.jcv.db.util.JsonConverter
import com.ekino.oss.jcv.db.util.JsonConverter.compareJsonAndLogResult
import com.ekino.oss.jcv.db.util.takeIfIsJson
import org.json.JSONArray
import org.skyscreamer.jsonassert.JSONCompareMode
import java.io.IOException
import java.io.InputStream
import java.sql.Connection

Expand All @@ -27,12 +25,11 @@ class DbComparatorJDBC constructor(
fun assertThatQuery(query: String): DbComparatorJDBC = DBComparatorBuilder.create().build(query)
}

fun isValidAgainst(input: String) = input.takeIfIsJson()?.let { compareActualAndExcepted(it as JSONArray) } ?: throw DbAssertException(
"Unable to parse string to json array"
fun isValidAgainst(input: String) = JsonConverter.formatInput(input)?.let { compareActualAndExcepted(it) } ?: throw DbAssertException(
"Unable to parse expected result from string to json"
)

@Throws(IOException::class)
fun isValidAgainst(inputStream: InputStream) = compareActualAndExcepted(JsonConverter.loadJson(inputStream))
fun isValidAgainst(inputStream: InputStream) = isValidAgainst(JsonConverter.loadFileAsString(inputStream))

fun using(comparator: JsonComparator) =
DbComparatorJDBC(query, queryConverter, comparator, customMapper)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,21 @@ class MSSQLTypeTest {
.isValidAgainst(expected)
}

@Test
fun `Should valid single row against json object`() {
val expected = // language=json
"""
{
"id": "642A00A5-18F2-47CF-9E5C-0161156FF0A0",
"criteria_number": 3,
"content": "content 4"
}
""".trimIndent()

assertThatQuery("SELECT * FROM table_test WHERE id='642A00A5-18F2-47CF-9E5C-0161156FF0A0'")
.isValidAgainst(expected)
}

private fun customValidator(): JsonValidator<String> {
return validator {
templatedValidator<String>("custom_notempty", comparator { actual, expected ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,21 @@ class MySQLTypeTest {
.isValidAgainst(expected)
}

@Test
fun `Should valid single row against json object`() {
val expected = // language=json
"""
{
"id": 1234,
"criteria_number": 0,
"content": "content 1"
}
""".trimIndent()

assertThatQuery("SELECT * FROM table_test WHERE id=1234")
.isValidAgainst(expected)
}

private fun customValidator(): JsonValidator<String> {
return validator {
templatedValidator<String>("custom_notempty", comparator { actual, expected ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,21 @@ class PostgresTypeTest {
.isValidAgainst(expected)
}

@Test
fun `Should valid single row against json object`() {
val expected = // language=json
"""
{
"id": "07621b34-35dc-4b8f-94f4-b0f7e98b4088",
"criteria_number": 0,
"content": "content 1"
}
""".trimIndent()

assertThatQuery("SELECT * FROM table_test WHERE id='07621b34-35dc-4b8f-94f4-b0f7e98b4088'")
.isValidAgainst(expected)
}

private fun customValidator(): JsonValidator<String> {
return validator {
templatedValidator<String>("custom_notempty", comparator { actual, expected ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@ import com.ekino.oss.jcv.db.mongo.util.DBComparatorBuilder
import com.ekino.oss.jcv.db.mongo.util.MongoConverter
import com.ekino.oss.jcv.db.util.JsonConverter
import com.ekino.oss.jcv.db.util.JsonConverter.compareJsonAndLogResult
import com.ekino.oss.jcv.db.util.takeIfIsJson
import com.mongodb.client.FindIterable
import org.bson.Document
import org.json.JSONArray
import org.skyscreamer.jsonassert.JSONCompareMode
import java.io.IOException
import java.io.InputStream

class DbComparatorMongo(
Expand All @@ -27,15 +25,14 @@ class DbComparatorMongo(
fun assertThatCollection(collection: FindIterable<Document>) = DBComparatorBuilder.create().build(collection)

@JvmStatic
fun assertThatCollection(document: Document) = DBComparatorBuilder.create().build(document)
fun assertThatCollection(document: Document?) = document?.let { DBComparatorBuilder.create().build(it) } ?: throw DbAssertException("Mongo document is null")
}

fun isValidAgainst(input: String) = input.takeIfIsJson()?.let { compareActualAndExcepted(it as JSONArray) } ?: throw DbAssertException(
"Unable to parse expected result from string to json array"
fun isValidAgainst(input: String) = JsonConverter.formatInput(input)?.let { compareActualAndExcepted(it) } ?: throw DbAssertException(
"Unable to parse expected result from string to json"
)

@Throws(IOException::class)
fun isValidAgainst(inputStream: InputStream) = compareActualAndExcepted(JsonConverter.loadJson(inputStream))
fun isValidAgainst(inputStream: InputStream) = isValidAgainst(JsonConverter.loadFileAsString(inputStream))

private fun compareActualAndExcepted(expected: JSONArray) {
val actualJson = mongoConverter.convertContentToTableModel(collection).getTableModelAsJson(mapper)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,10 @@ class MongoAssertDB {

val expected = // language=json
"""
[
{
"name": "test-mongo-db",
"_id": "{#mongo_id#}"
}
]
{
"name": "test-mongo-db",
"_id": "{#mongo_id#}"
}
""".trimIndent()

DbComparatorMongo.assertThatCollection(database.getCollection("testCollection").find(eq("name", "test-mongo-db")).first()).isValidAgainst(expected)
Expand Down

0 comments on commit 9f553bb

Please sign in to comment.