Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
Adven27 committed Jan 26, 2024
1 parent ba64166 commit 1bf5ddc
Show file tree
Hide file tree
Showing 15 changed files with 202 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ internal class ExamExampleListener(private val skipDecider: SkipDecider) : Examp
"data-summary-exception" to summary.exceptionCount.toString(),
"data-summary-status" to summary.implementationStatus.tag
)
card.first("div")?.let { title ->
card.firstOrNull("div")?.let { title ->
title.childs().first().let {
val txt = it.text()
it.removeChildren()
Expand All @@ -115,7 +115,7 @@ internal class ExamExampleListener(private val skipDecider: SkipDecider) : Examp
failureCount == 0L && exceptionCount == 0L && implementationStatus == EXPECTED_TO_PASS

private fun removeConcordionExpectedToFailWarning(card: Html) {
card.first("p")?.let { card.remove(it) }
card.firstOrNull("p")?.let { card.remove(it) }
}
}

Expand All @@ -131,7 +131,7 @@ class FocusOnErrorsListener : SpecificationProcessingListener {

failed.forEach { (id, summary) ->
val example = findExample(event.rootElement, id)
example?.first("p")?.first("a")?.invoke(
example?.firstOrNull("p")?.firstOrNull("a")?.invoke(
summary.successCount.toPill("success"),
summary.ignoredCount.toPill("secondary"),
summary.failureCount.toPill("warning"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import org.concordion.internal.util.Check

open class EqCommand(val verifier: ContentVerifier) : AssertEqualsCommand() {
companion object : KLogging() {
private fun objectToString(any: Any?): String = any?.toString() ?: "(null)"
fun objectToString(any: Any?): String = any?.toString() ?: "(null)"
}

override fun verify(command: CommandCall, eval: Evaluator, resultRecorder: ResultRecorder, fixture: Fixture) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ class Html(val el: Element) {

infix fun insteadOf(original: Html) = insteadOf(original.el)

fun first(tag: String): Html? {
fun firstOrNull(tag: String): Html? {
val first = el.childElements.firstOrNull { it.localName == tag }
return if (first == null) null else Html(first)
}
Expand All @@ -210,13 +210,13 @@ class Html(val el: Element) {
return if (last == null) null else Html(last)
}

fun firstOptional(tag: String): Optional<Html> = Optional.ofNullable(first(tag))
fun firstOptional(tag: String): Optional<Html> = Optional.ofNullable(firstOrNull(tag))

fun all(tag: String): Collection<Html> {
return el.childElements.asList().filter { it.localName == tag }.map { Html(it) }
}

fun firstOrThrow(tag: String) = first(tag) ?: error("<$tag> tag is required")
fun firstOrThrow(tag: String) = firstOrNull(tag) ?: error("<$tag> tag is required")

fun removeChildren(): Html {
moveChildrenTo(Html("tmp"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ open class DbSetTableParser : DbSetCommand.Parser {
strategy = context[DbCommand.OPERATION]?.let { SeedStrategy.valueOf(it.uppercase()) }
?: SeedStrategy.CLEAN_INSERT
),
caption = context.el.first("caption")!!.text().ifBlank { null }
caption = context.el.firstOrNull("caption")?.text()
)

private fun table(context: Context): ITable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ open class DbShowCommand(
override fun parse(context: Context) = Model(
ds = context[DS],
table = context.expression,
caption = context.el.first("caption")!!.text(),
caption = context.el.firstOrNull("caption")!!.text(),
where = context[WHERE],
createDataSet = context[CREATE_DATASET].toBoolean(),
saveToResources = context[SAVE_TO_RESOURCES],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class DbCheckParser : DbCheckCommand.Parser {
}

override fun parse(context: Context): DbCheckCommand.Model = DbCheckCommand.Model(
caption = context.el.first("caption")!!.text(),
caption = context.el.firstOrNull("caption")?.text(),
expectation = TableExpectation(
ds = context[DS],
table = table(context.expression, context.el, context.eval),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package io.github.adven27.concordion.extensions.exam.mq.commands
import com.github.jknack.handlebars.internal.text.StringEscapeUtils.escapeJava
import io.github.adven27.concordion.extensions.exam.core.Content
import io.github.adven27.concordion.extensions.exam.core.ContentVerifier.Fail
import io.github.adven27.concordion.extensions.exam.core.commands.EqCommand.Companion.objectToString
import io.github.adven27.concordion.extensions.exam.core.commands.Verifier
import io.github.adven27.concordion.extensions.exam.core.html.Html
import io.github.adven27.concordion.extensions.exam.core.html.div
Expand Down Expand Up @@ -36,7 +37,8 @@ interface MqCheckRenderer {
params = Result.success(it.params),
content = Result.success(Content(body = it.body, type = it.content.type))
)
}
},
"success"
).toHtml()
)
parent().remove(this)
Expand All @@ -61,7 +63,7 @@ interface MqCheckRenderer {
}

private fun renderMessageContentError(fail: MessageVerifyingError) =
template(fail.queue, fail.expected).toHtml()
template(fail.queue, fail.expected, "failure").toHtml()

private fun renderSizeError(fail: SizeVerifyingError) =
errorMessage(
Expand All @@ -77,7 +79,8 @@ interface MqCheckRenderer {
params = Result.success(it.params),
content = Result.success(Content(body = it.body, type = it.content.type))
)
}
},
"success"
).toHtml(),
span("but was:"),
template(
Expand All @@ -88,36 +91,37 @@ interface MqCheckRenderer {
params = Result.success(it.params),
content = Result.success(Content.Text(it.body))
)
}
},
"failure"
).toHtml()
)
).second
}

fun template(name: String, messages: List<MessageVerifyResult>) = //language=html
fun template(name: String, messages: List<MessageVerifyResult>, style: String) = //language=html
"""
<div class="mq-check">
<table class="tableblock frame-ends grid-rows stretch">
<caption><i class="fa fa-envelope-open me-1"> </i><span>$name</span></caption>
<tbody> ${renderMessages(messages)} </tbody>
<tbody> ${renderMessages(messages, style)} </tbody>
</table>
</div>
""".trimIndent()

// language=html
private fun renderMessages(messages: List<MessageVerifyResult>) = messages.joinToString("\n") { r ->
private fun renderMessages(messages: List<MessageVerifyResult>, style: String) = messages.joinToString("\n") { r ->
"""
<tr><td class='exp-body'>
${r.params.fold(::renderParams, ::renderError)}
${r.headers.fold(::renderHeaders, ::renderError)}
${r.content.fold(::renderContent, ::renderContentError)}
${r.params.fold({ renderProps("Params", it, style) }, ::renderError)}
${r.headers.fold({ renderProps("Headers", it, style) }, ::renderError)}
${r.content.fold({ renderContent(it, style) }, ::renderContentError)}
</td></tr>
""".trimIndent()
}.ifEmpty { """<tr><td class='exp-body success'>EMPTY</td></tr>""" }
}.ifEmpty { """<tr><td class='exp-body $style'>EMPTY</td></tr>""" }

// language=html
private fun renderContent(content: Content) =
"""<div class="${content.type} success"></div>""".toHtml().text(content.pretty()).el.toXML()
private fun renderContent(content: Content, style: String) =
"""<div class="${content.type} $style"></div>""".toHtml().text(content.pretty()).el.toXML()

// language=html
private fun renderContentError(error: Throwable) = when (error) {
Expand All @@ -134,33 +138,24 @@ interface MqCheckRenderer {
}

// language=html
private fun renderHeaders(headers: Map<String, String?>) = if (headers.isNotEmpty()) {
"""
<table class="table table-sm caption-top">
<caption class="small">Headers</caption>
<tbody> ${toRows(headers)} </tbody>
</table>
""".trimIndent()
} else {
""
}

// language=html
private fun renderParams(params: Map<String, String?>) = if (params.isNotEmpty()) {
"""
<table class="table table-sm caption-top">
<caption class="small">Params</caption>
<tbody> ${toRows(params)} </tbody>
</table>
""".trimIndent()
} else {
""
}
private fun renderProps(caption: String, props: Map<String, String?>, style: String) =
props.takeIf { it.isNotEmpty() }?.let {
"""
<table class="table table-sm caption-top">
<caption class="small">$caption</caption>
<tbody> ${toRows(props, style)} </tbody>
</table>
""".trimIndent()
} ?: ""

private fun renderError(error: Throwable) = errorMessage(message = error.rootCauseMessage()).second.el.toXML()

// language=html
private fun toRows(headers: Map<String, String?>) = headers.entries.joinToString("\n") { (k, v) ->
"""<tr><td class="success">$k</td><td class="success"><pre><![CDATA[${escapeJava(v)}]]></pre></td></tr>"""
private fun toRows(headers: Map<String, String?>, style: String) = headers.entries.joinToString("\n") { (k, v) ->
"<tr><td class='$style'>$k</td><td class='$style'>${renderValue(v)}</td></tr>"
}

fun renderValue(v: String?): String = runCatching { pre(objectToString(v)).el.toXML() }
.recoverCatching { pre(escapeJava(objectToString(v))).el.toXML() }
.getOrElse { pre(it.rootCauseMessage()).el.toXML() }
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ open class RawHttpParser(
override fun parseRequest(r: String) = parse(r).let { request ->
HttpRequest(
method = request.method,
url = request.uri.path,
url = request.uri.let{ "${it.path}?${it.query}" },
httpVersion = request.startLine.httpVersion.toString(),
body = request.body.getOrNull()?.decodeBodyToString(StandardCharsets.UTF_8),
headers = request.headers.headerNames.associateWith { request.headers.get(it) }
Expand Down
1 change: 1 addition & 0 deletions example/src/test/kotlin/specs/Specs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import net.javacrumbs.jsonunit.core.Option.IGNORING_EXTRA_FIELDS
import java.util.ArrayDeque

class Nested : Specs()
class MqCheckFailures : Specs()

@Suppress("FunctionOnlyReturningConstant")
open class Specs : AbstractSpecs() {
Expand Down
125 changes: 125 additions & 0 deletions example/src/test/resources/specs/MqCheckFailures.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
= Message Queue Check Failures

[#before]
.Before each example
****
[e-mq-clean]#myQueue# is empty.
****

[.ExpectedToFail]
.Surplus messages
====
.Got message
[source,json,e-mq-set=myQueue]
----
{ "a": 1, "b": "some" }
----

.Expected no messages
[caption=, e-mq-check=myQueue]
|===
|===
====

[.ExpectedToFail]
.Missing messages
====
Got no messages.

.Expected single message
[cols="a", caption=, e-mq-check=myQueue]
|===
|[source,json,e-mq-set=myQueue]
----
{ "a": 1, "b": "some" }
----
|===
====

[.ExpectedToFail]
.Wrong payload
====
.Got message
[source,json,e-mq-set=myQueue]
----
{ "a": 1, "b": "some" }
----

[.ExpectedToFail]
.Wrong message body expectations
[cols="a", caption=, e-mq-check=myQueue]
|===
|[source,json]
----
{ "a": 1 }
----
|===
====

[.ExpectedToFail]
.Wrong headers or params
====
.Got messages:
[cols="a", grid=rows, frame=ends, caption=, e-mq-set=myQueue]
|===
|
[.headers]
.Headers
[cols="h,1", caption=]
,===
h1, {{isoDate (at '-1d')}}
h2, 2
,===

[source,json]
----
{ "a": 1, "b": "some" }
----

|
[.params]
.Params
[cols="h,1", caption=]
,===
key, some-kafka-message-key
partition, 1
,===

[source,json]
----
{ "a": 1, "b": "some" }
----
|===

.Wrong expectations in headers and params
[cols="a", grid=rows, frame=ends, caption=, e-mq-check=myQueue]
|===
|
[.headers]
.Headers
[cols="h,1", caption=]
,===
h1, {{isoDate (at)}}
h2, 3
,===

[source,json]
----
{ "a": 1, "b": "some" }
----

|
[.params]
.Params
[cols="h,1", caption=]
,===
key, wrong
partition, 2
,===

[source,json]
----
{ "a": 1, "b": "some" }
----
|===
====
8 changes: 4 additions & 4 deletions example/src/test/resources/specs/Specs.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
[.lead]
Extension for https://github.com/concordion/concordion/[Concordion BDD framework]

include::overview.adoc[]
// include::overview.adoc[]

include::plugin-core.adoc[]

'''

include::plugin-ws.adoc[]
// include::plugin-ws.adoc[]

'''

include::plugin-db.adoc[]
// include::plugin-db.adoc[]

'''

include::plugin-mq.adoc[]
// include::plugin-mq.adoc[]
Loading

0 comments on commit 1bf5ddc

Please sign in to comment.