|
1 | 1 | /* |
2 | | - * Copyright (C) 2021-2022 Rick Busarow |
| 2 | + * Copyright (C) 2021-2023 Rick Busarow |
3 | 3 | * Licensed under the Apache License, Version 2.0 (the "License"); |
4 | 4 | * you may not use this file except in compliance with the License. |
5 | 5 | * You may obtain a copy of the License at |
|
15 | 15 |
|
16 | 16 | package modulecheck.testing |
17 | 17 |
|
| 18 | +import io.kotest.assertions.asClue |
| 19 | +import io.kotest.matchers.shouldNotBe |
18 | 20 | import org.junit.jupiter.api.fail |
19 | 21 |
|
20 | 22 | fun <T : Any> T?.requireNotNullOrFail( |
21 | 23 | lazyMessage: () -> String = { "The receiver cannot be null, but it was. ¯\\_(ツ)_/¯" } |
22 | 24 | ): T { |
23 | | - |
24 | 25 | if (this != null) return this |
25 | 26 |
|
26 | 27 | fail(lazyMessage) |
27 | 28 | } |
| 29 | + |
| 30 | +/** |
| 31 | + * Asserts that the receiver string is changed after calling [String.replace] |
| 32 | + * |
| 33 | + * @since 0.12.4 |
| 34 | + */ |
| 35 | +fun String.replaceOrFail(oldValue: String, replacement: String): String { |
| 36 | + return assertChanged( |
| 37 | + oldString = this@replaceOrFail, |
| 38 | + newString = replace(oldValue, replacement), |
| 39 | + token = oldValue, |
| 40 | + replacement = replacement |
| 41 | + ) |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Asserts that the receiver string is changed after calling [String.replace] |
| 46 | + * |
| 47 | + * @since 0.12.4 |
| 48 | + */ |
| 49 | +fun String.replaceOrFail(regex: Regex, replacement: String): String { |
| 50 | + return assertChanged( |
| 51 | + oldString = this@replaceOrFail, |
| 52 | + newString = replace(regex, replacement), |
| 53 | + token = regex, |
| 54 | + replacement = replacement |
| 55 | + ) |
| 56 | +} |
| 57 | + |
| 58 | +private fun assertChanged( |
| 59 | + oldString: String, |
| 60 | + newString: String, |
| 61 | + token: Any, |
| 62 | + replacement: String |
| 63 | +) = newString.also { new -> |
| 64 | + trimmedAssert { |
| 65 | + |
| 66 | + val tokenName = (if (token is Regex) "regex" else "oldValue").padStart(9) |
| 67 | + |
| 68 | + """ |
| 69 | + |String replacement did not change the original string. |
| 70 | + | |
| 71 | + | $tokenName: $token |
| 72 | + | replacement: $replacement |
| 73 | + | |
| 74 | + |original string (starting on the new line): |
| 75 | + |$oldString |
| 76 | + |____________________________________________________ |
| 77 | + |""".replaceIndentByMargin() |
| 78 | + .asClue { new shouldNotBe oldString } |
| 79 | + } |
| 80 | +} |
0 commit comments