Skip to content

Commit

Permalink
Reduce duplicated code amongst the inline snapshots.
Browse files Browse the repository at this point in the history
  • Loading branch information
nedtwigg committed Dec 19, 2023
1 parent 55fdebe commit f1437b3
Showing 1 changed file with 22 additions and 22 deletions.
44 changes: 22 additions & 22 deletions selfie-runner-junit5/src/main/kotlin/com/diffplug/selfie/Selfie.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,26 @@ object Selfie {
fun <T> expectSelfie(actual: T, snapshotter: Snapshotter<T>) =
DiskSelfie(snapshotter.snapshot(actual))

/** Implements the inline snapshot whenever a match fails. */
private fun <T : Any> toBeDidntMatch(expected: T?, actual: T, format: LiteralFormat<T>): T {
if (RW.isWrite) {
Router.writeInline(recordCall(), LiteralValue(expected, actual, format))
return actual
} else {
if (expected == null) {
throw AssertionFailedError(
"`.toBe_TODO()` was called in `read` mode, try again with selfie in write mode")
} else {
throw AssertionFailedError(
"Inline literal did not match the actual value", expected, actual)
}
}
}

class StringSelfie(private val actual: String) : DiskSelfie(Snapshot.of(actual)) {
fun toBe(expected: String): String = TODO()
fun toBe_TODO(): String = TODO()
fun toBe_TODO() = toBeDidntMatch(null, actual, LiteralString)
infix fun toBe(expected: String) =
if (actual == expected) expected else toBeDidntMatch(expected, actual, LiteralString)
}

@JvmStatic fun expectSelfie(actual: String) = StringSelfie(actual)
Expand All @@ -63,26 +80,9 @@ object Selfie {
@JvmStatic fun expectSelfie(actual: ByteArray) = BinarySelfie(actual)

class IntSelfie(private val actual: Int) {
fun toBe_TODO(): Int = toBeDidntMatch(null)
infix fun toBe(expected: Int): Int =
if (actual == expected) expected
else {
toBeDidntMatch(expected)
}
private fun toBeDidntMatch(expected: Int?): Int {
if (RW.isWrite) {
Router.writeInline(recordCall(), LiteralValue(expected, actual, LiteralInt))
return actual
} else {
if (expected == null) {
throw AssertionFailedError(
"`.toBe_TODO()` was called in `read` mode, try again with selfie in write mode")
} else {
throw AssertionFailedError(
"Inline literal did not match the actual value", expected, actual)
}
}
}
fun toBe_TODO() = toBeDidntMatch(null, actual, LiteralInt)
infix fun toBe(expected: Int) =
if (actual == expected) expected else toBeDidntMatch(expected, actual, LiteralInt)
}

@JvmStatic fun expectSelfie(actual: Int) = IntSelfie(actual)
Expand Down

0 comments on commit f1437b3

Please sign in to comment.