Move failWithErrorReason to a common place

This is a shared public utility. Its main utility is for methods
that can fail, have an error message of their own, and also want
to take an error message from a caller and want to combine them.
Example use :
fun <T> assertEquals(expected: T, actual: T, msg: String? = null) {
  if (expected != null) {
    failWithErrorReason(msg, "Expected $expected, got $actual")
  }
}
...which allows someone to say
assertEquals(a, b, "Checking a vs b")

Test: TH
Flag: EXEMPT test-only change
Change-Id: Id3eaa8384b4177f38f13576d9b4d742c52027ae4
This commit is contained in:
Chalard Jean 2025-04-27 11:01:10 +09:00
commit c96d1ae0e6
3 changed files with 10 additions and 14 deletions

View file

@ -70,7 +70,7 @@ open class RecorderCallback private constructor(
data class Reserved private constructor(
override val network: Network,
val caps: NetworkCapabilities
): CallbackEntry() {
) : CallbackEntry() {
constructor(caps: NetworkCapabilities) : this(NULL_NETWORK, caps)
}
data class Available(override val network: Network) : CallbackEntry()
@ -399,12 +399,6 @@ open class TestableNetworkCallback private constructor(
}
} as T
// "Nothing" is the return type to declare a function never returns a value.
fun failWithErrorReason(errorMsg: String?, errorReason: String): Nothing {
val message = if (errorMsg != null) "$errorMsg : $errorReason" else errorReason
fail(message)
}
inline fun <reified T : CallbackEntry> expect(
network: HasNetwork,
timeoutMs: Long = defaultTimeoutMs,

View file

@ -56,12 +56,6 @@ class TestableNetworkOfferCallback(
history.add(CallbackEntry.Unneeded(request))
}
// TODO : move to some utility, this is copied from TestableNetworkCallback
fun failWithErrorReason(errorMsg: String?, errorReason: String): Nothing {
val message = if (errorMsg != null) "$errorMsg : $errorReason" else errorReason
fail(message)
}
inline fun <reified T : CallbackEntry> expect(
errorMsg: String? = null,
predicate: (T) -> Boolean = { true }

View file

@ -142,4 +142,12 @@ fun assertEventuallyTrue(
}
Thread.sleep(pollIntervalMs)
}
}
}
// "Nothing" is the return type to declare a function never returns a value. This is useful
// because the compiler will know the branch of the code calling this does not return, which
// lets check exhaustivity, infer return types, nullability and smart casts.
fun failWithErrorReason(errorMsg: String?, errorReason: String): Nothing {
val message = if (errorMsg != null) "$errorMsg : $errorReason" else errorReason
fail(message)
}