Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Map.IsSimilarTo assertion #304

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions strikt-core/src/main/kotlin/strikt/assertions/Map.kt
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,36 @@ fun <T : Map<K, V>, K, V> Builder<T>.hasEntry(
value: V
): Builder<T> = apply { containsKey(key)[key].isEqualTo(value) }

/**
* Asserts that all key-value pairs of [expected] _and no others_ are present in
* the subject map.
*/
infix fun <T : Map<in K, V>, K, V> Assertion.Builder<T>.isSimilarTo(expected: Map<K, V>): Assertion.Builder<T> =
compose(
"contains exactly the pairs %s in any order",
expected
) { subject ->
val remaining = subject.toMutableMap()
expected.forEach { entry: Map.Entry<K, V> ->
assert("contains %s", entry) {
if (remaining.remove(entry.key, entry.value)) {
pass()
} else {
fail()
}
}
}
assert("contains no further pairs") {
if (remaining.isEmpty()) {
pass()
} else {
fail(actual = remaining)
}
}
} then {
if (allPassed) pass() else fail()
}

/**
* Maps an assertion on a map to an assertion on its keys.
*
Expand Down