From 23d67c304f7bcc66ce8d0de649bb83b13e461461 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Sat, 6 Jan 2024 00:31:00 -0500 Subject: [PATCH] Switch to assertFailsWith (#8177) * Switch to assertk.fail * Use assertFailsWith * More assertFailsWith * Use more assertFailsWith * More assertFailsWith * More assertFailsWith * Native image dependencies * Move JUnit dependency * Don't lock in a specific implementation class * Missing finally --- mockwebserver-deprecated/build.gradle.kts | 2 + .../mockwebserver/MockWebServerTest.kt | 8 +- mockwebserver/build.gradle.kts | 2 + .../java/mockwebserver3/MockWebServerTest.kt | 8 +- native-image-tests/build.gradle.kts | 2 + okhttp-brotli/build.gradle.kts | 2 + .../okhttp3/brotli/BrotliInterceptorTest.kt | 8 +- okhttp-coroutines/build.gradle.kts | 3 +- .../test/kotlin/okhttp3/SuspendCallTest.kt | 6 +- okhttp-dnsoverhttps/build.gradle.kts | 2 + .../dnsoverhttps/DnsRecordCodecTest.kt | 8 +- okhttp-testing-support/build.gradle.kts | 2 + .../okhttp3/OkHttpClientTestRuleTest.kt | 7 +- okhttp-tls/build.gradle.kts | 2 + .../java/okhttp3/tls/internal/der/DerTest.kt | 87 +++--- .../test/java/okhttp3/CacheControlJvmTest.kt | 6 +- okhttp/src/test/java/okhttp3/CacheTest.kt | 34 +-- .../src/test/java/okhttp3/CallKotlinTest.kt | 18 +- okhttp/src/test/java/okhttp3/CallTest.kt | 206 ++++++------- .../okhttp3/CertificateChainCleanerTest.kt | 10 +- .../java/okhttp3/CertificatePinnerTest.kt | 54 +--- .../java/okhttp3/ConnectionCoalescingTest.kt | 29 +- .../java/okhttp3/ConnectionListenerTest.kt | 11 +- .../test/java/okhttp3/ConnectionReuseTest.kt | 15 +- .../test/java/okhttp3/ConnectionSpecTest.kt | 12 +- okhttp/src/test/java/okhttp3/CookieTest.kt | 19 +- okhttp/src/test/java/okhttp3/CookiesTest.kt | 4 +- .../src/test/java/okhttp3/DispatcherTest.kt | 11 +- okhttp/src/test/java/okhttp3/DuplexTest.kt | 38 ++- .../test/java/okhttp3/EventListenerTest.kt | 46 +-- .../src/test/java/okhttp3/FastFallbackTest.kt | 9 +- okhttp/src/test/java/okhttp3/HandshakeTest.kt | 13 +- .../src/test/java/okhttp3/HeadersJvmTest.kt | 26 +- okhttp/src/test/java/okhttp3/HeadersTest.kt | 95 +++--- .../test/java/okhttp3/InsecureForHostTest.kt | 10 +- .../src/test/java/okhttp3/InterceptorTest.kt | 54 ++-- .../test/java/okhttp3/MultipartBodyTest.kt | 17 +- .../test/java/okhttp3/MultipartReaderTest.kt | 55 ++-- .../src/test/java/okhttp3/OkHttpClientTest.kt | 45 ++- .../test/java/okhttp3/RequestCommonTest.kt | 30 +- okhttp/src/test/java/okhttp3/RequestTest.kt | 30 +- .../test/java/okhttp3/ResponseBodyJvmTest.kt | 30 +- .../okhttp3/ServerTruncatesRequestTest.kt | 16 +- .../test/java/okhttp3/URLConnectionTest.kt | 272 +++++++----------- .../okhttp3/UrlComponentEncodingTester.kt | 5 +- .../java/okhttp3/WholeOperationTimeoutTest.kt | 45 ++- .../internal/cache/DiskLruCacheTest.kt | 107 +++---- .../internal/cache2/FileOperatorTest.kt | 15 +- .../java/okhttp3/internal/cache2/RelayTest.kt | 6 +- .../internal/concurrent/TaskRunnerTest.kt | 7 +- .../FastFallbackExchangeFinderTest.kt | 33 +-- .../internal/connection/RouteSelectorTest.kt | 22 +- .../java/okhttp3/internal/http/CancelTest.kt | 20 +- .../okhttp3/internal/http/StatusLineTest.kt | 7 +- .../internal/http/ThreadInterruptTest.kt | 13 +- .../okhttp3/internal/http2/BaseTestHandler.kt | 24 +- .../java/okhttp3/internal/http2/HpackTest.kt | 51 ++-- .../internal/http2/Http2ConnectionTest.kt | 116 +++----- .../java/okhttp3/internal/http2/Http2Test.kt | 87 +++--- .../internal/http2/HttpOverHttp2Test.kt | 85 +++--- .../publicsuffix/PublicSuffixDatabaseTest.kt | 13 +- .../CertificatePinnerChainValidationTest.kt | 57 ++-- .../okhttp3/internal/tls/ClientAuthTest.kt | 67 +++-- .../ws/MessageDeflaterInflaterTest.kt | 10 +- .../okhttp3/internal/ws/RealWebSocketTest.kt | 6 +- .../okhttp3/internal/ws/WebSocketHttpTest.kt | 6 +- .../internal/ws/WebSocketReaderTest.kt | 135 ++++----- .../internal/ws/WebSocketWriterTest.kt | 38 ++- 68 files changed, 928 insertions(+), 1411 deletions(-) diff --git a/mockwebserver-deprecated/build.gradle.kts b/mockwebserver-deprecated/build.gradle.kts index 06ce4f0e1..b646bc09c 100644 --- a/mockwebserver-deprecated/build.gradle.kts +++ b/mockwebserver-deprecated/build.gradle.kts @@ -21,6 +21,8 @@ dependencies { testImplementation(projects.okhttpTestingSupport) testImplementation(projects.okhttpTls) + testImplementation(libs.kotlin.test.common) + testImplementation(libs.kotlin.test.junit) } mavenPublishing { diff --git a/mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt b/mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt index 541036cf8..e81e2411f 100644 --- a/mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt +++ b/mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt @@ -40,6 +40,7 @@ import java.util.Arrays import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import javax.net.ssl.HttpsURLConnection +import kotlin.test.assertFailsWith import okhttp3.Headers import okhttp3.Protocol import okhttp3.RecordingHostnameVerifier @@ -500,11 +501,10 @@ class MockWebServerTest { val connection = url.openConnection() as HttpURLConnection assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK) val refusedConnection = url.openConnection() as HttpURLConnection - try { + assertFailsWith { refusedConnection.getResponseCode() - fail("Second connection should be refused") - } catch (e: ConnectException) { - assertThat(e.message!!).contains("refused") + }.also { expected -> + assertThat(expected.message!!).contains("refused") } } diff --git a/mockwebserver/build.gradle.kts b/mockwebserver/build.gradle.kts index f6431f936..b50cd4c8c 100644 --- a/mockwebserver/build.gradle.kts +++ b/mockwebserver/build.gradle.kts @@ -21,6 +21,8 @@ dependencies { testImplementation(projects.okhttpTls) testRuntimeOnly(projects.mockwebserver3Junit5) testImplementation(libs.junit) + testImplementation(libs.kotlin.test.common) + testImplementation(libs.kotlin.test.junit) testImplementation(libs.assertk) } diff --git a/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt b/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt index 4c298ac7f..738051eb1 100644 --- a/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt +++ b/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt @@ -38,6 +38,7 @@ import java.nio.charset.StandardCharsets.UTF_8 import java.time.Duration import java.util.concurrent.TimeUnit import javax.net.ssl.HttpsURLConnection +import kotlin.test.assertFailsWith import mockwebserver3.SocketPolicy.DisconnectAtStart import mockwebserver3.SocketPolicy.DisconnectDuringRequestBody import mockwebserver3.SocketPolicy.DisconnectDuringResponseBody @@ -496,11 +497,10 @@ class MockWebServerTest { val connection = url.openConnection() as HttpURLConnection assertThat(connection.responseCode).isEqualTo(HttpURLConnection.HTTP_OK) val refusedConnection = url.openConnection() as HttpURLConnection - try { + assertFailsWith { refusedConnection.responseCode - fail("Second connection should be refused") - } catch (e: ConnectException) { - assertThat(e.message!!).contains("refused") + }.also { expected -> + assertThat(expected.message!!).contains("refused") } } diff --git a/native-image-tests/build.gradle.kts b/native-image-tests/build.gradle.kts index 0f82353eb..e58500245 100644 --- a/native-image-tests/build.gradle.kts +++ b/native-image-tests/build.gradle.kts @@ -27,6 +27,8 @@ dependencies { implementation(libs.junit.jupiter.api) implementation(libs.junit.jupiter.params) implementation(libs.assertk) + implementation(libs.kotlin.test.common) + implementation(libs.kotlin.test.junit) implementation(libs.nativeImageSvm) diff --git a/okhttp-brotli/build.gradle.kts b/okhttp-brotli/build.gradle.kts index 26613adb5..69922d9b3 100644 --- a/okhttp-brotli/build.gradle.kts +++ b/okhttp-brotli/build.gradle.kts @@ -22,6 +22,8 @@ dependencies { testImplementation(projects.okhttpTestingSupport) testImplementation(libs.conscrypt.openjdk) testImplementation(libs.junit) + testImplementation(libs.kotlin.test.common) + testImplementation(libs.kotlin.test.junit) testImplementation(libs.assertk) } diff --git a/okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt b/okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt index ccf8f58b6..3a5a46a42 100644 --- a/okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt +++ b/okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt @@ -21,6 +21,7 @@ import assertk.assertions.hasMessage import assertk.assertions.isEmpty import assertk.assertions.isEqualTo import java.io.IOException +import kotlin.test.assertFailsWith import okhttp3.MediaType.Companion.toMediaType import okhttp3.Protocol import okhttp3.Request @@ -32,7 +33,6 @@ import okio.ByteString.Companion.EMPTY import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.encodeUtf8 import org.junit.jupiter.api.Test -import org.junit.jupiter.api.fail class BrotliInterceptorTest { @Test @@ -90,12 +90,10 @@ class BrotliInterceptorTest { header("Content-Encoding", "br") } - try { + assertFailsWith { val failingResponse = uncompress(response) failingResponse.body.string() - - fail("expected uncompress error") - } catch (ioe: IOException) { + }.also { ioe -> assertThat(ioe).hasMessage("Brotli stream decoding failed") assertThat(ioe.cause?.javaClass?.simpleName).isEqualTo("BrotliRuntimeException") } diff --git a/okhttp-coroutines/build.gradle.kts b/okhttp-coroutines/build.gradle.kts index 748bac623..3c96b52c9 100644 --- a/okhttp-coroutines/build.gradle.kts +++ b/okhttp-coroutines/build.gradle.kts @@ -20,8 +20,9 @@ dependencies { api(libs.squareup.okio) api(libs.kotlin.stdlib) - testImplementation(libs.kotlin.test.common) testImplementation(libs.kotlin.test.annotations) + testImplementation(libs.kotlin.test.common) + testImplementation(libs.kotlin.test.junit) testApi(libs.assertk) testImplementation(projects.okhttpTestingSupport) testImplementation(libs.kotlinx.coroutines.test) diff --git a/okhttp-coroutines/src/test/kotlin/okhttp3/SuspendCallTest.kt b/okhttp-coroutines/src/test/kotlin/okhttp3/SuspendCallTest.kt index 696de522e..97711d413 100644 --- a/okhttp-coroutines/src/test/kotlin/okhttp3/SuspendCallTest.kt +++ b/okhttp-coroutines/src/test/kotlin/okhttp3/SuspendCallTest.kt @@ -24,6 +24,7 @@ import assertk.assertions.isEqualTo import assertk.assertions.isTrue import java.io.IOException import java.util.concurrent.TimeUnit +import kotlin.test.assertFailsWith import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -141,15 +142,12 @@ class SuspendCallTest { val call = client.newCall(request) - try { + assertFailsWith { call.executeAsync().use { withContext(Dispatchers.IO) { it.body.string() } } - fail("No expected to get response") - } catch (ioe: IOException) { - // expected } } } diff --git a/okhttp-dnsoverhttps/build.gradle.kts b/okhttp-dnsoverhttps/build.gradle.kts index aa905364e..5232ce6b6 100644 --- a/okhttp-dnsoverhttps/build.gradle.kts +++ b/okhttp-dnsoverhttps/build.gradle.kts @@ -24,6 +24,8 @@ dependencies { testImplementation(libs.squareup.okio.fakefilesystem) testImplementation(libs.conscrypt.openjdk) testImplementation(libs.junit) + testImplementation(libs.kotlin.test.common) + testImplementation(libs.kotlin.test.junit) } mavenPublishing { diff --git a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt index b9f5e4c27..cbdd77164 100644 --- a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt +++ b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt @@ -22,6 +22,7 @@ import assertk.assertions.isEqualTo import assertk.fail import java.net.InetAddress import java.net.UnknownHostException +import kotlin.test.assertFailsWith import okhttp3.AsyncDns.Companion.TYPE_A import okhttp3.AsyncDns.Companion.TYPE_AAAA import okhttp3.dnsoverhttps.DnsRecordCodec.decodeAnswers @@ -80,16 +81,15 @@ class DnsRecordCodecTest { @Test fun testGoogleDotComDecodingNxdomainFailure() { - try { + assertFailsWith { decodeAnswers( hostname = "sdflkhfsdlkjdf.ee", byteString = ("0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b" + "00060001000007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e65" + "74c01b5adb12c100000e10000003840012750000000e10").decodeHex() ) - fail("") - } catch (uhe: UnknownHostException) { - assertThat(uhe.message).isEqualTo("sdflkhfsdlkjdf.ee: NXDOMAIN") + }.also { expected -> + assertThat(expected.message).isEqualTo("sdflkhfsdlkjdf.ee: NXDOMAIN") } } } diff --git a/okhttp-testing-support/build.gradle.kts b/okhttp-testing-support/build.gradle.kts index 6c025fdd3..68d2cb4bc 100644 --- a/okhttp-testing-support/build.gradle.kts +++ b/okhttp-testing-support/build.gradle.kts @@ -27,6 +27,8 @@ dependencies { compileOnly(libs.findbugs.jsr305) compileOnly(libs.robolectric.android) + testImplementation(libs.kotlin.test.common) + testImplementation(libs.kotlin.test.junit) } animalsniffer { diff --git a/okhttp-testing-support/src/test/kotlin/okhttp3/OkHttpClientTestRuleTest.kt b/okhttp-testing-support/src/test/kotlin/okhttp3/OkHttpClientTestRuleTest.kt index ffbab02da..f14899122 100644 --- a/okhttp-testing-support/src/test/kotlin/okhttp3/OkHttpClientTestRuleTest.kt +++ b/okhttp-testing-support/src/test/kotlin/okhttp3/OkHttpClientTestRuleTest.kt @@ -17,11 +17,11 @@ package okhttp3 import assertk.assertThat import assertk.assertions.hasMessage +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.RegisterExtension -import org.junit.jupiter.api.fail class OkHttpClientTestRuleTest { lateinit var extensionContext: ExtensionContext @@ -42,10 +42,9 @@ class OkHttpClientTestRuleTest { thread.start() thread.join() - try { + assertFailsWith { testRule.afterEach(extensionContext) - fail("") - } catch (expected: AssertionError) { + }.also { expected -> assertThat(expected).hasMessage("uncaught exception thrown during test") assertThat(expected.cause!!).hasMessage("boom!") } diff --git a/okhttp-tls/build.gradle.kts b/okhttp-tls/build.gradle.kts index 20a646753..948fb4df3 100644 --- a/okhttp-tls/build.gradle.kts +++ b/okhttp-tls/build.gradle.kts @@ -24,6 +24,8 @@ dependencies { testImplementation(projects.okhttpTestingSupport) testImplementation(projects.mockwebserver3Junit5) testImplementation(libs.junit) + testImplementation(libs.kotlin.test.common) + testImplementation(libs.kotlin.test.junit) testImplementation(libs.assertk) } diff --git a/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt b/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt index d60099777..fafff4efc 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt +++ b/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt @@ -27,6 +27,7 @@ import java.net.ProtocolException import java.text.SimpleDateFormat import java.util.Date import java.util.TimeZone +import kotlin.test.assertFailsWith import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints @@ -69,10 +70,9 @@ internal class DerTest { val derReader = DerReader(buffer) - try { + assertFailsWith { derReader.read("test") {} - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message).isEqualTo("invalid encoding for length") } } @@ -85,10 +85,9 @@ internal class DerTest { val derReader = DerReader(buffer) - try { + assertFailsWith { derReader.read("test") {} - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message).isEqualTo("invalid encoding for length") } } @@ -127,10 +126,9 @@ internal class DerTest { val derReader = DerReader(buffer) - try { + assertFailsWith { derReader.read("test") {} - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message).isEqualTo("length > Long.MAX_VALUE") } } @@ -152,10 +150,9 @@ internal class DerTest { val derReader = DerReader(buffer) - try { + assertFailsWith { derReader.read("test") {} - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("length encoded with more than 8 bytes is not supported") } @@ -634,10 +631,9 @@ internal class DerTest { } @Test fun `cannot decode utc time with offset`() { - try { + assertFailsWith { Adapters.UTC_TIME.fromDer("17113139313231353139303231302d30383030".decodeHex()) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("Failed to parse UTCTime 191215190210-0800") } } @@ -651,19 +647,17 @@ internal class DerTest { @Test fun `cannot decode malformed utc time`() { val bytes = "170d3139313231362333303231305a".decodeHex() - try { + assertFailsWith { Adapters.UTC_TIME.fromDer(bytes) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("Failed to parse UTCTime 191216#30210Z") } } @Test fun `cannot decode generalized time with offset`() { - try { + assertFailsWith { Adapters.GENERALIZED_TIME.fromDer("181332303139313231353139303231302d30383030".decodeHex()) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191215190210-0800") } } @@ -677,10 +671,9 @@ internal class DerTest { @Test fun `cannot decode malformed generalized time`() { val bytes = "180f32303139313231362333303231305a".decodeHex() - try { + assertFailsWith { Adapters.GENERALIZED_TIME.fromDer(bytes) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191216#30210Z") } } @@ -779,10 +772,9 @@ internal class DerTest { @Test fun `cannot decode empty bit string`() { val bytes = "0300".decodeHex() - try { + assertFailsWith { Adapters.BIT_STRING.fromDer(bytes) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("malformed bit string") } } @@ -795,41 +787,39 @@ internal class DerTest { } @Test fun `cannot decode constructed octet string`() { - try { + assertFailsWith { Adapters.OCTET_STRING.fromDer( - "2410040668656c6c6f200406776f726c6421".decodeHex()) - fail("") - } catch (expected: ProtocolException) { + "2410040668656c6c6f200406776f726c6421".decodeHex() + ) + }.also { expected -> assertThat(expected).hasMessage("constructed octet strings not supported for DER") } } @Test fun `cannot decode constructed bit string`() { - try { + assertFailsWith { Adapters.BIT_STRING.fromDer( - "231203070068656c6c6f20030700776f726c6421".decodeHex()) - fail("") - } catch (expected: ProtocolException) { + "231203070068656c6c6f20030700776f726c6421".decodeHex() + ) + }.also { expected -> assertThat(expected).hasMessage("constructed bit strings not supported for DER") } } @Test fun `cannot decode constructed string`() { - try { + assertFailsWith { Adapters.UTF8_STRING.fromDer( "2c100c0668656c6c6f200c06776f726c6421".decodeHex()) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("constructed strings not supported for DER") } } @Test fun `cannot decode indefinite length bit string`() { - try { + assertFailsWith { Adapters.BIT_STRING.fromDer( "23800303000A3B0305045F291CD00000".decodeHex()) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("indefinite length not permitted for DER") } } @@ -838,12 +828,11 @@ internal class DerTest { val buffer = Buffer() .write("3A0904034A6F6E04026573".decodeHex()) val derReader = DerReader(buffer) - try { + assertFailsWith { derReader.read("test") { derReader.readOctetString() } - fail("") - } catch (expected: Exception) { + }.also { expected -> assertThat(expected).hasMessage("constructed octet strings not supported for DER") } } @@ -922,10 +911,9 @@ internal class DerTest { /** Make the claimed length of a nested object larger than the enclosing object. */ @Test fun `large object inside small object`() { val bytes = "301b300d06092a864886f70d010101050003847fffffff000504030201".decodeHex() - try { + assertFailsWith { CertificateAdapters.subjectPublicKeyInfo.fromDer(bytes) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message).isEqualTo("enclosed object too large") } } @@ -933,10 +921,9 @@ internal class DerTest { /** Object identifiers are nominally self-delimiting. Outrun the limit with one. */ @Test fun `variable length long outruns limit`() { val bytes = "060229ffffff7f".decodeHex() - try { + assertFailsWith { Adapters.OBJECT_IDENTIFIER.fromDer(bytes) - fail("") - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message).isEqualTo("unexpected byte count at OBJECT IDENTIFIER") } } diff --git a/okhttp/src/test/java/okhttp3/CacheControlJvmTest.kt b/okhttp/src/test/java/okhttp3/CacheControlJvmTest.kt index 7bd0f3528..1b109fb73 100644 --- a/okhttp/src/test/java/okhttp3/CacheControlJvmTest.kt +++ b/okhttp/src/test/java/okhttp3/CacheControlJvmTest.kt @@ -21,9 +21,9 @@ import assertk.assertions.isFalse import assertk.assertions.isSameAs import assertk.assertions.isTrue import java.util.concurrent.TimeUnit +import kotlin.test.assertFailsWith import okhttp3.CacheControl.Companion.parse import okhttp3.Headers.Companion.headersOf -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Test class CacheControlJvmTest { @@ -192,10 +192,8 @@ class CacheControlJvmTest { @Throws(Exception::class) fun secondsMustBeNonNegative() { val builder = CacheControl.Builder() - try { + assertFailsWith { builder.maxAge(-1, TimeUnit.SECONDS) - fail() - } catch (expected: IllegalArgumentException) { } } diff --git a/okhttp/src/test/java/okhttp3/CacheTest.kt b/okhttp/src/test/java/okhttp3/CacheTest.kt index 3f49b68d6..b8569a944 100644 --- a/okhttp/src/test/java/okhttp3/CacheTest.kt +++ b/okhttp/src/test/java/okhttp3/CacheTest.kt @@ -24,6 +24,7 @@ import assertk.assertions.isFalse import assertk.assertions.isNotNull import assertk.assertions.isNull import assertk.assertions.isTrue +import assertk.fail import java.io.IOException import java.net.CookieManager import java.net.HttpURLConnection @@ -36,6 +37,7 @@ import java.util.TimeZone import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference import javax.net.ssl.HostnameVerifier +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.RecordedRequest @@ -58,8 +60,8 @@ import okio.Path import okio.Path.Companion.toPath import okio.buffer import okio.fakefilesystem.FakeFileSystem +import okio.use import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -692,12 +694,10 @@ class CacheTest { ) val bodySource = get(server.url("/")).body.source() assertThat(bodySource.readUtf8Line()).isEqualTo("ABCDE") - try { - bodySource.readUtf8(21) - fail("This implementation silently ignored a truncated HTTP body.") - } catch (expected: IOException) { - } finally { - bodySource.close() + bodySource.use { + assertFailsWith { + bodySource.readUtf8(21) + } } assertThat(cache.writeAbortCount()).isEqualTo(1) assertThat(cache.writeSuccessCount()).isEqualTo(0) @@ -737,10 +737,8 @@ class CacheTest { val `in` = response1.body.source() assertThat(`in`.readUtf8(5)).isEqualTo("ABCDE") `in`.close() - try { + assertFailsWith { `in`.readByte() - fail("Expected an IllegalStateException because the source is closed.") - } catch (expected: IllegalStateException) { } assertThat(cache.writeAbortCount()).isEqualTo(1) assertThat(cache.writeSuccessCount()).isEqualTo(0) @@ -2916,10 +2914,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} // ... and nothing else. assertThat(i.hasNext()).isFalse() - try { + assertFailsWith { i.next() - fail() - } catch (expected: NoSuchElementException) { } } @@ -2961,10 +2957,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} assertThat(get(url).body.string()).isEqualTo("a") val i = cache.urls() assertThat(i.hasNext()).isTrue() - try { + assertFailsWith { i.remove() - fail() - } catch (expected: IllegalStateException) { } } @@ -2983,10 +2977,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} i.remove() // Too many calls to remove(). - try { + assertFailsWith { i.remove() - fail() - } catch (expected: IllegalStateException) { } } @@ -3028,10 +3020,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} // The URL was evicted before hasNext() made any promises. assertThat(i.hasNext()).isFalse() - try { + assertFailsWith { i.next() - fail() - } catch (expected: NoSuchElementException) { } } diff --git a/okhttp/src/test/java/okhttp3/CallKotlinTest.kt b/okhttp/src/test/java/okhttp3/CallKotlinTest.kt index 1fac8c356..974b8d732 100644 --- a/okhttp/src/test/java/okhttp3/CallKotlinTest.kt +++ b/okhttp/src/test/java/okhttp3/CallKotlinTest.kt @@ -43,7 +43,8 @@ import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.extension.RegisterExtension -import org.junit.jupiter.api.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junitpioneer.jupiter.RetryingTest @Timeout(30) @@ -160,11 +161,8 @@ class CallKotlinTest { .header("Content-Type", "application/xml") .put(ErringRequestBody()) .build() - try { + assertFailsWith { client.newCall(request).execute() - fail("test should always throw exception") - } catch (_: IOException) { - // NOTE: expected } request = Request.Builder() @@ -229,10 +227,9 @@ class CallKotlinTest { .build() val request = Request(server.url("/")) - try { + assertFailsWith { client.newCall(request).execute() - fail("") - } catch (expected: IOException) { + }.also { expected -> expected.assertSuppressed { val suppressed = it.single() assertThat(suppressed).isInstanceOf(IOException::class.java) @@ -251,10 +248,9 @@ class CallKotlinTest { .build() val request = Request(server.url("/")) - try { + assertFailsWith { client.newCall(request).execute() - fail("") - } catch (expected: IOException) { + }.also { expected -> expected.assertSuppressed { val suppressed = it.single() assertThat(suppressed).isInstanceOf(IOException::class.java) diff --git a/okhttp/src/test/java/okhttp3/CallTest.kt b/okhttp/src/test/java/okhttp3/CallTest.kt index c0fe00c1d..ca8698e19 100644 --- a/okhttp/src/test/java/okhttp3/CallTest.kt +++ b/okhttp/src/test/java/okhttp3/CallTest.kt @@ -31,6 +31,7 @@ import assertk.assertions.isNotSameAs import assertk.assertions.isNull import assertk.assertions.isTrue import assertk.assertions.startsWith +import assertk.fail import java.io.FileNotFoundException import java.io.IOException import java.io.InterruptedIOException @@ -60,6 +61,7 @@ import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLProtocolException import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.QueueDispatcher @@ -107,9 +109,9 @@ import okio.GzipSink import okio.Path.Companion.toPath import okio.buffer import okio.fakefilesystem.FakeFileSystem +import okio.use import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertArrayEquals -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Assumptions.assumeFalse import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled @@ -203,10 +205,9 @@ open class CallTest { @Test fun invalidScheme() { val requestBuilder = Request.Builder() - try { + assertFailsWith { requestBuilder.url("ftp://hostname/path") - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Expected URL scheme 'http' or 'https' but was 'ftp'") } } @@ -214,10 +215,9 @@ open class CallTest { @Test fun invalidPort() { val requestBuilder = Request.Builder() - try { + assertFailsWith { requestBuilder.url("http://localhost:65536/") - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Invalid URL port: \"65536\"") } } @@ -268,10 +268,8 @@ open class CallTest { @Test fun getWithRequestBody() { server.enqueue(MockResponse()) - try { + assertFailsWith { Request.Builder().method("GET", "abc".toRequestBody("text/plain".toMediaType())) - fail() - } catch (expected: IllegalArgumentException) { } } @@ -499,10 +497,9 @@ open class CallTest { client = client.newBuilder() .authenticator(RecordingOkAuthenticator(credential, null)) .build() - try { + assertFailsWith { client.newCall(Request.Builder().url(server.url("/0")).build()).execute() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Too many follow-up requests: 21") } } @@ -680,17 +677,15 @@ open class CallTest { val call = client.newCall(request) val response = call.execute() response.body.close() - try { + assertFailsWith { call.execute() - fail() - } catch (e: IllegalStateException) { - assertThat(e.message).isEqualTo("Already Executed") + }.also { expected -> + assertThat(expected.message).isEqualTo("Already Executed") } - try { + assertFailsWith { call.enqueue(callback) - fail() - } catch (e: IllegalStateException) { - assertThat(e.message).isEqualTo("Already Executed") + }.also { expected -> + assertThat(expected.message).isEqualTo("Already Executed") } assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest") } @@ -709,17 +704,15 @@ open class CallTest { .build() val call = client.newCall(request) call.enqueue(callback) - try { + assertFailsWith { call.execute() - fail() - } catch (e: IllegalStateException) { - assertThat(e.message).isEqualTo("Already Executed") + }.also { expected -> + assertThat(expected.message).isEqualTo("Already Executed") } - try { + assertFailsWith { call.enqueue(callback) - fail() - } catch (e: IllegalStateException) { - assertThat(e.message).isEqualTo("Already Executed") + }.also { expected -> + assertThat(expected.message).isEqualTo("Already Executed") } assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest") callback.await(request.url).assertSuccessful() @@ -782,7 +775,7 @@ open class CallTest { val request = Request(server.url("/secret")) client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { - fail() + fail("") } override fun onResponse(call: Call, response: Response) { @@ -924,16 +917,15 @@ open class CallTest { // The second byte of this request will be delayed by 750ms so we should time out after 250ms. val startNanos = System.nanoTime() - try { - bodySource.readByte() - fail() - } catch (expected: IOException) { - // Timed out as expected. - val elapsedNanos = System.nanoTime() - startNanos - val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos) - assertThat(elapsedMillis).isLessThan(500) - } finally { - bodySource.close() + bodySource.use { + assertFailsWith { + bodySource.readByte() + }.also { expected -> + // Timed out as expected. + val elapsedNanos = System.nanoTime() - startNanos + val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos) + assertThat(elapsedMillis).isLessThan(500) + } } } @@ -947,11 +939,9 @@ open class CallTest { .readTimeout(Duration.ofMillis(100)) .build() val request = Request.Builder().url(server.url("/")).build() - try { + assertFailsWith { // If this succeeds, too many requests were made. client.newCall(request).execute() - fail() - } catch (expected: InterruptedIOException) { } } @@ -1007,10 +997,9 @@ open class CallTest { val response = chain.proceed( chain.request() ) - try { + assertFailsWith { chain.proceed(chain.request()) - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message!!).contains("please call response.close()") } response @@ -1281,10 +1270,8 @@ open class CallTest { .hostnameVerifier(RecordingHostnameVerifier()) .build() val request = Request.Builder().url(server.url("/")).build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: SSLHandshakeException) { } val firstSocket = clientSocketFactory.socketsCreated[0] assertThat(firstSocket.enabledCipherSuites) @@ -1331,17 +1318,23 @@ open class CallTest { server.useHttps(handshakeCertificates.sslSocketFactory()) server.enqueue(MockResponse(socketPolicy = FailHandshake)) val request = Request.Builder().url(server.url("/")).build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: SSLProtocolException) { - // RI response to the FAIL_HANDSHAKE - } catch (expected: SSLHandshakeException) { - // Android's response to the FAIL_HANDSHAKE - } catch (expected: SSLException) { - // JDK 11 response to the FAIL_HANDSHAKE - val jvmVersion = System.getProperty("java.specification.version") - assertThat(jvmVersion).isEqualTo("11") + }.also { expected -> + when (expected) { + is SSLProtocolException -> { + // RI response to the FAIL_HANDSHAKE + } + is SSLHandshakeException -> { + // Android's response to the FAIL_HANDSHAKE + } + is SSLException -> { + // JDK 11 response to the FAIL_HANDSHAKE + val jvmVersion = System.getProperty("java.specification.version") + assertThat(jvmVersion).isEqualTo("11") + } + else -> throw expected + } } } @@ -1416,10 +1409,9 @@ open class CallTest { .build() server.enqueue(MockResponse()) val request = Request.Builder().url(server.url("/")).build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: UnknownServiceException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "CLEARTEXT communication not enabled for client" ) @@ -1434,10 +1426,9 @@ open class CallTest { server.useHttps(handshakeCertificates.sslSocketFactory()) server.enqueue(MockResponse()) val call = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: UnknownServiceException) { + }.also { expected -> assertThat(expected.message).isEqualTo("H2_PRIOR_KNOWLEDGE cannot be used with HTTPS") } } @@ -1506,10 +1497,9 @@ open class CallTest { // When we pin the wrong certificate, connectivity fails. val request = Request.Builder().url(server.url("/")).build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: SSLPeerUnverifiedException) { + }.also { expected -> assertThat(expected.message!!).startsWith("Certificate pinning failure!") } } @@ -1552,12 +1542,10 @@ open class CallTest { url = server.url("/"), body = "body!".toRequestBody("text/plain".toMediaType()), ) - try { + assertFailsWith { client.newCall(request2).execute() - fail() - } catch (e: IOException) { - assertThat(e.message!!).startsWith("unexpected end of stream on http://") - // expected + }.also { expected -> + assertThat(expected.message!!).startsWith("unexpected end of stream on http://") } assertThat(listener.recordedEventTypes()).containsExactly( @@ -2401,10 +2389,9 @@ open class CallTest { ) ) } - try { + assertFailsWith { client.newCall(Request.Builder().url(server.url("/0")).build()).execute() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Too many follow-up requests: 21") } } @@ -2473,10 +2460,8 @@ open class CallTest { fun canceledBeforeExecute() { val call = client.newCall(Request.Builder().url(server.url("/a")).build()) call.cancel() - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } assertThat(server.requestCount).isEqualTo(0) } @@ -2500,10 +2485,8 @@ open class CallTest { val call = client.newCall(Request(server.url("/").newBuilder().scheme(scheme!!).build())) cancelLater(call, cancelDelayMillis) val startNanos = System.nanoTime() - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } val elapsedNanos = System.nanoTime() - startNanos assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedNanos).toFloat()) @@ -2554,10 +2537,8 @@ open class CallTest { } client = client.newBuilder().eventListener(listener).build() val call = client.newCall(Request(server.url("/a"))) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } } @@ -2578,10 +2559,8 @@ open class CallTest { val result = executor.submit { call.execute() } Thread.sleep(100) // wait for it to go in flight. call.cancel() - try { + assertFailsWith { result.get()!!.body.bytes() - fail() - } catch (expected: IOException) { } assertThat(server.requestCount).isEqualTo(1) } @@ -2596,10 +2575,8 @@ open class CallTest { return MockResponse(body = "A") } } - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } assertThat(server.takeRequest().path).isEqualTo("/a") } @@ -2746,10 +2723,8 @@ open class CallTest { .build() val call = client.newCall(Request(server.url("/a"))) call.cancel() - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } assertThat(server.requestCount).isEqualTo(0) } @@ -2938,10 +2913,8 @@ open class CallTest { .post("abc".toRequestBody("text/plain".toMediaType())) .build() val call = client.newCall(request) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SocketTimeoutException) { } val recordedRequest = server.takeRequest() assertThat(recordedRequest.body.readUtf8()).isEqualTo("") @@ -3045,10 +3018,8 @@ open class CallTest { body = "abc".toRequestBody("text/plain".toMediaType()), ) val call = client.newCall(request) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SocketTimeoutException) { } val recordedRequest = server.takeRequest() assertThat(recordedRequest.body.readUtf8()).isEqualTo("abc") @@ -3265,10 +3236,9 @@ open class CallTest { .hostnameVerifier(hostnameVerifier) .build() val request = Request("https://android.com/foo".toHttpUrl()) - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected).hasMessage("unexpected end of stream") } } @@ -3409,10 +3379,8 @@ open class CallTest { .hostnameVerifier(RecordingHostnameVerifier()) .build() val request = Request("https://android.com/foo".toHttpUrl()) - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: ProtocolException) { } } @@ -3543,10 +3511,8 @@ open class CallTest { .proxy(server.toProxyAddress()) .build() val request = Request(server.url("/")) - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: IOException) { } } @@ -3613,20 +3579,18 @@ open class CallTest { @Test fun requestHeaderNameWithSpaceForbidden() { - try { + assertFailsWith { Request.Builder().addHeader("a b", "c") - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Unexpected char 0x20 at 1 in header name: a b") } } @Test fun requestHeaderNameWithTabForbidden() { - try { + assertFailsWith { Request.Builder().addHeader("a\tb", "c") - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Unexpected char 0x09 at 1 in header name: a\tb") } } @@ -3974,7 +3938,7 @@ open class CallTest { val latch = CountDownLatch(1) client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { - fail() + fail("") } override fun onResponse(call: Call, response: Response) { @@ -4242,10 +4206,9 @@ open class CallTest { assertThat(response.body.string()).isEqualTo("this is the redirect target") assertThat(response.priorResponse?.body?.contentType()) .isEqualTo("text/plain; charset=UTF-8".toMediaType()) - try { + assertFailsWith { response.priorResponse?.body?.string() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message!!).contains("Unreadable ResponseBody!") } } @@ -4270,10 +4233,9 @@ open class CallTest { body = requestBody, ) ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("write body fail!") } } diff --git a/okhttp/src/test/java/okhttp3/CertificateChainCleanerTest.kt b/okhttp/src/test/java/okhttp3/CertificateChainCleanerTest.kt index c4f4f2882..11a76141b 100644 --- a/okhttp/src/test/java/okhttp3/CertificateChainCleanerTest.kt +++ b/okhttp/src/test/java/okhttp3/CertificateChainCleanerTest.kt @@ -19,10 +19,10 @@ import assertk.assertThat import assertk.assertions.isEqualTo import java.security.cert.Certificate import javax.net.ssl.SSLPeerUnverifiedException +import kotlin.test.assertFailsWith import okhttp3.internal.tls.CertificateChainCleaner.Companion.get import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Test class CertificateChainCleanerTest { @@ -60,10 +60,8 @@ class CertificateChainCleanerTest { .serialNumber(1L) .build() val cleaner = get() - try { + assertFailsWith { cleaner.clean(list(root), "hostname") - fail() - } catch (expected: SSLPeerUnverifiedException) { } } @@ -276,10 +274,8 @@ class CertificateChainCleanerTest { } val root = heldCertificates[heldCertificates.size - 1].certificate val cleaner = get(root) - try { + assertFailsWith { cleaner.clean(certificates, "hostname") - fail() - } catch (expected: SSLPeerUnverifiedException) { } } diff --git a/okhttp/src/test/java/okhttp3/CertificatePinnerTest.kt b/okhttp/src/test/java/okhttp3/CertificatePinnerTest.kt index 10c346082..2c5559e4d 100644 --- a/okhttp/src/test/java/okhttp3/CertificatePinnerTest.kt +++ b/okhttp/src/test/java/okhttp3/CertificatePinnerTest.kt @@ -18,35 +18,32 @@ package okhttp3 import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isNotEqualTo +import assertk.fail import java.util.Arrays import javax.net.ssl.SSLPeerUnverifiedException +import kotlin.test.assertFailsWith import okhttp3.CertificatePinner.Companion.pin import okhttp3.CertificatePinner.Companion.sha1Hash import okhttp3.tls.HeldCertificate import okio.ByteString.Companion.decodeBase64 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Test class CertificatePinnerTest { @Test fun malformedPin() { val builder = CertificatePinner.Builder() - try { + assertFailsWith { builder.add("example.com", "md5/DmxUShsZuNiqPQsX2Oi9uv2sCnw=") - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun malformedBase64() { val builder = CertificatePinner.Builder() - try { + assertFailsWith { builder.add("example.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw*") - fail() - } catch (expected: IllegalArgumentException) { } } @@ -100,10 +97,8 @@ class CertificatePinnerTest { val certificatePinner = CertificatePinner.Builder() .add("example.com", certA1Sha256Pin) .build() - try { + assertFailsWith { certificatePinner.check("example.com", certB1.certificate) - fail() - } catch (expected: SSLPeerUnverifiedException) { } } @@ -156,10 +151,8 @@ class CertificatePinnerTest { val certificatePinner = CertificatePinner.Builder() .add("*.example.com", certA1Sha256Pin) .build() - try { + assertFailsWith { certificatePinner.check("a.example.com", listOf(certB1.certificate)) - fail() - } catch (expected: SSLPeerUnverifiedException) { } } @@ -188,10 +181,8 @@ class CertificatePinnerTest { .add("*.example.com", certA1Sha256Pin) .add("a.example.com", certB1Sha256Pin) .build() - try { + assertFailsWith { certificatePinner.check("a.example.com", listOf(certC1.certificate)) - fail() - } catch (expected: SSLPeerUnverifiedException) { } } @@ -202,25 +193,17 @@ class CertificatePinnerTest { .build() // Should be pinned: - try { + assertFailsWith { certificatePinner.check("example.co.uk", listOf(certB1.certificate)) - fail() - } catch (expected: SSLPeerUnverifiedException) { } - try { + assertFailsWith { certificatePinner.check("foo.example.co.uk", listOf(certB1.certificate)) - fail() - } catch (expected: SSLPeerUnverifiedException) { } - try { + assertFailsWith { certificatePinner.check("foo.bar.example.co.uk", listOf(certB1.certificate)) - fail() - } catch (expected: SSLPeerUnverifiedException) { } - try { + assertFailsWith { certificatePinner.check("foo.bar.baz.example.co.uk", listOf(certB1.certificate)) - fail() - } catch (expected: SSLPeerUnverifiedException) { } // Should not be pinned: @@ -232,40 +215,31 @@ class CertificatePinnerTest { @Test fun testBadPin() { - try { + assertFailsWith { CertificatePinner.Pin( "example.co.uk", "sha256/a" ) - fail() - } catch (iae: IllegalArgumentException) { - // expected } } @Test fun testBadAlgorithm() { - try { + assertFailsWith { CertificatePinner.Pin( "example.co.uk", "sha512/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" ) - fail() - } catch (iae: IllegalArgumentException) { - // expected } } @Test fun testBadHost() { - try { + assertFailsWith { CertificatePinner.Pin( "example.*", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" ) - fail() - } catch (iae: IllegalArgumentException) { - // expected } } diff --git a/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt b/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt index 6c9f0ffae..1ccaf03a0 100644 --- a/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt +++ b/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt @@ -36,7 +36,8 @@ import okhttp3.CertificatePinner.Companion.pin import okhttp3.testing.PlatformRule import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -238,7 +239,7 @@ class ConnectionCoalescingTest { } override fun onFailure(call: Call, e: IOException) { - fail() + fail("") } }) val client2 = client.newBuilder() @@ -255,10 +256,8 @@ class ConnectionCoalescingTest { server.enqueue(MockResponse()) assert200Http2Response(execute(url), server.hostName) val differentDnsUrl = url.newBuilder().host("differentdns.com").build() - try { + assertFailsWith { execute(differentDnsUrl) - fail("expected a failed attempt to connect") - } catch (expected: IOException) { } } @@ -275,11 +274,9 @@ class ConnectionCoalescingTest { .body("unexpected call") .build() ) - try { + assertFailsWith { val response = execute(url) response.close() - fail("expected a failed attempt to connect") - } catch (expected: IOException) { } } @@ -290,10 +287,8 @@ class ConnectionCoalescingTest { server.enqueue(MockResponse()) assert200Http2Response(execute(url), server.hostName) val nonsanUrl = url.newBuilder().host("nonsan.com").build() - try { + assertFailsWith { execute(nonsanUrl) - fail("expected a failed attempt to connect") - } catch (expected: SSLPeerUnverifiedException) { } } @@ -306,11 +301,9 @@ class ConnectionCoalescingTest { .build() ) server.enqueue(MockResponse()) - try { + assertFailsWith { val response = execute(url) response.close() - fail("expected a failed attempt to connect") - } catch (expected: SSLPeerUnverifiedException) { } } @@ -339,10 +332,8 @@ class ConnectionCoalescingTest { server.enqueue(MockResponse()) assert200Http2Response(execute(url), server.hostName) val sanUrl = url.newBuilder().host("san.com").build() - try { + assertFailsWith { execute(sanUrl) - fail("expected a failed attempt to connect") - } catch (expected: IOException) { } } @@ -359,10 +350,8 @@ class ConnectionCoalescingTest { .build() ) server.enqueue(MockResponse()) - try { + assertFailsWith { execute(url) - fail("expected a failed attempt to connect") - } catch (expected: SSLPeerUnverifiedException) { } } diff --git a/okhttp/src/test/java/okhttp3/ConnectionListenerTest.kt b/okhttp/src/test/java/okhttp3/ConnectionListenerTest.kt index 7b8eb9622..e4ecd1764 100644 --- a/okhttp/src/test/java/okhttp3/ConnectionListenerTest.kt +++ b/okhttp/src/test/java/okhttp3/ConnectionListenerTest.kt @@ -20,12 +20,14 @@ import assertk.assertions.containsExactly import assertk.assertions.hasMessage import assertk.assertions.isEqualTo import assertk.assertions.isIn +import assertk.fail import java.io.IOException import java.net.InetSocketAddress import java.net.UnknownHostException import java.time.Duration import java.util.Arrays import java.util.concurrent.TimeUnit +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.SocketPolicy.FailHandshake @@ -103,10 +105,9 @@ open class ConnectionListenerTest { val call = client.newCall(Request.Builder() .url(server!!.url("/")) .build()) - try { + assertFailsWith { call.execute() - org.junit.jupiter.api.Assertions.fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isIn("timeout", "Read timed out") } assertThat(listener.recordedEventTypes()).containsExactly( @@ -219,10 +220,8 @@ open class ConnectionListenerTest { val call = client.newCall(Request.Builder() .url(server!!.url("/")) .build()) - try { + assertFailsWith { call.execute() - org.junit.jupiter.api.Assertions.fail() - } catch (expected: IOException) { } val address = client.dns.lookup(server!!.hostName)[0] val expectedAddress = InetSocketAddress(address, server!!.port) diff --git a/okhttp/src/test/java/okhttp3/ConnectionReuseTest.kt b/okhttp/src/test/java/okhttp3/ConnectionReuseTest.kt index c567162f5..c27615f6d 100644 --- a/okhttp/src/test/java/okhttp3/ConnectionReuseTest.kt +++ b/okhttp/src/test/java/okhttp3/ConnectionReuseTest.kt @@ -17,8 +17,12 @@ package okhttp3 import assertk.assertThat import assertk.assertions.isEqualTo +import assertk.assertions.isIn +import java.io.IOException import java.util.concurrent.TimeUnit import javax.net.ssl.SSLException +import kotlin.math.exp +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.SocketPolicy.DisconnectAfterRequest @@ -31,7 +35,6 @@ import okhttp3.internal.closeQuietly import okhttp3.testing.PlatformRule import okhttp3.tls.HandshakeCertificates import org.bouncycastle.tls.TlsFatalAlert -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -241,11 +244,13 @@ class ConnectionReuseTest { .build() // This client fails to connect because the new SSL socket factory refuses. - try { + assertFailsWith { anotherClient.newCall(request).execute() - fail() - } catch (expected: SSLException) { - } catch (expected: TlsFatalAlert) { + }.also { expected -> + when (expected) { + is SSLException, is TlsFatalAlert -> {} + else -> throw expected + } } } diff --git a/okhttp/src/test/java/okhttp3/ConnectionSpecTest.kt b/okhttp/src/test/java/okhttp3/ConnectionSpecTest.kt index dcae22f1b..c1fb68aa7 100644 --- a/okhttp/src/test/java/okhttp3/ConnectionSpecTest.kt +++ b/okhttp/src/test/java/okhttp3/ConnectionSpecTest.kt @@ -26,11 +26,11 @@ import assertk.assertions.isTrue import java.util.concurrent.CopyOnWriteArraySet import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory +import kotlin.test.assertFailsWith import okhttp3.internal.applyConnectionSpec import okhttp3.internal.platform.Platform.Companion.isAndroid import okhttp3.testing.PlatformRule import okhttp3.testing.PlatformVersion.majorVersion -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension @@ -40,12 +40,11 @@ class ConnectionSpecTest { @Test fun noTlsVersions() { - try { + assertFailsWith { ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(*arrayOf()) .build() - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("At least one TLS version is required") } @@ -53,12 +52,11 @@ class ConnectionSpecTest { @Test fun noCipherSuites() { - try { + assertFailsWith { ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .cipherSuites(*arrayOf()) .build() - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("At least one cipher suite is required") } diff --git a/okhttp/src/test/java/okhttp3/CookieTest.kt b/okhttp/src/test/java/okhttp3/CookieTest.kt index 3ac41993e..bc0cb0b72 100644 --- a/okhttp/src/test/java/okhttp3/CookieTest.kt +++ b/okhttp/src/test/java/okhttp3/CookieTest.kt @@ -32,7 +32,8 @@ import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.internal.UTC import okhttp3.internal.http.MAX_DATE import okhttp3.internal.parseCookie -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.params.ParameterizedTest @@ -446,18 +447,14 @@ class CookieTest { } @Test fun builderNameValidation() { - try { + assertFailsWith { Cookie.Builder().name(" a ") - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun builderValueValidation() { - try { + assertFailsWith { Cookie.Builder().value(" b ") - fail() - } catch (expected: IllegalArgumentException) { } } @@ -492,10 +489,8 @@ class CookieTest { } @Test fun builderDomainValidation() { - try { + assertFailsWith { Cookie.Builder().hostOnlyDomain("a/b") - fail() - } catch (expected: IllegalArgumentException) { } } @@ -520,10 +515,8 @@ class CookieTest { } @Test fun builderPathValidation() { - try { + assertFailsWith { Cookie.Builder().path("foo") - fail() - } catch (expected: IllegalArgumentException) { } } diff --git a/okhttp/src/test/java/okhttp3/CookiesTest.kt b/okhttp/src/test/java/okhttp3/CookiesTest.kt index 60605418f..f90eab55c 100644 --- a/okhttp/src/test/java/okhttp3/CookiesTest.kt +++ b/okhttp/src/test/java/okhttp3/CookiesTest.kt @@ -23,6 +23,7 @@ import assertk.assertions.isFalse import assertk.assertions.isGreaterThan import assertk.assertions.isNull import assertk.assertions.isTrue +import assertk.fail import java.net.CookieHandler import java.net.CookieManager import java.net.CookiePolicy @@ -35,7 +36,6 @@ import mockwebserver3.MockWebServer import okhttp3.Cookie.Companion.parse import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.java.net.cookiejar.JavaNetCookieJar -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout @@ -252,7 +252,7 @@ class CookiesTest { assertThat(request.headers["Cookie"]).isEqualTo("c=cookie") for (header in redirectTarget.takeRequest().headers.names()) { if (header.startsWith("Cookie")) { - fail(header) + fail(header) } } } diff --git a/okhttp/src/test/java/okhttp3/DispatcherTest.kt b/okhttp/src/test/java/okhttp3/DispatcherTest.kt index 1b5b9cee6..626edc9c3 100644 --- a/okhttp/src/test/java/okhttp3/DispatcherTest.kt +++ b/okhttp/src/test/java/okhttp3/DispatcherTest.kt @@ -13,7 +13,8 @@ import java.net.UnknownHostException import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -44,19 +45,15 @@ class DispatcherTest { @Test fun maxRequestsZero() { - try { + assertFailsWith { dispatcher.maxRequests = 0 - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun maxPerHostZero() { - try { + assertFailsWith { dispatcher.maxRequestsPerHost = 0 - fail() - } catch (expected: IllegalArgumentException) { } } diff --git a/okhttp/src/test/java/okhttp3/DuplexTest.kt b/okhttp/src/test/java/okhttp3/DuplexTest.kt index a13682823..eaabb963a 100644 --- a/okhttp/src/test/java/okhttp3/DuplexTest.kt +++ b/okhttp/src/test/java/okhttp3/DuplexTest.kt @@ -42,7 +42,8 @@ import okhttp3.testing.PlatformRule import okio.BufferedSink import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Tag @@ -87,10 +88,8 @@ class DuplexTest { .post(AsyncRequestBody()) .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: ProtocolException) { } } @@ -369,11 +368,10 @@ class DuplexTest { .isEqualTo("this is /b") } val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink() - try { + assertFailsWith { requestBody.writeUtf8("request body\n") requestBody.flush() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("stream was reset: CANCEL") } @@ -431,11 +429,10 @@ class DuplexTest { // First duplex request is detached with violence. val requestBody1 = (call.request().body as AsyncRequestBody?)!!.takeSink() - try { + assertFailsWith { requestBody1.writeUtf8("not authenticated\n") requestBody1.flush() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("stream was reset: CANCEL") } @@ -469,11 +466,10 @@ class DuplexTest { .build() val call = client.newCall(request) call.timeout().timeout(250, TimeUnit.MILLISECONDS) - try { + assertFailsWith { call.execute() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") assertTrue(call.isCanceled()) } } @@ -631,11 +627,10 @@ class DuplexTest { .readTimeout(1000, TimeUnit.MILLISECONDS) .build() val call = client.newCall(request) - try { + assertFailsWith { call.execute() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") } } @@ -658,11 +653,10 @@ class DuplexTest { .build() val call = client.newCall(request) val response = call.execute() - try { + assertFailsWith { response.body.string() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") } } diff --git a/okhttp/src/test/java/okhttp3/EventListenerTest.kt b/okhttp/src/test/java/okhttp3/EventListenerTest.kt index ed3888f65..3a1d923c6 100644 --- a/okhttp/src/test/java/okhttp3/EventListenerTest.kt +++ b/okhttp/src/test/java/okhttp3/EventListenerTest.kt @@ -78,7 +78,8 @@ import org.hamcrest.Matcher import org.hamcrest.MatcherAssert import org.junit.Assume import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -221,10 +222,9 @@ class EventListenerTest { .url(server.url("/")) .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isIn("timeout", "Read timed out") } assertThat(listener.recordedEventTypes()).containsExactly( @@ -254,10 +254,9 @@ class EventListenerTest { .build() ) val response = call.execute() - try { + assertFailsWith { response.body.string() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("unexpected end of stream") } assertThat(listener.recordedEventTypes()).containsExactly( @@ -279,10 +278,9 @@ class EventListenerTest { .build() ) call.cancel() - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Canceled") } assertThat(listener.recordedEventTypes()).containsExactly( @@ -618,10 +616,8 @@ class EventListenerTest { .url("http://fakeurl/") .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } listener.removeUpToEvent() val callFailed: CallFailed = listener.removeUpToEvent() @@ -640,10 +636,8 @@ class EventListenerTest { .url("http://fakeurl/") .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } listener.removeUpToEvent() val callFailed: CallFailed = listener.removeUpToEvent() @@ -689,10 +683,8 @@ class EventListenerTest { .url(server.url("/")) .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } val address = client.dns.lookup(server.hostName)[0] val expectedAddress = InetSocketAddress(address, server.port) @@ -860,10 +852,8 @@ class EventListenerTest { .url(server.url("/")) .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } val secureStart = listener.removeUpToEvent() assertThat(secureStart.call).isSameAs(call) @@ -1093,10 +1083,8 @@ class EventListenerTest { Assume.assumeThat(response, matchesProtocol(Protocol.HTTP_2)) } assertThat(response.protocol).isEqualTo(expectedProtocol) - try { + assertFailsWith { response.body.string() - fail() - } catch (expected: IOException) { } val callFailed = listener.removeUpToEvent() assertThat(callFailed.ioe).isNotNull() @@ -1209,10 +1197,8 @@ class EventListenerTest { .post(request) .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } if (expectedProtocol != null) { val connectionAcquired = listener.removeUpToEvent() @@ -1285,10 +1271,8 @@ class EventListenerTest { .post(requestBody) .build() ) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } assertThat(listener.recordedEventTypes()).containsExactly( "CallStart", diff --git a/okhttp/src/test/java/okhttp3/FastFallbackTest.kt b/okhttp/src/test/java/okhttp3/FastFallbackTest.kt index 654cd0d37..da696b776 100644 --- a/okhttp/src/test/java/okhttp3/FastFallbackTest.kt +++ b/okhttp/src/test/java/okhttp3/FastFallbackTest.kt @@ -19,6 +19,7 @@ import assertk.assertThat import assertk.assertions.hasMessage import assertk.assertions.hasSize import assertk.assertions.isEqualTo +import assertk.fail import java.io.IOException import java.net.Inet4Address import java.net.Inet6Address @@ -28,7 +29,6 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import javax.net.SocketFactory import kotlin.test.assertFailsWith -import kotlin.test.fail import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.SocketPolicy.ResetStreamAtStart @@ -241,11 +241,10 @@ class FastFallbackTest { .callTimeout(1_000, TimeUnit.MILLISECONDS) .build() val call = client.newCall(Request(url)) - try { + assertFailsWith { call.execute() - fail("expected a timeout") - } catch (e: IOException) { - assertThat(e).hasMessage("timeout") + }.also { expected -> + assertThat(expected).hasMessage("timeout") } } diff --git a/okhttp/src/test/java/okhttp3/HandshakeTest.kt b/okhttp/src/test/java/okhttp3/HandshakeTest.kt index 3931b62c8..3dd35f561 100644 --- a/okhttp/src/test/java/okhttp3/HandshakeTest.kt +++ b/okhttp/src/test/java/okhttp3/HandshakeTest.kt @@ -25,7 +25,8 @@ import java.io.IOException import java.security.cert.Certificate import okhttp3.Handshake.Companion.handshake import okhttp3.tls.HeldCertificate -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Test class HandshakeTest { @@ -89,10 +90,9 @@ class HandshakeTest { null ) - try { + assertFailsWith { sslSession.handshake() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected).hasMessage("cipherSuite == SSL_NULL_WITH_NULL_NULL") } } @@ -106,10 +106,9 @@ class HandshakeTest { null ) - try { + assertFailsWith { sslSession.handshake() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected).hasMessage("cipherSuite == TLS_NULL_WITH_NULL_NULL") } } diff --git a/okhttp/src/test/java/okhttp3/HeadersJvmTest.kt b/okhttp/src/test/java/okhttp3/HeadersJvmTest.kt index dd0af2664..a54d7f8e0 100644 --- a/okhttp/src/test/java/okhttp3/HeadersJvmTest.kt +++ b/okhttp/src/test/java/okhttp3/HeadersJvmTest.kt @@ -20,6 +20,7 @@ import assertk.assertions.containsExactly import assertk.assertions.isEqualTo import java.time.Instant import java.util.Date +import kotlin.test.assertFailsWith import kotlin.test.fail import okhttp3.Headers.Companion.toHeaders import okhttp3.internal.EMPTY_HEADERS @@ -98,41 +99,32 @@ class HeadersJvmTest { } @Test fun addThrowsOnEmptyName() { - try { + assertFailsWith { Headers.Builder().add(": bar") - fail() - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { Headers.Builder().add(" : bar") - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun addThrowsOnNoColon() { - try { + assertFailsWith { Headers.Builder().add("foo bar") - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun addThrowsOnMultiColon() { - try { + assertFailsWith { Headers.Builder().add(":status: 200 OK") - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun addUnsafeNonAsciiRejectsUnicodeName() { - try { + assertFailsWith { Headers.Builder() .addUnsafeNonAscii("héader1", "value1") .build() - fail("Should have complained about invalid value") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") } } @@ -146,10 +138,8 @@ class HeadersJvmTest { // Fails on JS, ClassCastException: Illegal cast @Test fun ofMapThrowsOnNull() { - try { + assertFailsWith { (mapOf("User-Agent" to null) as Map).toHeaders() - fail() - } catch (expected: NullPointerException) { } } diff --git a/okhttp/src/test/java/okhttp3/HeadersTest.kt b/okhttp/src/test/java/okhttp3/HeadersTest.kt index e9c537cb3..4c665e1cb 100644 --- a/okhttp/src/test/java/okhttp3/HeadersTest.kt +++ b/okhttp/src/test/java/okhttp3/HeadersTest.kt @@ -19,6 +19,7 @@ import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isNotEqualTo import kotlin.test.Test +import kotlin.test.assertFailsWith import kotlin.test.fail import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.toHeaders @@ -31,18 +32,14 @@ class HeadersTest { } @Test fun ofThrowsOddNumberOfHeaders() { - try { + assertFailsWith { headersOf("User-Agent", "OkHttp", "Content-Length") - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun ofThrowsOnEmptyName() { - try { + assertFailsWith { headersOf("", "OkHttp") - fail() - } catch (expected: IllegalArgumentException) { } } @@ -62,26 +59,20 @@ class HeadersTest { } @Test fun ofRejectsNullChar() { - try { + assertFailsWith { headersOf("User-Agent", "Square\u0000OkHttp") - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun ofMapThrowsOnEmptyName() { - try { + assertFailsWith { mapOf("" to "OkHttp").toHeaders() - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun ofMapThrowsOnBlankName() { - try { + assertFailsWith { mapOf(" " to "OkHttp").toHeaders() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -109,107 +100,93 @@ class HeadersTest { } @Test fun ofMapRejectsNullCharInName() { - try { + assertFailsWith { mapOf("User-\u0000Agent" to "OkHttp").toHeaders() - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun ofMapRejectsNullCharInValue() { - try { + assertFailsWith { mapOf("User-Agent" to "Square\u0000OkHttp").toHeaders() - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun builderRejectsUnicodeInHeaderName() { - try { + assertFailsWith { Headers.Builder().add("héader1", "value1") - fail("Should have complained about invalid name") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") } } @Test fun builderRejectsUnicodeInHeaderValue() { - try { + assertFailsWith { Headers.Builder().add("header1", "valué1") - fail("Should have complained about invalid value") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1") } } @Test fun varargFactoryRejectsUnicodeInHeaderName() { - try { + assertFailsWith { headersOf("héader1", "value1") - fail("Should have complained about invalid value") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") } } @Test fun varargFactoryRejectsUnicodeInHeaderValue() { - try { + assertFailsWith { headersOf("header1", "valué1") - fail("Should have complained about invalid value") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1") } } @Test fun mapFactoryRejectsUnicodeInHeaderName() { - try { + assertFailsWith { mapOf("héader1" to "value1").toHeaders() - fail("Should have complained about invalid value") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") } } @Test fun mapFactoryRejectsUnicodeInHeaderValue() { - try { + assertFailsWith { mapOf("header1" to "valué1").toHeaders() - fail("Should have complained about invalid value") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1") } } @Test fun sensitiveHeadersNotIncludedInExceptions() { - try { + assertFailsWith { Headers.Builder().add("Authorization", "valué1") - fail("Should have complained about invalid name") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 4 in Authorization value") } - try { + assertFailsWith { Headers.Builder().add("Cookie", "valué1") - fail("Should have complained about invalid name") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 4 in Cookie value") } - try { + assertFailsWith { Headers.Builder().add("Proxy-Authorization", "valué1") - fail("Should have complained about invalid name") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 4 in Proxy-Authorization value") } - try { + assertFailsWith { Headers.Builder().add("Set-Cookie", "valué1") - fail("Should have complained about invalid name") - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Unexpected char 0xe9 at 4 in Set-Cookie value") } @@ -286,33 +263,25 @@ class HeadersTest { @Test fun nameIndexesAreStrict() { val headers = headersOf("a", "b", "c", "d") - try { + assertFailsWith { headers.name(-1) - fail() - } catch (expected: IndexOutOfBoundsException) { } assertThat(headers.name(0)).isEqualTo("a") assertThat(headers.name(1)).isEqualTo("c") - try { + assertFailsWith { headers.name(2) - fail() - } catch (expected: IndexOutOfBoundsException) { } } @Test fun valueIndexesAreStrict() { val headers = headersOf("a", "b", "c", "d") - try { + assertFailsWith { headers.value(-1) - fail() - } catch (expected: IndexOutOfBoundsException) { } assertThat(headers.value(0)).isEqualTo("b") assertThat(headers.value(1)).isEqualTo("d") - try { + assertFailsWith { headers.value(2) - fail() - } catch (expected: IndexOutOfBoundsException) { } } } diff --git a/okhttp/src/test/java/okhttp3/InsecureForHostTest.kt b/okhttp/src/test/java/okhttp3/InsecureForHostTest.kt index 2f92c66f1..c7a86d70a 100644 --- a/okhttp/src/test/java/okhttp3/InsecureForHostTest.kt +++ b/okhttp/src/test/java/okhttp3/InsecureForHostTest.kt @@ -21,6 +21,7 @@ import assertk.assertions.isEqualTo import assertk.assertions.isNotNull import assertk.assertions.isNull import javax.net.ssl.SSLException +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import okhttp3.testing.PlatformRule @@ -29,7 +30,6 @@ import okhttp3.tls.HeldCertificate import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension -import org.junit.jupiter.api.fail class InsecureForHostTest { @RegisterExtension @JvmField val platform = PlatformRule() @@ -90,10 +90,8 @@ class InsecureForHostTest { .build() val call = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call.execute() - fail("") - } catch (expected: SSLException) { } } @@ -112,10 +110,8 @@ class InsecureForHostTest { .build() val call = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call.execute() - fail("") - } catch (expected: SSLException) { } } } diff --git a/okhttp/src/test/java/okhttp3/InterceptorTest.kt b/okhttp/src/test/java/okhttp3/InterceptorTest.kt index 1fbf461ca..4c3b15b51 100644 --- a/okhttp/src/test/java/okhttp3/InterceptorTest.kt +++ b/okhttp/src/test/java/okhttp3/InterceptorTest.kt @@ -48,7 +48,8 @@ import okio.GzipSink import okio.Sink import okio.Source import okio.buffer -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -109,10 +110,9 @@ class InterceptorTest { val request = Request.Builder() .url(server.url("/")) .build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "network interceptor $interceptor must call proceed() exactly once" ) @@ -133,10 +133,9 @@ class InterceptorTest { val request = Request.Builder() .url(server.url("/")) .build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "network interceptor $interceptor must call proceed() exactly once" ) @@ -166,10 +165,9 @@ class InterceptorTest { val request = Request.Builder() .url(server.url("/")) .build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "network interceptor $interceptor must retain the same host and port" ) @@ -491,10 +489,9 @@ class InterceptorTest { val request = Request.Builder() .url(server.url("/")) .build() - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: RuntimeException) { + }.also { expected -> assertThat(expected.message).isEqualTo("boom!") } } @@ -605,10 +602,8 @@ class InterceptorTest { .build() val call = client.newCall(request1) val startNanos = System.nanoTime() - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SocketTimeoutException) { } val elapsedNanos = System.nanoTime() - startNanos org.junit.jupiter.api.Assertions.assertTrue( @@ -646,10 +641,8 @@ class InterceptorTest { val call = client.newCall(request1) val response = call.execute() val body = response.body - try { + assertFailsWith { body.string() - fail() - } catch (expected: SocketTimeoutException) { } } @@ -663,10 +656,9 @@ class InterceptorTest { } val request1 = Request.Builder().url(server.url("/")).build() val call = client.newCall(request1) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Timeouts can't be adjusted in a network interceptor") } @@ -682,10 +674,9 @@ class InterceptorTest { } val request1 = Request.Builder().url(server.url("/")).build() val call = client.newCall(request1) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Timeouts can't be adjusted in a network interceptor") } @@ -701,10 +692,9 @@ class InterceptorTest { } val request1 = Request.Builder().url(server.url("/")).build() val call = client.newCall(request1) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("Timeouts can't be adjusted in a network interceptor") } @@ -739,10 +729,8 @@ class InterceptorTest { .post(data.toRequestBody("text/plain".toMediaType())) .build() val call = client.newCall(request1) - try { + assertFailsWith { call.execute() // we want this call to throw a SocketTimeoutException - fail() - } catch (expected: SocketTimeoutException) { } } @@ -764,10 +752,8 @@ class InterceptorTest { .url(server.url("/")) .build() val call = client.newCall(request) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } assertThat(callRef.get()).isSameAs(call) } diff --git a/okhttp/src/test/java/okhttp3/MultipartBodyTest.kt b/okhttp/src/test/java/okhttp3/MultipartBodyTest.kt index 116512cb2..eafa23a5d 100644 --- a/okhttp/src/test/java/okhttp3/MultipartBodyTest.kt +++ b/okhttp/src/test/java/okhttp3/MultipartBodyTest.kt @@ -19,6 +19,7 @@ import assertk.assertThat import assertk.assertions.isEqualTo import java.io.IOException import java.nio.charset.StandardCharsets +import kotlin.test.assertFailsWith import okhttp3.Headers.Companion.headersOf import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaTypeOrNull @@ -26,17 +27,15 @@ import okhttp3.RequestBody.Companion.toRequestBody import okio.Buffer import okio.BufferedSink import okio.utf8Size -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Test class MultipartBodyTest { @Test fun onePartRequired() { - try { + assertFailsWith { MultipartBody.Builder().build() - fail() - } catch (e: IllegalStateException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Multipart body must have at least one part.") } } @@ -241,26 +240,22 @@ class MultipartBodyTest { @Test fun contentTypeHeaderIsForbidden() { val multipart = MultipartBody.Builder() - try { + assertFailsWith { multipart.addPart( headersOf("Content-Type", "text/plain"), "Hello, World!".toRequestBody(null) ) - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun contentLengthHeaderIsForbidden() { val multipart = MultipartBody.Builder() - try { + assertFailsWith { multipart.addPart( headersOf("Content-Length", "13"), "Hello, World!".toRequestBody(null) ) - fail() - } catch (expected: IllegalArgumentException) { } } diff --git a/okhttp/src/test/java/okhttp3/MultipartReaderTest.kt b/okhttp/src/test/java/okhttp3/MultipartReaderTest.kt index 9843811f4..b7fe06c70 100644 --- a/okhttp/src/test/java/okhttp3/MultipartReaderTest.kt +++ b/okhttp/src/test/java/okhttp3/MultipartReaderTest.kt @@ -27,7 +27,8 @@ import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.ResponseBody.Companion.toResponseBody import okio.Buffer -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -116,16 +117,12 @@ class MultipartReaderTest { ) val part = parts.nextPart()!! - try { + assertFailsWith { assertThat(part.body.readUtf8()).isEqualTo("abcd\r\nefgh\r\n") - fail() - } catch (expected: EOFException) { } - try { + assertFailsWith { assertThat(parts.nextPart()).isNull() - fail() - } catch (expected: EOFException) { } } @@ -141,10 +138,8 @@ class MultipartReaderTest { source = Buffer().writeUtf8(multipart) ) - try { + assertFailsWith { parts.nextPart() - fail() - } catch (expected: EOFException) { } } @@ -243,11 +238,10 @@ class MultipartReaderTest { val partAbc = parts.nextPart()!! val partMno = parts.nextPart()!! - try { + assertFailsWith { partAbc.body.request(20) - fail() - } catch (e: IllegalStateException) { - assertThat(e).hasMessage("closed") + }.also { expected -> + assertThat(expected).hasMessage("closed") } assertThat(partMno.body.readUtf8()).isEqualTo("mnop") @@ -271,11 +265,10 @@ class MultipartReaderTest { val part = parts.nextPart()!! parts.close() - try { + assertFailsWith { part.body.request(10) - fail() - } catch (e: IllegalStateException) { - assertThat(e).hasMessage("closed") + }.also { expected -> + assertThat(expected).hasMessage("closed") } } @@ -287,11 +280,10 @@ class MultipartReaderTest { parts.close() - try { + assertFailsWith { parts.nextPart() - fail() - } catch (e: IllegalStateException) { - assertThat(e).hasMessage("closed") + }.also { expected -> + assertThat(expected).hasMessage("closed") } } @@ -306,10 +298,9 @@ class MultipartReaderTest { source = Buffer().writeUtf8(multipart) ) - try { + assertFailsWith { parts.nextPart() - fail() - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("expected at least 1 part") } } @@ -415,10 +406,9 @@ class MultipartReaderTest { source = Buffer().writeUtf8(multipart) ) - try { + assertFailsWith { parts.nextPart() - fail() - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("unexpected characters after boundary") } } @@ -438,10 +428,9 @@ class MultipartReaderTest { ) parts.nextPart() - try { + assertFailsWith { parts.nextPart() - fail() - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected).hasMessage("unexpected characters after boundary") } } @@ -505,10 +494,8 @@ class MultipartReaderTest { source = Buffer() ) - try { + assertFailsWith { parts.nextPart() - fail() - } catch (expected: EOFException) { } } diff --git a/okhttp/src/test/java/okhttp3/OkHttpClientTest.kt b/okhttp/src/test/java/okhttp3/OkHttpClientTest.kt index 2e5108503..9492784aa 100644 --- a/okhttp/src/test/java/okhttp3/OkHttpClientTest.kt +++ b/okhttp/src/test/java/okhttp3/OkHttpClientTest.kt @@ -43,7 +43,8 @@ import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotSame import org.junit.jupiter.api.Assertions.assertSame -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension @@ -154,10 +155,8 @@ class OkHttpClientTest { @Test fun setProtocolsRejectsHttp10() { val builder = OkHttpClient.Builder() - try { + assertFailsWith { builder.protocols(listOf(Protocol.HTTP_1_0, Protocol.HTTP_1_1)) - fail() - } catch (expected: IllegalArgumentException) { } } @@ -170,10 +169,9 @@ class OkHttpClientTest { @Test fun nullInterceptorInList() { val builder = OkHttpClient.Builder() builder.interceptors().addAll(listOf(null) as List) - try { + assertFailsWith { builder.build() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Null interceptor: [null]") } } @@ -181,20 +179,18 @@ class OkHttpClientTest { @Test fun nullNetworkInterceptorInList() { val builder = OkHttpClient.Builder() builder.networkInterceptors().addAll(listOf(null) as List) - try { + assertFailsWith { builder.build() - fail() - } catch (expected: IllegalStateException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Null network interceptor: [null]") } } @Test fun testH2PriorKnowledgeOkHttpClientConstructionFallback() { - try { + assertFailsWith { OkHttpClient.Builder() .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)) - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "protocols containing h2_prior_knowledge cannot use other protocols: " + "[h2_prior_knowledge, http/1.1]" @@ -203,11 +199,10 @@ class OkHttpClientTest { } @Test fun testH2PriorKnowledgeOkHttpClientConstructionDuplicates() { - try { + assertFailsWith { OkHttpClient.Builder() .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)) - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "protocols containing h2_prior_knowledge cannot use other protocols: " + "[h2_prior_knowledge, h2_prior_knowledge]" @@ -234,10 +229,8 @@ class OkHttpClientTest { @Test fun sslSocketFactorySetAsSocketFactory() { val builder = OkHttpClient.Builder() - try { + assertFailsWith { builder.socketFactory(SSLSocketFactory.getDefault()) - fail() - } catch (expected: IllegalArgumentException) { } } @@ -245,10 +238,8 @@ class OkHttpClientTest { val client = OkHttpClient.Builder() .connectionSpecs(listOf(ConnectionSpec.CLEARTEXT)) .build() - try { + assertFailsWith { client.sslSocketFactory - fail() - } catch (expected: IllegalStateException) { } } @@ -281,11 +272,10 @@ class OkHttpClientTest { Protocol.HTTP_1_1, null ) - try { + assertFailsWith { OkHttpClient.Builder() .protocols(protocols as List) - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo("protocols must not contain null") } } @@ -420,10 +410,9 @@ class OkHttpClientTest { @Test fun minWebSocketMessageToCompressNegative() { val builder = OkHttpClient.Builder() - try { + assertFailsWith { builder.minWebSocketMessageToCompress(-1024) - fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message) .isEqualTo("minWebSocketMessageToCompress must be positive: -1024") } diff --git a/okhttp/src/test/java/okhttp3/RequestCommonTest.kt b/okhttp/src/test/java/okhttp3/RequestCommonTest.kt index 9f8fc580e..4d979398a 100644 --- a/okhttp/src/test/java/okhttp3/RequestCommonTest.kt +++ b/okhttp/src/test/java/okhttp3/RequestCommonTest.kt @@ -22,8 +22,8 @@ import assertk.assertions.isEqualTo import assertk.assertions.isNull import assertk.assertions.isSameAs import assertk.assertions.isTrue -import assertk.fail import kotlin.test.Test +import kotlin.test.assertFailsWith import okhttp3.Headers.Companion.headersOf import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.RequestBody.Companion.toRequestBody @@ -146,15 +146,11 @@ class RequestCommonTest { @Test fun emptyNameForbidden() { val builder = Request.Builder() - try { + assertFailsWith { builder.header("", "Value") - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.addHeader("", "Value") - fail("") - } catch (expected: IllegalArgumentException) { } } @@ -162,10 +158,8 @@ class RequestCommonTest { fun headerAllowsTabOnlyInValues() { val builder = Request.Builder() builder.header("key", "sample\tvalue") - try { + assertFailsWith { builder.header("sample\tkey", "value") - fail("") - } catch (expected: IllegalArgumentException) { } } @@ -182,25 +176,17 @@ class RequestCommonTest { private fun assertForbiddenHeader(s: String) { val builder = Request.Builder() - try { + assertFailsWith { builder.header(s, "Value") - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.addHeader(s, "Value") - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.header("Name", s) - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.addHeader("Name", s) - fail("") - } catch (expected: IllegalArgumentException) { } } diff --git a/okhttp/src/test/java/okhttp3/RequestTest.kt b/okhttp/src/test/java/okhttp3/RequestTest.kt index 10efd7906..6700abdca 100644 --- a/okhttp/src/test/java/okhttp3/RequestTest.kt +++ b/okhttp/src/test/java/okhttp3/RequestTest.kt @@ -26,7 +26,7 @@ import java.io.File import java.io.FileWriter import java.net.URI import java.util.UUID -import kotlin.test.fail +import kotlin.test.assertFailsWith import okhttp3.Headers.Companion.headersOf import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType @@ -264,15 +264,11 @@ class RequestTest { @Test fun emptyNameForbidden() { val builder = Request.Builder() - try { + assertFailsWith { builder.header("", "Value") - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.addHeader("", "Value") - fail("") - } catch (expected: IllegalArgumentException) { } } @@ -280,10 +276,8 @@ class RequestTest { fun headerAllowsTabOnlyInValues() { val builder = Request.Builder() builder.header("key", "sample\tvalue") - try { + assertFailsWith { builder.header("sample\tkey", "value") - fail("") - } catch (expected: IllegalArgumentException) { } } @@ -300,25 +294,17 @@ class RequestTest { private fun assertForbiddenHeader(s: String) { val builder = Request.Builder() - try { + assertFailsWith { builder.header(s, "Value") - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.addHeader(s, "Value") - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.header("Name", s) - fail("") - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { builder.addHeader("Name", s) - fail("") - } catch (expected: IllegalArgumentException) { } } diff --git a/okhttp/src/test/java/okhttp3/ResponseBodyJvmTest.kt b/okhttp/src/test/java/okhttp3/ResponseBodyJvmTest.kt index 0fd46c125..83481c08f 100644 --- a/okhttp/src/test/java/okhttp3/ResponseBodyJvmTest.kt +++ b/okhttp/src/test/java/okhttp3/ResponseBodyJvmTest.kt @@ -18,11 +18,13 @@ package okhttp3 import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isTrue +import assertk.fail import java.io.IOException import java.io.InputStreamReader import java.io.Reader import java.nio.charset.StandardCharsets import java.util.concurrent.atomic.AtomicBoolean +import kotlin.test.assertFailsWith import okhttp3.MediaType.Companion.toMediaType import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.internal.and @@ -300,11 +302,10 @@ class ResponseBodyJvmTest { return Buffer().writeUtf8("hello") } } - try { + assertFailsWith { body.bytes() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Content-Length (10) and stream length (5) disagree" ) } @@ -325,11 +326,10 @@ class ResponseBodyJvmTest { throw AssertionError() } } - try { + assertFailsWith { body.bytes() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Cannot buffer entire body for content length: 2147483648" ) } @@ -391,11 +391,10 @@ class ResponseBodyJvmTest { return Buffer().writeUtf8("hello") } } - try { + assertFailsWith { body.byteString() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Content-Length (10) and stream length (5) disagree" ) } @@ -416,11 +415,10 @@ class ResponseBodyJvmTest { throw AssertionError() } } - try { + assertFailsWith { body.byteString() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Cannot buffer entire body for content length: 2147483648" ) } diff --git a/okhttp/src/test/java/okhttp3/ServerTruncatesRequestTest.kt b/okhttp/src/test/java/okhttp3/ServerTruncatesRequestTest.kt index 96a54646b..9b84fb239 100644 --- a/okhttp/src/test/java/okhttp3/ServerTruncatesRequestTest.kt +++ b/okhttp/src/test/java/okhttp3/ServerTruncatesRequestTest.kt @@ -36,7 +36,8 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.RegisterExtension -import org.junit.jupiter.api.fail +import assertk.fail +import kotlin.test.assertFailsWith @Timeout(30) @Tag("Slowish") @@ -152,15 +153,11 @@ class ServerTruncatesRequestTest { call.execute().use { response -> assertThat(response.body.string()).isEqualTo("abc") val requestBodyOut = requestBody.takeSink() - try { + assertFailsWith { SlowRequestBody.writeTo(requestBodyOut) - fail("") - } catch (expected: IOException) { } - try { + assertFailsWith { requestBodyOut.close() - fail("") - } catch (expected: IOException) { } } @@ -266,10 +263,9 @@ class ServerTruncatesRequestTest { ) ) - try { + assertFailsWith { callA.execute() - fail("") - } catch (expected: IOException) { + }.also { expected -> assertThat(expected).hasMessage("boom") } diff --git a/okhttp/src/test/java/okhttp3/URLConnectionTest.kt b/okhttp/src/test/java/okhttp3/URLConnectionTest.kt index 4a312eea1..1f7442423 100644 --- a/okhttp/src/test/java/okhttp3/URLConnectionTest.kt +++ b/okhttp/src/test/java/okhttp3/URLConnectionTest.kt @@ -28,6 +28,7 @@ import assertk.assertions.isLessThan import assertk.assertions.isNotEmpty import assertk.assertions.isNull import assertk.assertions.isTrue +import assertk.fail import java.io.File import java.io.IOException import java.io.InputStream @@ -64,6 +65,7 @@ import javax.net.ssl.SSLProtocolException import javax.net.ssl.TrustManager import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.SocketPolicy @@ -97,7 +99,6 @@ import okio.buffer import okio.utf8Size import org.bouncycastle.tls.TlsFatalAlert import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Tag @@ -209,10 +210,8 @@ class URLConnectionTest { .status("HTP/1.1 200 OK") .build()) val request = newRequest("/") - try { + assertFailsWith { getResponse(request) - fail() - } catch (expected: IOException) { } } @@ -222,10 +221,8 @@ class URLConnectionTest { .status("HTTP/1.1 2147483648 OK") .build()) val request = newRequest("/") - try { + assertFailsWith { getResponse(request) - fail() - } catch (expected: IOException) { } } @@ -235,10 +232,8 @@ class URLConnectionTest { .status("HTTP/1.1 00a OK") .build()) val request = newRequest("/") - try { + assertFailsWith { getResponse(request) - fail() - } catch (expected: IOException) { } } @@ -248,10 +243,8 @@ class URLConnectionTest { .status(" HTTP/1.1 2147483648 OK") .build()) val request = newRequest("/") - try { + assertFailsWith { getResponse(request) - fail() - } catch (expected: IOException) { } } @@ -259,10 +252,8 @@ class URLConnectionTest { fun connectRetriesUntilConnectedOrFailed() { val request = newRequest("/foo") server.shutdown() - try { + assertFailsWith { getResponse(request) - fail() - } catch (expected: IOException) { } } @@ -369,14 +360,12 @@ class URLConnectionTest { client = client.newBuilder() .dns(FakeDns()) .build() - try { + assertFailsWith { getResponse( Request.Builder() .url("http://1234.1.1.1/index.html".toHttpUrl()) .build() ) - fail() - } catch (expected: UnknownHostException) { } } @@ -582,13 +571,13 @@ class URLConnectionTest { client = client.newBuilder() .sslSocketFactory(sslSocketFactory2, trustManager) .build() - try { + assertFailsWith { getResponse(newRequest("/")) - fail( - "without an SSL socket factory, the connection should fail" - ) - } catch (expected: SSLException) { - } catch (expected: TlsFatalAlert) { + }.also { expected -> + when (expected) { + is SSLException, is TlsFatalAlert -> {} + else -> throw expected + } } } @@ -632,10 +621,9 @@ class URLConnectionTest { suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager ) .build() - try { + assertFailsWith { getResponse(newRequest("/foo")) - fail() - } catch (expected: IOException) { + }.also { expected -> expected.assertSuppressed { throwables: List? -> assertThat(throwables!!.size).isEqualTo(1) } @@ -690,15 +678,19 @@ class URLConnectionTest { // Flaky https://github.com/square/okhttp/issues/5222 server.useHttps(handshakeCertificates.sslSocketFactory()) server.enqueue(MockResponse()) // unused - try { + assertFailsWith { getResponse(newRequest("/foo")) - fail() - } catch (expected: SSLHandshakeException) { - // Allow conscrypt to fail in different ways - if (!platform.isConscrypt()) { - assertThat(expected.cause!!).isInstanceOf() + }.also { expected -> + when (expected) { + is SSLHandshakeException -> { + // Allow conscrypt to fail in different ways + if (!platform.isConscrypt()) { + assertThat(expected.cause!!).isInstanceOf() + } + } + is TlsFatalAlert -> {} + else -> throw expected } - } catch (expected: TlsFatalAlert) { } assertThat(server.requestCount).isEqualTo(0) } @@ -752,11 +744,9 @@ class URLConnectionTest { .setHeader("Content-Length", "5") .socketPolicy(DisconnectAtEnd) .build()) - try { + assertFailsWith { val response = getResponse(newRequest("/")) response.body.source().readUtf8(5) - fail() - } catch (expected: ProtocolException) { } } @@ -797,10 +787,8 @@ class URLConnectionTest { client = client.newBuilder() .socketFactory(uselessSocketFactory) .build() - try { + assertFailsWith { getResponse(newRequest("/")) - fail() - } catch (expected: IllegalArgumentException) { } client = client.newBuilder() .socketFactory(SocketFactory.getDefault()) @@ -846,11 +834,9 @@ class URLConnectionTest { builder.addHeader("Transfer-encoding: chunked") builder.socketPolicy(DisconnectAtEnd) server.enqueue(builder.build()) - try { + assertFailsWith { val response = getResponse(newRequest("/")) response.body.source().readUtf8(7) - fail() - } catch (expected: IOException) { } } @@ -1121,14 +1107,12 @@ class URLConnectionTest { val inputStream = response.body.byteStream() assertThat(inputStream.read().toChar()).isEqualTo('A') call.cancel() - try { + assertFailsWith { // Reading 'B' may succeed if it's buffered. inputStream.read() // But 'C' shouldn't be buffered (the response is throttled) and this should fail. inputStream.read() - fail("Expected a connection closed exception") - } catch (expected: IOException) { } inputStream.close() } @@ -1149,10 +1133,9 @@ class URLConnectionTest { .build() val call = client.newCall(newRequest("/")) callReference.set(call) - try { + assertFailsWith { call.execute() - fail("Connection should not be established") - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Canceled") } } @@ -1164,10 +1147,8 @@ class URLConnectionTest { ) val call = client.newCall(newRequest("/")) call.cancel() - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } } @@ -1219,10 +1200,8 @@ class URLConnectionTest { .isFalse() inputStream.mark(5) assertThat(readAscii(inputStream, 5)).isEqualTo("ABCDE") - try { + assertFailsWith { inputStream.reset() - fail() - } catch (expected: IOException) { } assertThat(readAscii(inputStream, Int.MAX_VALUE)).isEqualTo( "FGHIJKLMNOPQRSTUVWXYZ" @@ -1262,12 +1241,10 @@ class URLConnectionTest { .addHeader("Transfer-encoding: chunked") .build() ) - try { + assertFailsWith { getResponse(newRequest("/")).use { response -> response.body.string() - fail() } - } catch (expected: IOException) { } } @@ -1280,12 +1257,10 @@ class URLConnectionTest { .addHeader("Transfer-encoding: chunked") .build() ) - try { + assertFailsWith { getResponse(newRequest("/")).use { response -> readAscii(response.body.byteStream(), Int.MAX_VALUE) - fail() } - } catch (expected: IOException) { } } @@ -1311,12 +1286,10 @@ class URLConnectionTest { .socketPolicy(DisconnectAtEnd) .build() ) - try { + assertFailsWith { getResponse(newRequest("/")).use { response -> readAscii(response.body.byteStream(), Int.MAX_VALUE) - fail() } - } catch (expected: IOException) { } } @@ -1777,13 +1750,11 @@ class URLConnectionTest { } private fun assertMethodForbidsRequestBody(requestMethod: String) { - try { + assertFailsWith { Request.Builder() .url(server.url("/")) .method(requestMethod, "abc".toRequestBody(null)) .build() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -1796,13 +1767,11 @@ class URLConnectionTest { } private fun assertMethodForbidsNoRequestBody(requestMethod: String) { - try { + assertFailsWith { Request.Builder() .url(server.url("/")) .method(requestMethod, null) .build() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -2672,10 +2641,9 @@ class URLConnectionTest { ) ) } - try { + assertFailsWith { getResponse(newRequest("/0")) - fail() - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "Too many follow-up requests: 21" ) @@ -2781,10 +2749,8 @@ class URLConnectionTest { assertThat(source.readByte()).isEqualTo('A'.code.toByte()) assertThat(source.readByte()).isEqualTo('B'.code.toByte()) assertThat(source.readByte()).isEqualTo('C'.code.toByte()) - try { + assertFailsWith { source.readByte() // If Content-Length was accurate, this would return -1 immediately. - fail() - } catch (expected: SocketTimeoutException) { } source.close() } @@ -2831,10 +2797,8 @@ class URLConnectionTest { } }, ) - try { + assertFailsWith { getResponse(request) - fail() - } catch (expected: SocketTimeoutException) { } } @@ -2938,10 +2902,9 @@ class URLConnectionTest { body = "This body is not allowed!", ) ) - try { + assertFailsWith { getResponse(newRequest("/")) - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("HTTP 204 had non-zero Content-Length: 25") } } @@ -3001,26 +2964,20 @@ class URLConnectionTest { ) assertThat(readAscii(response.body.byteStream(), Int.MAX_VALUE)) .isEqualTo("abc") - try { + assertFailsWith { sinkReference.get().flush() - fail() - } catch (expected: IllegalStateException) { } - try { + assertFailsWith { sinkReference.get().write("ghi".toByteArray()) sinkReference.get().emit() - fail() - } catch (expected: IllegalStateException) { } } @Test fun getHeadersThrows() { server.enqueue(MockResponse(socketPolicy = SocketPolicy.DisconnectAtStart)) - try { + assertFailsWith { getResponse(newRequest("/")) - fail() - } catch (expected: IOException) { } } @@ -3029,19 +2986,15 @@ class URLConnectionTest { client = client.newBuilder() .dns(FakeDns()) .build() - try { + assertFailsWith { getResponse(Request("http://host.unlikelytld".toHttpUrl())) - fail() - } catch (expected: IOException) { } } @Test fun malformedUrlThrowsUnknownHostException() { - try { + assertFailsWith { getResponse(Request("http://-/foo.html".toHttpUrl())) - fail() - } catch (expected: IOException) { } } @@ -3056,10 +3009,8 @@ class URLConnectionTest { source1.timeout().timeout(100, TimeUnit.MILLISECONDS) assertThat(readAscii(source1.inputStream(), Int.MAX_VALUE)).isEqualTo("ABC") server.shutdown() - try { + assertFailsWith { getResponse(newRequest("/")) - fail() - } catch (expected: ConnectException) { } } @@ -3084,13 +3035,11 @@ class URLConnectionTest { @Test fun getOutputStreamOnGetFails() { - try { + assertFailsWith { Request.Builder() .url(server.url("/")) .method("GET", "abc".toRequestBody(null)) .build() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -3163,13 +3112,11 @@ class URLConnectionTest { @Test fun doOutputForMethodThatDoesntSupportOutput() { - try { + assertFailsWith { Request.Builder() .url(server.url("/")) .method("HEAD", "".toRequestBody(null)) .build() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -3314,15 +3261,13 @@ class URLConnectionTest { sink.writeUtf8("abc") } } - try { + assertFailsWith { getResponse( Request( url = server.url("/b"), body = requestBody, ) ) - fail() - } catch (expected: IOException) { } } @@ -3340,15 +3285,13 @@ class URLConnectionTest { sink.writeUtf8("abcd") } } - try { + assertFailsWith { getResponse( Request( url = server.url("/b"), body = requestBody, ) ) - fail() - } catch (expected: IOException) { } } @@ -3356,20 +3299,20 @@ class URLConnectionTest { @Disabled fun testPooledConnectionsDetectHttp10() { // TODO: write a test that shows pooled connections detect HTTP/1.0 (vs. HTTP/1.1) - fail("TODO") + fail("TODO") } @Test @Disabled fun postBodiesRetransmittedOnAuthProblems() { - fail("TODO") + fail("TODO") } @Test @Disabled fun cookiesAndTrailers() { // Do cookie headers get processed too many times? - fail("TODO") + fail("TODO") } @Test @@ -3402,13 +3345,11 @@ class URLConnectionTest { @Test fun emptyRequestHeaderNameIsStrict() { - try { + assertFailsWith { Request.Builder() .url(server.url("/")) .header("", "A") .build() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -3430,35 +3371,25 @@ class URLConnectionTest { @Test fun requestHeaderValidationIsStrict() { - try { + assertFailsWith { Request.Builder() .addHeader("a\tb", "Value") - fail() - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { Request.Builder() .addHeader("Name", "c\u007fd") - fail() - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { Request.Builder() .addHeader("", "Value") - fail() - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { Request.Builder() .addHeader("\ud83c\udf69", "Value") - fail() - } catch (expected: IllegalArgumentException) { } - try { + assertFailsWith { Request.Builder() .addHeader("Name", "\u2615\ufe0f") - fail() - } catch (expected: IllegalArgumentException) { } } @@ -3481,19 +3412,19 @@ class URLConnectionTest { @Test @Disabled fun deflateCompression() { - fail("TODO") + fail("TODO") } @Test @Disabled fun postBodiesRetransmittedOnIpAddressProblems() { - fail("TODO") + fail("TODO") } @Test @Disabled fun pooledConnectionProblemsNotReportedToProxySelector() { - fail("TODO") + fail("TODO") } @Test @@ -3607,10 +3538,9 @@ class URLConnectionTest { client = client.newBuilder() .authenticator(RecordingOkAuthenticator(credential, null)) .build() - try { + assertFailsWith { getResponse(newRequest("/")) - fail() - } catch (expected: ProtocolException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Too many follow-up requests: 21") } } @@ -3708,21 +3638,17 @@ class URLConnectionTest { @Test fun setProtocolsWithoutHttp11() { - try { + assertFailsWith { OkHttpClient.Builder() .protocols(Arrays.asList(Protocol.HTTP_2)) - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun setProtocolsWithNull() { - try { + assertFailsWith { OkHttpClient.Builder() .protocols(Arrays.asList(Protocol.HTTP_1_1, null)) - fail() - } catch (expected: IllegalArgumentException) { } } @@ -3770,18 +3696,25 @@ class URLConnectionTest { handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager ) .build() - try { + assertFailsWith { getResponse(newRequest("/")) - fail() - } catch (expected: SSLProtocolException) { - // RI response to the FAIL_HANDSHAKE - } catch (expected: SSLHandshakeException) { - // Android's response to the FAIL_HANDSHAKE - } catch (expected: SSLException) { - // JDK 1.9 response to the FAIL_HANDSHAKE - // javax.net.ssl.SSLException: Unexpected handshake message: client_hello - } catch (expected: SocketException) { - // Conscrypt's response to the FAIL_HANDSHAKE + }.also { expected -> + when (expected) { + is SSLProtocolException -> { + // RI response to the FAIL_HANDSHAKE + } + is SSLHandshakeException -> { + // Android's response to the FAIL_HANDSHAKE + } + is SSLException -> { + // JDK 1.9 response to the FAIL_HANDSHAKE + // javax.net.ssl.SSLException: Unexpected handshake message: client_hello + } + is SocketException -> { + // Conscrypt's response to the FAIL_HANDSHAKE + } + else -> throw expected + } } } @@ -3868,28 +3801,22 @@ class URLConnectionTest { @Test fun urlWithSpaceInHost() { - try { + assertFailsWith { "http://and roid.com/".toHttpUrl() - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun urlWithSpaceInHostViaHttpProxy() { - try { + assertFailsWith { "http://and roid.com/".toHttpUrl() - fail() - } catch (expected: IllegalArgumentException) { } } @Test fun urlHostWithNul() { - try { + assertFailsWith { "http://host\u0000/".toHttpUrl() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -3909,10 +3836,8 @@ class URLConnectionTest { @Test fun urlWithBadAsciiHost() { - try { + assertFailsWith { "http://host\u0001/".toHttpUrl() - fail() - } catch (expected: IllegalArgumentException) { } } @@ -3920,11 +3845,9 @@ class URLConnectionTest { @Test fun setSslSocketFactoryFailsOnJdk9() { platform.assumeJdk9() - try { + assertFailsWith { client.newBuilder() .sslSocketFactory(handshakeCertificates.sslSocketFactory()) - fail() - } catch (expected: UnsupportedOperationException) { } } @@ -3935,10 +3858,9 @@ class URLConnectionTest { .dns { hostname: String? -> throw RuntimeException("boom!") } .build() server.enqueue(MockResponse()) - try { + assertFailsWith { getResponse(newRequest("/")) - fail() - } catch (expected: RuntimeException) { + }.also { expected -> assertThat(expected.message).isEqualTo("boom!") } } diff --git a/okhttp/src/test/java/okhttp3/UrlComponentEncodingTester.kt b/okhttp/src/test/java/okhttp3/UrlComponentEncodingTester.kt index 31f9c84ad..abaff3fe7 100644 --- a/okhttp/src/test/java/okhttp3/UrlComponentEncodingTester.kt +++ b/okhttp/src/test/java/okhttp3/UrlComponentEncodingTester.kt @@ -17,6 +17,7 @@ package okhttp3 import assertk.assertThat import assertk.assertions.startsWith +import kotlin.test.assertFailsWith import kotlin.test.fail import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.internal.idn.Punycode @@ -142,10 +143,8 @@ class UrlComponentEncodingTester private constructor() { private fun testForbidden(codePoint: Int, codePointString: String, component: Component) { val builder = "http://host/".toHttpUrl().newBuilder() - try { + assertFailsWith { component[builder] = codePointString - fail("Accepted forbidden code point $component $codePoint") - } catch (expected: IllegalArgumentException) { } } diff --git a/okhttp/src/test/java/okhttp3/WholeOperationTimeoutTest.kt b/okhttp/src/test/java/okhttp3/WholeOperationTimeoutTest.kt index 93ad38600..8e72232c8 100644 --- a/okhttp/src/test/java/okhttp3/WholeOperationTimeoutTest.kt +++ b/okhttp/src/test/java/okhttp3/WholeOperationTimeoutTest.kt @@ -27,13 +27,13 @@ import java.time.Duration import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.TestUtil.repeat import okhttp3.testing.Flaky import okio.BufferedSink -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -85,11 +85,10 @@ class WholeOperationTimeoutTest { .build() val call = client.newCall(request) call.timeout().timeout(250, TimeUnit.MILLISECONDS) - try { + assertFailsWith { call.execute() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") assertThat(call.isCanceled()).isTrue() } } @@ -134,11 +133,10 @@ class WholeOperationTimeoutTest { .build() val call = client.newCall(request) call.timeout().timeout(250, TimeUnit.MILLISECONDS) - try { + assertFailsWith { call.execute() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") assertThat(call.isCanceled()).isTrue() } } @@ -188,11 +186,10 @@ class WholeOperationTimeoutTest { call.timeout().timeout(250, TimeUnit.MILLISECONDS) val response = call.execute() Thread.sleep(500) - try { + assertFailsWith { response.body.source().readUtf8() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") assertThat(call.isCanceled()).isTrue() } } @@ -223,12 +220,10 @@ class WholeOperationTimeoutTest { } catch (e: InterruptedException) { throw AssertionError() } - try { + assertFailsWith { response.body.source().readUtf8() - fail() - } catch (e: IOException) { - exceptionRef.set(e) - } finally { + }.also { expected -> + exceptionRef.set(expected) latch.countDown() } } @@ -281,11 +276,10 @@ class WholeOperationTimeoutTest { .build() val call = client.newCall(request) call.timeout().timeout(250, TimeUnit.MILLISECONDS) - try { + assertFailsWith { call.execute() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") assertThat(call.isCanceled()).isTrue() } } @@ -307,11 +301,10 @@ class WholeOperationTimeoutTest { val request = Request.Builder().url(server.url("/")).build() val call = client.newCall(request) call.timeout().timeout(250, TimeUnit.MILLISECONDS) - try { + assertFailsWith { call.execute() - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("timeout") + }.also { expected -> + assertThat(expected.message).isEqualTo("timeout") assertThat(call.isCanceled()).isTrue() } } diff --git a/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt b/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt index 1dfc867f3..63fcc37a3 100644 --- a/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt @@ -41,7 +41,8 @@ import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assumptions import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Timeout -import org.junit.jupiter.api.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ArgumentsSource @@ -129,10 +130,8 @@ class DiskLruCacheTest { cache = DiskLruCache(filesystem, cacheDir, appVersion, 2, Int.MAX_VALUE.toLong(), taskRunner).also { toClose.add(it) } - try { + assertFailsWith { cache["k1"] - fail("") - } catch (_: IOException) { } // Now let it operate normally. @@ -146,49 +145,43 @@ class DiskLruCacheTest { @ArgumentsSource(FileSystemParamProvider::class) fun validateKey(parameters: Pair) { setUp(parameters.first, parameters.second) - var key: String? = null - try { + var key = "" + assertFailsWith { key = "has_space " cache.edit(key) - fail("Expecting an IllegalArgumentException as the key was invalid.") - } catch (iae: IllegalArgumentException) { - assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") + }.also { expected -> + assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") } - try { + assertFailsWith { key = "has_CR\r" cache.edit(key) - fail("Expecting an IllegalArgumentException as the key was invalid.") - } catch (iae: IllegalArgumentException) { - assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") + }.also { expected -> + assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") } - try { + assertFailsWith { key = "has_LF\n" cache.edit(key) - fail("Expecting an IllegalArgumentException as the key was invalid.") - } catch (iae: IllegalArgumentException) { - assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") + }.also { expected -> + assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") } - try { + assertFailsWith { key = "has_invalid/" cache.edit(key) - fail("Expecting an IllegalArgumentException as the key was invalid.") - } catch (iae: IllegalArgumentException) { - assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") + }.also { expected -> + assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") } - try { + assertFailsWith { key = "has_invalid\u2603" cache.edit(key) - fail("Expecting an IllegalArgumentException as the key was invalid.") - } catch (iae: IllegalArgumentException) { - assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") + }.also { expected -> + assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") } - try { + assertFailsWith { key = ("this_is_way_too_long_this_is_way_too_long_this_is_way_too_long_" + "this_is_way_too_long_this_is_way_too_long_this_is_way_too_long") cache.edit(key) - fail("Expecting an IllegalArgumentException as the key was too long.") - } catch (iae: IllegalArgumentException) { - assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") + }.also { expected -> + assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"") } // Test valid cases. @@ -544,10 +537,8 @@ class DiskLruCacheTest { @ArgumentsSource(FileSystemParamProvider::class) fun keyWithSpaceNotPermitted(parameters: Pair) { setUp(parameters.first, parameters.second) - try { + assertFailsWith { cache.edit("my key") - fail("") - } catch (_: IllegalArgumentException) { } } @@ -555,10 +546,8 @@ class DiskLruCacheTest { @ArgumentsSource(FileSystemParamProvider::class) fun keyWithNewlineNotPermitted(parameters: Pair) { setUp(parameters.first, parameters.second) - try { + assertFailsWith { cache.edit("my\nkey") - fail("") - } catch (_: IllegalArgumentException) { } } @@ -566,10 +555,8 @@ class DiskLruCacheTest { @ArgumentsSource(FileSystemParamProvider::class) fun keyWithCarriageReturnNotPermitted(parameters: Pair) { setUp(parameters.first, parameters.second) - try { + assertFailsWith { cache.edit("my\rkey") - fail("") - } catch (_: IllegalArgumentException) { } } @@ -579,10 +566,8 @@ class DiskLruCacheTest { setUp(parameters.first, parameters.second) val creator = cache.edit("k1")!! creator.setString(1, "A") - try { + assertFailsWith { creator.commit() - fail("") - } catch (_: IllegalStateException) { } assertThat(filesystem.exists(getCleanFile("k1", 0))).isFalse() assertThat(filesystem.exists(getCleanFile("k1", 1))).isFalse() @@ -789,10 +774,8 @@ class DiskLruCacheTest { @ArgumentsSource(FileSystemParamProvider::class) fun constructorDoesNotAllowZeroCacheSize(parameters: Pair) { setUp(parameters.first, parameters.second) - try { + assertFailsWith { DiskLruCache(filesystem, cacheDir, appVersion, 2, 0, taskRunner) - fail("") - } catch (_: IllegalArgumentException) { } } @@ -800,10 +783,8 @@ class DiskLruCacheTest { @ArgumentsSource(FileSystemParamProvider::class) fun constructorDoesNotAllowZeroValuesPerEntry(parameters: Pair) { setUp(parameters.first, parameters.second) - try { + assertFailsWith { DiskLruCache(filesystem, cacheDir, appVersion, 0, 10, taskRunner) - fail("") - } catch (_: IllegalArgumentException) { } } @@ -1426,10 +1407,8 @@ class DiskLruCacheTest { it.assertValue(1, "c2") } assertThat(iterator.hasNext()).isFalse() - try { + assertFailsWith { iterator.next() - fail("") - } catch (_: NoSuchElementException) { } } @@ -1500,10 +1479,8 @@ class DiskLruCacheTest { setUp(parameters.first, parameters.second) set("a", "a1", "a2") val iterator = cache.snapshots() - try { + assertFailsWith { iterator.remove() - fail("") - } catch (_: IllegalStateException) { } } @@ -1516,10 +1493,8 @@ class DiskLruCacheTest { iterator.next().use { iterator.remove() } - try { + assertFailsWith { iterator.remove() - fail("") - } catch (_: IllegalStateException) { } } @@ -2322,30 +2297,20 @@ class DiskLruCacheTest { private fun sourceAsString(source: Source) = source.buffer().readUtf8() private fun Editor.assertInoperable() { - try { + assertFailsWith { setString(0, "A") - fail("") - } catch (_: IllegalStateException) { } - try { + assertFailsWith { newSource(0) - fail("") - } catch (_: IllegalStateException) { } - try { + assertFailsWith { newSink(0) - fail("") - } catch (_: IllegalStateException) { } - try { + assertFailsWith { commit() - fail("") - } catch (_: IllegalStateException) { } - try { + assertFailsWith { abort() - fail("") - } catch (_: IllegalStateException) { } } diff --git a/okhttp/src/test/java/okhttp3/internal/cache2/FileOperatorTest.kt b/okhttp/src/test/java/okhttp3/internal/cache2/FileOperatorTest.kt index 6b3b17c42..32eceb4c3 100644 --- a/okhttp/src/test/java/okhttp3/internal/cache2/FileOperatorTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/cache2/FileOperatorTest.kt @@ -27,7 +27,8 @@ import okio.buffer import okio.sink import okio.source import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir @@ -165,10 +166,8 @@ class FileOperatorTest { randomAccessFile!!.getChannel() ) val buffer = Buffer() - try { + assertFailsWith { operator.read(0, buffer, -1L) - fail() - } catch (expected: IndexOutOfBoundsException) { } } @@ -178,15 +177,11 @@ class FileOperatorTest { randomAccessFile!!.getChannel() ) val buffer = Buffer().writeUtf8("abc") - try { + assertFailsWith { operator.write(0, buffer, -1L) - fail() - } catch (expected: IndexOutOfBoundsException) { } - try { + assertFailsWith { operator.write(0, buffer, 4L) - fail() - } catch (expected: IndexOutOfBoundsException) { } } diff --git a/okhttp/src/test/java/okhttp3/internal/cache2/RelayTest.kt b/okhttp/src/test/java/okhttp3/internal/cache2/RelayTest.kt index 9fac73150..38c533916 100644 --- a/okhttp/src/test/java/okhttp3/internal/cache2/RelayTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/cache2/RelayTest.kt @@ -24,6 +24,7 @@ import java.io.File import java.io.IOException import java.util.concurrent.Callable import java.util.concurrent.Executors +import kotlin.test.assertFailsWith import okhttp3.internal.cache2.Relay.Companion.edit import okhttp3.internal.cache2.Relay.Companion.read import okio.Buffer @@ -163,10 +164,9 @@ class RelayTest { assertThat(source1.readUtf8(10)).isEqualTo("abcdefghij") source1.close() // Not exhausted! assertThat(relay1.isClosed).isTrue() - try { + assertFailsWith { read(file) - org.junit.jupiter.api.Assertions.fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("unreadable cache file") } assertFile(Relay.PREFIX_DIRTY, -1L, -1, null, null) diff --git a/okhttp/src/test/java/okhttp3/internal/concurrent/TaskRunnerTest.kt b/okhttp/src/test/java/okhttp3/internal/concurrent/TaskRunnerTest.kt index 6dd7237d0..4c42dd707 100644 --- a/okhttp/src/test/java/okhttp3/internal/concurrent/TaskRunnerTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/concurrent/TaskRunnerTest.kt @@ -26,7 +26,8 @@ import okhttp3.TestLogHandler import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension -import org.junit.jupiter.api.fail +import assertk.fail +import kotlin.test.assertFailsWith class TaskRunnerTest { private val taskFaker = TaskFaker() @@ -618,14 +619,12 @@ class TaskRunnerTest { @Test fun scheduleThrowsWhenShutdown() { redQueue.shutdown() - try { + assertFailsWith { redQueue.schedule(object : Task("task", cancelable = false) { override fun runOnce(): Long { return -1L } }, 100.µs) - fail("") - } catch (_: RejectedExecutionException) { } taskFaker.assertNoMoreTasks() diff --git a/okhttp/src/test/java/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt b/okhttp/src/test/java/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt index a8896273a..d891610e9 100644 --- a/okhttp/src/test/java/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt @@ -26,7 +26,8 @@ import okhttp3.FakeRoutePlanner.ConnectState.TLS_CONNECTED import okhttp3.internal.concurrent.TaskFaker import okhttp3.testing.Flaky import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Test import org.junitpioneer.jupiter.RetryingTest @@ -325,11 +326,10 @@ internal class FastFallbackExchangeFinderTest { plan0.tcpConnectThrowable = IOException("boom!") taskRunner.newQueue().execute("connect") { - try { + assertFailsWith { finder.find() - fail() - } catch (e: IOException) { - assertThat(e).hasMessage("boom!") + }.also { expected -> + assertThat(expected).hasMessage("boom!") } } @@ -374,12 +374,11 @@ internal class FastFallbackExchangeFinderTest { plan1.tcpConnectThrowable = IOException("boom 1!") taskRunner.newQueue().execute("connect") { - try { + assertFailsWith { finder.find() - fail() - } catch (e: IOException) { - assertThat(e).hasMessage("boom 0!") - assertThat(e.suppressed.single()).hasMessage("boom 1!") + }.also { expected -> + assertThat(expected).hasMessage("boom 0!") + assertThat(expected.suppressed.single()).hasMessage("boom 1!") } } @@ -403,11 +402,10 @@ internal class FastFallbackExchangeFinderTest { routePlanner.addPlan() // This plan should not be used. taskRunner.newQueue().execute("connect") { - try { + assertFailsWith { finder.find() - fail() - } catch (e: IllegalStateException) { - assertThat(e).hasMessage("boom!") + }.also { expected -> + assertThat(expected).hasMessage("boom!") } } @@ -427,11 +425,10 @@ internal class FastFallbackExchangeFinderTest { plan0.planningThrowable = UnknownServiceException("boom!") taskRunner.newQueue().execute("connect") { - try { + assertFailsWith { finder.find() - fail() - } catch (e: UnknownServiceException) { - assertThat(e).hasMessage("boom!") + }.also { expected -> + assertThat(expected).hasMessage("boom!") } } diff --git a/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt b/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt index 30383a682..495252d09 100644 --- a/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt @@ -29,6 +29,7 @@ import java.net.ProxySelector import java.net.SocketAddress import java.net.URI import java.net.UnknownHostException +import kotlin.test.assertFailsWith import okhttp3.Address import okhttp3.Call import okhttp3.EventListener @@ -41,7 +42,6 @@ import okhttp3.internal.connection.RouteSelector.Companion.socketHost import okhttp3.internal.http.RecordingProxySelector import okhttp3.testing.PlatformRule import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension @@ -88,16 +88,12 @@ class RouteSelectorTest { assertRoute(selection.next(), address, Proxy.NO_PROXY, dns.lookup(uriHost, 0), uriPort) dns.assertRequests(uriHost) assertThat(selection.hasNext()).isFalse() - try { + assertFailsWith { selection.next() - fail() - } catch (expected: NoSuchElementException) { } assertThat(routeSelector.hasNext()).isFalse() - try { + assertFailsWith { routeSelector.next() - fail() - } catch (expected: NoSuchElementException) { } } @@ -113,16 +109,12 @@ class RouteSelectorTest { selection = routeSelector.next() assertRoute(selection.next(), address, Proxy.NO_PROXY, dns.lookup(uriHost, 0), uriPort) assertThat(selection.hasNext()).isFalse() - try { + assertFailsWith { selection.next() - fail() - } catch (expected: NoSuchElementException) { } assertThat(routeSelector.hasNext()).isFalse() - try { + assertFailsWith { routeSelector.next() - fail() - } catch (expected: NoSuchElementException) { } } @@ -279,10 +271,8 @@ class RouteSelectorTest { assertThat(selection1.hasNext()).isFalse() assertThat(routeSelector.hasNext()).isTrue() dns.clear(proxyBHost) - try { + assertFailsWith { routeSelector.next() - fail() - } catch (expected: UnknownHostException) { } dns.assertRequests(proxyBHost) assertThat(routeSelector.hasNext()).isTrue() diff --git a/okhttp/src/test/java/okhttp3/internal/http/CancelTest.kt b/okhttp/src/test/java/okhttp3/internal/http/CancelTest.kt index 15ff944fc..bba84453a 100644 --- a/okhttp/src/test/java/okhttp3/internal/http/CancelTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/http/CancelTest.kt @@ -20,6 +20,7 @@ import assertk.assertions.contains import assertk.assertions.doesNotContain import assertk.assertions.isEqualTo import assertk.assertions.startsWith +import assertk.fail import java.io.IOException import java.net.ServerSocket import java.net.Socket @@ -27,6 +28,7 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit.MILLISECONDS import javax.net.ServerSocketFactory import javax.net.SocketFactory +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import okhttp3.Call @@ -62,7 +64,6 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.extension.RegisterExtension -import org.junit.jupiter.api.fail import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ArgumentsSource @@ -168,10 +169,9 @@ class CancelTest { ) ) cancelLater(call, 500) - try { + assertFailsWith { call.execute() - fail("") - } catch (expected: IOException) { + }.also { expected -> assertEquals(cancelMode == INTERRUPT, Thread.interrupted()) } } @@ -195,11 +195,10 @@ class CancelTest { cancelLater(call, 500) val responseBody = response.body.byteStream() val buffer = ByteArray(1024) - try { + assertFailsWith { while (responseBody.read(buffer) != -1) { } - fail("Expected connection to be closed") - } catch (expected: IOException) { + }.also { expected -> assertEquals(cancelMode == INTERRUPT, Thread.interrupted()) } responseBody.close() @@ -227,11 +226,10 @@ class CancelTest { val cancelLatch = cancelLater(call, 500) val responseBody = response.body.byteStream() val buffer = ByteArray(1024) - try { + assertFailsWith { while (responseBody.read(buffer) != -1) { } - fail("Expected connection to be closed") - } catch (expected: IOException) { + }.also { expected -> assertEquals(cancelMode == INTERRUPT, Thread.interrupted()) } responseBody.close() @@ -244,7 +242,7 @@ class CancelTest { assertThat(events).startsWith("CallStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired") if (cancelMode == CANCEL) { - assertThat(events).contains("Canceled") + assertThat(events).contains("Canceled") } else { assertThat(events).doesNotContain("Canceled") } diff --git a/okhttp/src/test/java/okhttp3/internal/http/StatusLineTest.kt b/okhttp/src/test/java/okhttp3/internal/http/StatusLineTest.kt index 91ccb8719..40bf8b593 100644 --- a/okhttp/src/test/java/okhttp3/internal/http/StatusLineTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/http/StatusLineTest.kt @@ -20,7 +20,8 @@ import assertk.assertions.isEqualTo import java.net.ProtocolException import okhttp3.Protocol import okhttp3.internal.http.StatusLine.Companion.parse -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Test class StatusLineTest { @@ -117,10 +118,8 @@ class StatusLineTest { } private fun assertInvalid(statusLine: String) { - try { + assertFailsWith { parse(statusLine) - fail("") - } catch (expected: ProtocolException) { } } } diff --git a/okhttp/src/test/java/okhttp3/internal/http/ThreadInterruptTest.kt b/okhttp/src/test/java/okhttp3/internal/http/ThreadInterruptTest.kt index 2871253f3..28275ed7a 100644 --- a/okhttp/src/test/java/okhttp3/internal/http/ThreadInterruptTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/http/ThreadInterruptTest.kt @@ -32,7 +32,8 @@ import okhttp3.testing.PlatformRule import okio.Buffer import okio.BufferedSink import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -93,16 +94,14 @@ class ThreadInterruptTest { sink.flush() sleep(100) } - fail("Expected connection to be closed") + fail("Expected connection to be closed") } }) .build() ) interruptLater(500) - try { + assertFailsWith { call.execute() - fail("") - } catch (expected: IOException) { } } @@ -124,11 +123,9 @@ class ThreadInterruptTest { interruptLater(500) val responseBody = response.body.byteStream() val buffer = ByteArray(1024) - try { + assertFailsWith { while (responseBody.read(buffer) != -1) { } - fail("Expected connection to be interrupted") - } catch (expected: IOException) { } responseBody.close() } diff --git a/okhttp/src/test/java/okhttp3/internal/http2/BaseTestHandler.kt b/okhttp/src/test/java/okhttp3/internal/http2/BaseTestHandler.kt index 2352083db..5f3e88fc6 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/BaseTestHandler.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/BaseTestHandler.kt @@ -17,7 +17,7 @@ package okhttp3.internal.http2 import okio.BufferedSource import okio.ByteString -import org.junit.jupiter.api.Assertions.fail +import assertk.fail internal open class BaseTestHandler : Http2Reader.Handler { override fun data( @@ -26,7 +26,7 @@ internal open class BaseTestHandler : Http2Reader.Handler { source: BufferedSource, length: Int, ) { - fail() + fail("") } override fun headers( @@ -35,25 +35,25 @@ internal open class BaseTestHandler : Http2Reader.Handler { associatedStreamId: Int, headerBlock: List
, ) { - fail() + fail("") } override fun rstStream( streamId: Int, errorCode: ErrorCode, ) { - fail() + fail("") } override fun settings( clearPrevious: Boolean, settings: Settings, ) { - fail() + fail("") } override fun ackSettings() { - fail() + fail("") } override fun ping( @@ -61,7 +61,7 @@ internal open class BaseTestHandler : Http2Reader.Handler { payload1: Int, payload2: Int, ) { - fail() + fail("") } override fun goAway( @@ -69,14 +69,14 @@ internal open class BaseTestHandler : Http2Reader.Handler { errorCode: ErrorCode, debugData: ByteString, ) { - fail() + fail("") } override fun windowUpdate( streamId: Int, windowSizeIncrement: Long, ) { - fail() + fail("") } override fun priority( @@ -85,7 +85,7 @@ internal open class BaseTestHandler : Http2Reader.Handler { weight: Int, exclusive: Boolean, ) { - fail() + fail("") } override fun pushPromise( @@ -93,7 +93,7 @@ internal open class BaseTestHandler : Http2Reader.Handler { associatedStreamId: Int, headerBlock: List
, ) { - fail() + fail("") } override fun alternateService( @@ -104,6 +104,6 @@ internal open class BaseTestHandler : Http2Reader.Handler { port: Int, maxAge: Long, ) { - fail() + fail("") } } diff --git a/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt b/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt index 44b65f8c8..0d031b350 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt @@ -19,8 +19,10 @@ import assertk.assertThat import assertk.assertions.containsExactly import assertk.assertions.isEqualTo import assertk.assertions.isNull +import assertk.fail import java.io.IOException import java.util.Arrays +import kotlin.test.assertFailsWith import okhttp3.TestUtil.headerEntries import okio.Buffer import okio.ByteString @@ -337,11 +339,10 @@ class HpackTest { @Test fun readIndexedHeaderFieldIndex0() { bytesIn.writeByte(0x80) // == Indexed - Add idx = 0 - try { + assertFailsWith { hpackReader!!.readHeaders() - org.junit.jupiter.api.Assertions.fail("") - } catch (e: IOException) { - assertThat(e.message).isEqualTo("index == 0") + }.also { expected -> + assertThat(expected.message).isEqualTo("index == 0") } } @@ -349,11 +350,10 @@ class HpackTest { @Test fun readIndexedHeaderFieldTooLargeIndex() { bytesIn.writeShort(0xff00) // == Indexed - Add idx = 127 - try { + assertFailsWith { hpackReader!!.readHeaders() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("Header index too large 127") + }.also { expected -> + assertThat(expected.message).isEqualTo("Header index too large 127") } } @@ -362,11 +362,10 @@ class HpackTest { fun readIndexedHeaderFieldInsidiousIndex() { bytesIn.writeByte(0xff) // == Indexed - Add == bytesIn.write("8080808008".decodeHex()) // idx = -2147483521 - try { + assertFailsWith { hpackReader!!.readHeaders() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("Header index too large -2147483521") + }.also { expected -> + assertThat(expected.message).isEqualTo("Header index too large -2147483521") } } @@ -389,11 +388,10 @@ class HpackTest { bytesIn.writeByte(0x3f) // encode size 4097 bytesIn.writeByte(0xe2) bytesIn.writeByte(0x1f) - try { + assertFailsWith { hpackReader!!.readHeaders() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("Invalid dynamic table size update 4097") + }.also { expected -> + assertThat(expected.message).isEqualTo("Invalid dynamic table size update 4097") } } @@ -402,11 +400,10 @@ class HpackTest { fun readHeaderTableStateChangeInsidiousMaxHeaderByteCount() { bytesIn.writeByte(0x3f) bytesIn.write("e1ffffff07".decodeHex()) // count = -2147483648 - try { + assertFailsWith { hpackReader!!.readHeaders() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Invalid dynamic table size update -2147483648") } } @@ -483,11 +480,10 @@ class HpackTest { // Indexed name (idx = 4) -> :authority bytesIn.writeByte(0x0f) // Literal value (len = 15) bytesIn.writeUtf8("www.example.com") - try { + assertFailsWith { hpackReader!!.readHeaders() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("Header index too large 78") + }.also { expected -> + assertThat(expected.message).isEqualTo("Header index too large 78") } } @@ -817,7 +813,7 @@ class HpackTest { @Test fun mixedCaseHeaderNameIsMalformed() { - try { + assertFailsWith { newReader( byteStream( 0, @@ -831,9 +827,8 @@ class HpackTest { 'R'.code ) ).readHeaders() - org.junit.jupiter.api.Assertions.fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "PROTOCOL_ERROR response malformed: mixed case name: Foo" ) } diff --git a/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt b/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt index e515c62a5..4a68c7105 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt @@ -46,7 +46,8 @@ import okio.Source import okio.buffer import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertArrayEquals -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout @@ -237,19 +238,16 @@ class Http2ConnectionTest { val sink1 = stream1.getSink().buffer() val sink2 = stream2.getSink().buffer() sink1.writeUtf8("abc") - try { + assertFailsWith { sink2.writeUtf8("abc") sink2.flush() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM") } sink1.writeUtf8("def") sink1.close() - try { + assertFailsWith { connection.newStream(headerEntries("c", "cola"), true) - fail() - } catch (expected: ConnectionShutdownException) { } assertThat(stream1.isOpen).isTrue() assertThat(stream2.isOpen).isFalse() @@ -494,15 +492,11 @@ class Http2ConnectionTest { .build() connection.start( /* sendConnectionPreface = */false) socket.shutdownOutput() - try { + assertFailsWith { connection.newStream(headerEntries("a", longString), false) - fail() - } catch (expected: IOException) { } - try { + assertFailsWith { connection.newStream(headerEntries("b", longString), false) - fail() - } catch (expected: IOException) { } } @@ -676,10 +670,9 @@ class Http2ConnectionTest { connection.writePingAndAwaitPong() val sink = stream.getSink().buffer() sink.writeUtf8("abc") - try { + assertFailsWith { sink.close() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.errorCode).isEqualTo(ErrorCode.NO_ERROR) } assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android")) @@ -746,10 +739,8 @@ class Http2ConnectionTest { val connection = connect(peer) val stream = connection.newStream(headerEntries("a", "artichaut"), true) connection.writePingAndAwaitPong() - try { + assertFailsWith { stream.trailers() - fail() - } catch (expected: IllegalStateException) { } } @@ -767,10 +758,8 @@ class Http2ConnectionTest { val connection = connect(peer) val stream = connection.newStream(headerEntries("a", "artichaut"), true) connection.writePingAndAwaitPong() - try { + assertFailsWith { stream.trailers() - fail() - } catch (expected: StreamResetException) { } } @@ -788,10 +777,8 @@ class Http2ConnectionTest { val stream = connection.newStream(headerEntries("a", "android"), true) // finish the stream stream.writeHeaders(headerEntries("b", "berserk"), true, false) - try { + assertFailsWith { stream.enqueueTrailers(headersOf("trailers", "boom")) - fail() - } catch (expected: IllegalStateException) { } } @@ -1092,18 +1079,15 @@ class Http2ConnectionTest { val stream = connection.newStream(headerEntries("a", "android"), true) val out = stream.getSink().buffer() connection.writePingAndAwaitPong() // Ensure that the RST_CANCEL has been received. - try { + assertFailsWith { out.writeUtf8("square") out.flush() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream was reset: CANCEL") } - try { + // Close throws because buffered data wasn't flushed. + assertFailsWith { out.close() - fail() - } catch (expected: IOException) { - // Close throws because buffered data wasn't flushed. } assertThat(connection.openStreamCount()).isEqualTo(0) @@ -1133,17 +1117,15 @@ class Http2ConnectionTest { val source = stream.getSource() val out = stream.getSink().buffer() source.close() - try { + assertFailsWith { source.read(Buffer(), 1) - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream closed") } - try { + assertFailsWith { out.writeUtf8("a") out.flush() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream finished") } assertThat(connection.openStreamCount()).isEqualTo(0) @@ -1177,10 +1159,9 @@ class Http2ConnectionTest { val source = stream.getSource() val out = stream.getSink().buffer() source.close() - try { + assertFailsWith { source.read(Buffer(), 1) - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream closed") } out.writeUtf8("square") @@ -1327,10 +1308,9 @@ class Http2ConnectionTest { // Play it back. val connection = connect(peer) val stream = connection.newStream(headerEntries("a", "android"), false) - try { + assertFailsWith { stream.takeHeaders() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM") } assertThat(connection.openStreamCount()).isEqualTo(0) @@ -1363,19 +1343,16 @@ class Http2ConnectionTest { val sink1 = stream1.getSink().buffer() val sink2 = stream2.getSink().buffer() sink1.writeUtf8("abc") - try { + assertFailsWith { sink2.writeUtf8("abc") sink2.flush() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM") } sink1.writeUtf8("def") sink1.close() - try { + assertFailsWith { connection.newStream(headerEntries("c", "cola"), false) - fail() - } catch (expected: ConnectionShutdownException) { } assertThat(stream1.isOpen).isTrue() assertThat(stream2.isOpen).isFalse() @@ -1444,23 +1421,19 @@ class Http2ConnectionTest { assertThat(connection.openStreamCount()).isEqualTo(1) connection.close() assertThat(connection.openStreamCount()).isEqualTo(0) - try { + assertFailsWith { connection.newStream(headerEntries("b", "banana"), false) - fail() - } catch (expected: ConnectionShutdownException) { } val sink = stream.getSink().buffer() - try { + assertFailsWith { sink.writeByte(0) sink.flush() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream finished") } - try { + assertFailsWith { stream.getSource().read(Buffer(), 1) - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("stream was reset: CANCEL") } @@ -1487,10 +1460,8 @@ class Http2ConnectionTest { val stream = connection.newStream(headerEntries("b", "banana"), false) stream.readTimeout().timeout(500, TimeUnit.MILLISECONDS) val startNanos = System.nanoTime() - try { + assertFailsWith { stream.takeHeaders() - fail() - } catch (expected: InterruptedIOException) { } val elapsedNanos = System.nanoTime() - startNanos awaitWatchdogIdle() @@ -1530,10 +1501,8 @@ class Http2ConnectionTest { val source = stream.getSource().buffer() source.require(3) val startNanos = System.nanoTime() - try { + assertFailsWith { source.require(4) - fail() - } catch (expected: InterruptedIOException) { } val elapsedNanos = System.nanoTime() - startNanos awaitWatchdogIdle() @@ -1583,10 +1552,8 @@ class Http2ConnectionTest { stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS) val startNanos = System.nanoTime() sink.write(Buffer().writeUtf8("f"), 1) - try { + assertFailsWith { sink.flush() // This will time out waiting on the write window. - fail() - } catch (expected: InterruptedIOException) { } val elapsedNanos = System.nanoTime() - startNanos awaitWatchdogIdle() @@ -1628,10 +1595,8 @@ class Http2ConnectionTest { stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS) sink.write(Buffer().writeUtf8("abcdef"), 6) val startNanos = System.nanoTime() - try { + assertFailsWith { sink.flush() // This will time out waiting on the write window. - fail() - } catch (expected: InterruptedIOException) { } val elapsedNanos = System.nanoTime() - startNanos awaitWatchdogIdle() @@ -1835,10 +1800,8 @@ class Http2ConnectionTest { val stream = connection.newStream(headerEntries("b", "banana"), false) assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android")) val source = stream.getSource() - try { + assertFailsWith { source.buffer().readByteString(101) - fail() - } catch (expected: EOFException) { } } @@ -1914,10 +1877,9 @@ class Http2ConnectionTest { .build() connection.start( /* sendConnectionPreface = */false) val stream = connection.newStream(headerEntries("b", "banana"), false) - try { + assertFailsWith { stream.takeHeaders() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(expected.message).isEqualTo("Expected a SETTINGS frame but was HEADERS") } diff --git a/okhttp/src/test/java/okhttp3/internal/http2/Http2Test.kt b/okhttp/src/test/java/okhttp3/internal/http2/Http2Test.kt index caf35f1e6..4a05a6f07 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/Http2Test.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/Http2Test.kt @@ -40,7 +40,8 @@ import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.encodeUtf8 import okio.GzipSink import okio.buffer -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Test class Http2Test { @@ -265,11 +266,10 @@ class Http2Test { frame.writeInt(0) // Settings are always on the connection stream 0. frame.writeShort(2) frame.writeInt(2) - try { + assertFailsWith { reader.nextFrame(requireSettings = false, BaseTestHandler()) - fail("") - } catch (e: IOException) { - assertThat(e.message).isEqualTo("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1") + }.also { expected -> + assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1") } } @@ -310,11 +310,10 @@ class Http2Test { frame.writeInt(0) // Settings are always on the connection stream 0. frame.writeShort(4) // SETTINGS_INITIAL_WINDOW_SIZE frame.writeInt(Int.MIN_VALUE) - try { + assertFailsWith { reader.nextFrame(requireSettings = false, BaseTestHandler()) - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1" ) } @@ -327,11 +326,10 @@ class Http2Test { frame.writeInt(0) // Settings are always on the connection stream 0. frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE frame.writeInt(Int.MIN_VALUE) - try { + assertFailsWith { reader.nextFrame(requireSettings = false, BaseTestHandler()) - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: -2147483648" ) } @@ -344,11 +342,10 @@ class Http2Test { frame.writeInt(0) // Settings are always on the connection stream 0. frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE frame.writeInt(2.0.pow(14.0).toInt() - 1) - try { + assertFailsWith { reader.nextFrame(requireSettings = false, BaseTestHandler()) - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383") + }.also { expected -> + assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383") } } @@ -359,11 +356,10 @@ class Http2Test { frame.writeInt(0) // Settings are always on the connection stream 0. frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE frame.writeInt(2.0.pow(24.0).toInt()) - try { + assertFailsWith { reader.nextFrame(requireSettings = false, BaseTestHandler()) - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216") + }.also { expected -> + assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216") } } @@ -419,11 +415,10 @@ class Http2Test { frame.writeByte(FLAG_NONE) frame.writeInt(0) frame.write(payload) - try { + assertFailsWith { reader.nextFrame(requireSettings = false, BaseTestHandler()) - fail() - } catch (e: IOException) { - assertThat(e.message).isEqualTo("PROTOCOL_ERROR: TYPE_DATA streamId == 0") + }.also { expected -> + assertThat(expected.message).isEqualTo("PROTOCOL_ERROR: TYPE_DATA streamId == 0") } } @@ -438,11 +433,10 @@ class Http2Test { frame.writeByte(FLAG_COMPRESSED) frame.writeInt(expectedStreamId and 0x7fffffff) zipped.readAll(frame) - try { + assertFailsWith { reader.nextFrame(requireSettings = false, BaseTestHandler()) - fail() - } catch (e: IOException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA") } } @@ -536,11 +530,10 @@ class Http2Test { } @Test fun tooLargeDataFrame() { - try { + assertFailsWith { sendDataFrame(Buffer().write(ByteArray(0x1000000))) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216") + }.also { expected -> + assertThat(expected.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216") } } @@ -563,18 +556,16 @@ class Http2Test { } @Test fun badWindowSizeIncrement() { - try { + assertFailsWith { windowUpdate(0) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0") } - try { + assertFailsWith { windowUpdate(0x80000000L) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648") } } @@ -630,12 +621,11 @@ class Http2Test { @Test fun frameSizeError() { val writer = Http2Writer(Buffer(), true) - try { + assertFailsWith { writer.frameHeader(0, 16777216, Http2.TYPE_DATA, FLAG_NONE) - fail() - } catch (e: IllegalArgumentException) { + }.also { expected -> // TODO: real max is based on settings between 16384 and 16777215 - assertThat(e.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216") + assertThat(expected.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216") } } @@ -649,13 +639,12 @@ class Http2Test { @Test fun streamIdHasReservedBit() { val writer = Http2Writer(Buffer(), true) - try { + assertFailsWith { var streamId = 3 streamId = streamId or (1L shl 31).toInt() // set reserved bit writer.frameHeader(streamId, Http2.INITIAL_MAX_FRAME_SIZE, Http2.TYPE_DATA, FLAG_NONE) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message).isEqualTo("reserved bit set: -2147483645") + }.also { expected -> + assertThat(expected.message).isEqualTo("reserved bit set: -2147483645") } } diff --git a/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt b/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt index 161958460..c5395fd9a 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt @@ -21,8 +21,10 @@ import assertk.assertions.hasMessage import assertk.assertions.isCloseTo import assertk.assertions.isEqualTo import assertk.assertions.isFalse +import assertk.assertions.isIn import assertk.assertions.isNull import assertk.assertions.isTrue +import assertk.fail import java.io.File import java.io.IOException import java.net.HttpURLConnection @@ -38,6 +40,7 @@ import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicReference import javax.net.ssl.SSLException +import kotlin.test.assertFailsWith import mockwebserver3.Dispatcher import mockwebserver3.MockResponse import mockwebserver3.MockWebServer @@ -85,9 +88,9 @@ import okio.Buffer import okio.BufferedSink import okio.GzipSink import okio.buffer +import org.bouncycastle.tls.TlsFatalAlert import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertArrayEquals -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Assumptions.assumeTrue import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Tag @@ -546,10 +549,9 @@ class HttpOverHttp2Test { // Make a call expecting a timeout reading the response headers. val call1 = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call1.execute() - fail("Should have timed out!") - } catch (expected: SocketTimeoutException) { + }.also { expected -> assertThat(expected.message).isEqualTo("timeout") } @@ -613,10 +615,9 @@ class HttpOverHttp2Test { // Make a call expecting a timeout reading the response body. val call1 = client.newCall(Request(server.url("/"))) val response1 = call1.execute() - try { + assertFailsWith { response1.body.string() - fail("Should have timed out!") - } catch (expected: SocketTimeoutException) { + }.also { expected -> assertThat(expected.message).isEqualTo("timeout") } @@ -659,10 +660,8 @@ class HttpOverHttp2Test { ) val response1 = call1.execute() assertThat(response1.body.string()).isEqualTo("A") - try { + assertFailsWith { call2.execute() - fail() - } catch (expected: IOException) { } // Confirm that the connection was reused. @@ -825,10 +824,9 @@ class HttpOverHttp2Test { ) server.enqueue(MockResponse(body = "abc")) val call = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) } } @@ -876,10 +874,9 @@ class HttpOverHttp2Test { ) val request = Request(server.url("/")) - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) } assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection. @@ -899,10 +896,9 @@ class HttpOverHttp2Test { val request = Request(server.url("/")) // First call fails because it only has one route. - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) } assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) @@ -929,10 +925,9 @@ class HttpOverHttp2Test { val request = Request(server.url("/")) // First call makes a new connection and fails because it is the only route. - try { + assertFailsWith { client.newCall(request).execute() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) } assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection. @@ -968,10 +963,9 @@ class HttpOverHttp2Test { MockResponse(body = "abc") ) val call = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) } } @@ -1150,7 +1144,7 @@ class HttpOverHttp2Test { } override fun onResponse(call: Call, response: Response) { - fail() + fail("") } }) assertThat(server.takeRequest().sequenceNumber) @@ -1194,10 +1188,9 @@ class HttpOverHttp2Test { .retryOnConnectionFailure(false) .build() val call = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.errorCode).isEqualTo(errorCode) } } @@ -1235,7 +1228,7 @@ class HttpOverHttp2Test { .build() val callback: Callback = object : Callback { override fun onFailure(call: Call, e: IOException) { - fail() + fail("") } override fun onResponse(call: Call, response: Response) { @@ -1440,10 +1433,9 @@ class HttpOverHttp2Test { // Make a call. It'll fail as soon as our pings detect a problem. val call = client.newCall(Request(server.url("/"))) val executeAtNanos = System.nanoTime() - try { + assertFailsWith { call.execute() - fail() - } catch (expected: StreamResetException) { + }.also { expected -> assertThat(expected.message).isEqualTo( "stream was reset: PROTOCOL_ERROR" ) @@ -1478,19 +1470,19 @@ class HttpOverHttp2Test { // The first call times out. val call1 = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call1.execute() - fail() - } catch (expected: SocketTimeoutException) { - } catch (expected: SSLException) { + }.also { expected -> + when (expected) { + is SocketTimeoutException, is SSLException -> {} + else -> throw expected + } } // The second call times out because it uses the same bad connection. val call2 = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call2.execute() - fail() - } catch (expected: SocketTimeoutException) { } // But after the degraded pong timeout, that connection is abandoned. @@ -1520,12 +1512,10 @@ class HttpOverHttp2Test { // The first call times out. val call1 = client.newCall(Request(server.url("/"))) - try { + assertFailsWith { call1.execute().use { response -> response.body.string() - fail() } - } catch (expected: SocketTimeoutException) { } // The second call succeeds. @@ -1881,7 +1871,7 @@ class HttpOverHttp2Test { val latch = CountDownLatch(2) val callback: Callback = object : Callback { override fun onResponse(call: Call, response: Response) { - fail() + fail("") } override fun onFailure(call: Call, e: IOException) { @@ -1897,7 +1887,7 @@ class HttpOverHttp2Test { server.shutdown() } } catch (e: IOException) { - fail() + fail("") } } })).build() @@ -1930,10 +1920,9 @@ class HttpOverHttp2Test { ) ) callReference.set(call) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { + }.also { expected -> assertThat(call.isCanceled()).isTrue() } val recordedRequest = server.takeRequest() diff --git a/okhttp/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt b/okhttp/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt index 6c95313f6..6614a1999 100644 --- a/okhttp/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt @@ -20,7 +20,7 @@ import assertk.assertions.isEqualTo import assertk.assertions.isNull import assertk.assertions.isTrue import kotlin.test.assertEquals -import kotlin.test.fail +import kotlin.test.assertFailsWith import okhttp3.internal.toCanonicalHost import okio.Buffer import okio.FileSystem @@ -157,17 +157,14 @@ class PublicSuffixDatabaseTest { path = "/xxx.gz".toPath() ) lateinit var firstFailure: Exception - try { + assertFailsWith { badPublicSuffixDatabase.getEffectiveTldPlusOne("squareup.com") - fail("Read shouldn't have worked") - } catch (e: Exception) { + }.also { e -> firstFailure = e } - try { + assertFailsWith { badPublicSuffixDatabase.getEffectiveTldPlusOne("squareup.com") - fail("Read shouldn't have worked") - } catch (e: Exception) { - // expected + }.also { e -> assertEquals(firstFailure.toString(), e.toString()) } } diff --git a/okhttp/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt b/okhttp/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt index 9ef4fe0a5..9dc1a8462 100644 --- a/okhttp/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt @@ -19,6 +19,7 @@ import assertk.assertThat import assertk.assertions.contains import assertk.assertions.isEqualTo import assertk.assertions.startsWith +import java.io.IOException import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.KeyManager @@ -26,6 +27,7 @@ import javax.net.ssl.SSLHandshakeException import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.SocketPolicy.DisconnectAtEnd @@ -40,7 +42,6 @@ import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate import okhttp3.tls.internal.TlsUtil.newKeyManager import okhttp3.tls.internal.TlsUtil.newTrustManager -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension @@ -266,10 +267,9 @@ class CertificatePinnerChainValidationTest { .url(server.url("/")) .build() val call = client.newCall(request) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SSLPeerUnverifiedException) { + }.also { expected -> // Certificate pinning fails! assertThat(expected.message!!).startsWith("Certificate pinning failure!") } @@ -351,15 +351,20 @@ class CertificatePinnerChainValidationTest { .url(server.url("/")) .build() val call = client.newCall(request) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SSLHandshakeException) { - // On Android, the handshake fails before the certificate pinner runs. - assertThat(expected.message!!).contains("Could not validate certificate") - } catch (expected: SSLPeerUnverifiedException) { - // On OpenJDK, the handshake succeeds but the certificate pinner fails. - assertThat(expected.message!!).startsWith("Certificate pinning failure!") + }.also { expected -> + when (expected) { + is SSLHandshakeException -> { + // On Android, the handshake fails before the certificate pinner runs. + assertThat(expected.message!!).contains("Could not validate certificate") + } + is SSLPeerUnverifiedException -> { + // On OpenJDK, the handshake succeeds but the certificate pinner fails. + assertThat(expected.message!!).startsWith("Certificate pinning failure!") + } + else -> throw expected + } } } @@ -485,15 +490,20 @@ class CertificatePinnerChainValidationTest { .url(server.url("/")) .build() val call = client.newCall(request) - try { + assertFailsWith { call.execute() - .use { response -> fail("expected connection failure but got $response") } - } catch (expected: SSLPeerUnverifiedException) { - // Certificate pinning fails! - assertThat(expected.message!!).startsWith("Certificate pinning failure!") - } catch (expected: SSLHandshakeException) { - // We didn't have the opportunity to do certificate pinning because the handshake failed. - assertThat(expected.message!!).contains("this is not a CA certificate") + }.also { expected -> + when (expected) { + is SSLPeerUnverifiedException -> { + // Certificate pinning fails! + assertThat(expected.message!!).startsWith("Certificate pinning failure!") + } + is SSLHandshakeException -> { + // We didn't have the opportunity to do certificate pinning because the handshake failed. + assertThat(expected.message!!).contains("this is not a CA certificate") + } + else -> throw expected + } } } @@ -581,11 +591,8 @@ class CertificatePinnerChainValidationTest { .url(server.url("/")) .build() val call = client.newCall(request) - try { - call.execute().use { response -> - fail("expected connection failure but got $response") - } - } catch (expected: SSLHandshakeException) { + assertFailsWith { + call.execute() } } diff --git a/okhttp/src/test/java/okhttp3/internal/tls/ClientAuthTest.kt b/okhttp/src/test/java/okhttp3/internal/tls/ClientAuthTest.kt index 9fc40bd7c..817eb40df 100644 --- a/okhttp/src/test/java/okhttp3/internal/tls/ClientAuthTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/tls/ClientAuthTest.kt @@ -34,6 +34,7 @@ import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager import javax.security.auth.x500.X500Principal +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.junit5.internal.MockWebServerExtension @@ -48,7 +49,6 @@ import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate import okhttp3.tls.internal.TlsUtil.newKeyManager import okhttp3.tls.internal.TlsUtil.newTrustManager -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -210,17 +210,23 @@ class ClientAuthTest { server.useHttps(socketFactory) server.requireClientAuth() val call = client.newCall(Request.Builder().url(server.url("/")).build()) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SSLHandshakeException) { - // JDK 11+ - } catch (expected: SSLException) { - // javax.net.ssl.SSLException: readRecord - } catch (expected: SocketException) { - // Conscrypt, JDK 8 (>= 292), JDK 9 - } catch (expected: IOException) { - assertThat(expected.message).isEqualTo("exhausted all routes") + }.also { expected -> + when (expected) { + is SSLHandshakeException -> { + // JDK 11+ + } + is SSLException -> { + // javax.net.ssl.SSLException: readRecord + } + is SocketException -> { + // Conscrypt, JDK 8 (>= 292), JDK 9 + } + else -> { + assertThat(expected.message).isEqualTo("exhausted all routes") + } + } } } @@ -237,10 +243,8 @@ class ClientAuthTest { server.useHttps(socketFactory) server.requireClientAuth() val call = client.newCall(Request.Builder().url(server.url("/")).build()) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SSLPeerUnverifiedException) { } } @@ -257,19 +261,26 @@ class ClientAuthTest { server.useHttps(socketFactory) server.requireClientAuth() val call = client.newCall(Request.Builder().url(server.url("/")).build()) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: SSLHandshakeException) { - // JDK 11+ - } catch (expected: SSLException) { - // javax.net.ssl.SSLException: readRecord - } catch (expected: SocketException) { - // Conscrypt, JDK 8 (>= 292), JDK 9 - } catch (expected: ConnectionShutdownException) { - // It didn't fail until it reached the application layer. - } catch (expected: IOException) { - assertThat(expected.message).isEqualTo("exhausted all routes") + }.also { expected -> + when (expected) { + is SSLHandshakeException -> { + // JDK 11+ + } + is SSLException -> { + // javax.net.ssl.SSLException: readRecord + } + is SocketException -> { + // Conscrypt, JDK 8 (>= 292), JDK 9 + } + is ConnectionShutdownException -> { + // It didn't fail until it reached the application layer. + } + else -> { + assertThat(expected.message).isEqualTo("exhausted all routes") + } + } } } @@ -296,10 +307,8 @@ class ClientAuthTest { server.useHttps(socketFactory) server.requireClientAuth() val call = client.newCall(Request.Builder().url(server.url("/")).build()) - try { + assertFailsWith { call.execute() - fail() - } catch (expected: IOException) { } // Observed Events are variable diff --git a/okhttp/src/test/java/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt b/okhttp/src/test/java/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt index 400f38e52..b9d444268 100644 --- a/okhttp/src/test/java/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt @@ -19,12 +19,12 @@ import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isLessThan import java.io.EOFException +import kotlin.test.assertFailsWith import okhttp3.TestUtil.fragmentBuffer import okio.Buffer import okio.ByteString import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.encodeUtf8 -import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Test internal class MessageDeflaterInflaterTest { @@ -110,10 +110,8 @@ internal class MessageDeflaterInflaterTest { val deflater = MessageDeflater(true) deflater.close() - try { + assertFailsWith { deflater.deflate("Hello deflate!".encodeUtf8()) - fail() - } catch (expected: Exception) { } } @@ -122,10 +120,8 @@ internal class MessageDeflaterInflaterTest { inflater.close() - try { + assertFailsWith { inflater.inflate("f240e30300".decodeHex()) - fail() - } catch (expected: Exception) { } } diff --git a/okhttp/src/test/java/okhttp3/internal/ws/RealWebSocketTest.kt b/okhttp/src/test/java/okhttp3/internal/ws/RealWebSocketTest.kt index 325d2de75..bea512447 100644 --- a/okhttp/src/test/java/okhttp3/internal/ws/RealWebSocketTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/ws/RealWebSocketTest.kt @@ -26,6 +26,7 @@ import java.io.IOException import java.net.ProtocolException import java.net.SocketTimeoutException import java.util.Random +import kotlin.test.assertFailsWith import okhttp3.Headers import okhttp3.Headers.Companion.headersOf import okhttp3.Protocol @@ -98,10 +99,9 @@ class RealWebSocketTest { @Test fun clientCloseWith0Fails() { - try { + assertFailsWith { client.webSocket!!.close(0, null) - org.junit.jupiter.api.Assertions.fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat("Code must be in range [1000,5000): 0") .isEqualTo(expected.message) } diff --git a/okhttp/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.kt b/okhttp/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.kt index daf411633..e90391843 100644 --- a/okhttp/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.kt @@ -38,6 +38,7 @@ import java.util.Random import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger +import kotlin.test.assertFailsWith import mockwebserver3.Dispatcher import mockwebserver3.MockResponse import mockwebserver3.MockWebServer @@ -607,10 +608,9 @@ class WebSocketHttpTest { val server = serverListener.assertOpen() clientListener.assertOpen() val reason = repeat('X', 124) - try { + assertFailsWith { webSocket.close(1000, reason) - org.junit.jupiter.api.Assertions.fail() - } catch (expected: IllegalArgumentException) { + }.also { expected -> assertThat(expected.message).isEqualTo("reason.size() > 123: $reason") } webSocket.close(1000, null) diff --git a/okhttp/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.kt b/okhttp/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.kt index 88c3861b5..1330b11e0 100644 --- a/okhttp/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.kt @@ -24,6 +24,7 @@ import java.io.EOFException import java.io.IOException import java.net.ProtocolException import java.util.Random +import kotlin.test.assertFailsWith import okhttp3.internal.format import okio.Buffer import okio.ByteString @@ -75,92 +76,83 @@ class WebSocketReaderTest { @Test fun controlFramesMustBeFinal() { data.write("0a00".decodeHex()) // Empty pong. - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Control frames must be final.") } } @Test fun reservedFlag1IsUnsupportedWithNoCompression() { data.write("ca00".decodeHex()) // Empty pong, flag 1 set. - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message).isEqualTo("Unexpected rsv1 flag") + }.also { expected -> + assertThat(expected.message).isEqualTo("Unexpected rsv1 flag") } } @Test fun reservedFlag1IsUnsupportedForControlFrames() { data.write("ca00".decodeHex()) // Empty pong, flag 1 set. - try { + assertFailsWith { clientReaderWithCompression.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message).isEqualTo("Unexpected rsv1 flag") + }.also { expected -> + assertThat(expected.message).isEqualTo("Unexpected rsv1 flag") } } @Test fun reservedFlag1IsUnsupportedForContinuationFrames() { data.write("c000".decodeHex()) // Empty continuation, flag 1 set. - try { + assertFailsWith { clientReaderWithCompression.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message).isEqualTo("Unexpected rsv1 flag") + }.also { expected -> + assertThat(expected.message).isEqualTo("Unexpected rsv1 flag") } } @Test fun reservedFlags2and3AreUnsupported() { data.write("aa00".decodeHex()) // Empty pong, flag 2 set. - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message).isEqualTo("Unexpected rsv2 flag") + }.also { expected -> + assertThat(expected.message).isEqualTo("Unexpected rsv2 flag") } data.clear() data.write("9a00".decodeHex()) // Empty pong, flag 3 set. - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message).isEqualTo("Unexpected rsv3 flag") + }.also { expected -> + assertThat(expected.message).isEqualTo("Unexpected rsv3 flag") } } @Test fun clientSentFramesMustBeMasked() { data.write("8100".decodeHex()) - try { + assertFailsWith { serverReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Client-sent frames must be masked.") } } @Test fun serverSentFramesMustNotBeMasked() { - data.write("8180".decodeHex()) - try { + data.write("8180".decodeHex()) + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Server-sent frames must not be masked.") } } @Test fun controlFramePayloadMax() { data.write("8a7e007e".decodeHex()) - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Control frame must be less than 125B.") } } @@ -215,11 +207,10 @@ class WebSocketReaderTest { @Test fun clientFramePayloadTooLongThrows() { data.write("817f8000000000000000".decodeHex()) - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Frame length 0x8000000000000000 > 0x7FFFFFFFFFFFFFFF" ) } @@ -299,46 +290,36 @@ class WebSocketReaderTest { @Test fun clientIncompleteMessageBodyThrows() { data.write("810548656c".decodeHex()) // Length = 5, "Hel" - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (ignored: EOFException) { } } @Test fun clientUncompressedMessageWithCompressedFlagThrows() { data.write("c10548656c6c6f".decodeHex()) // Uncompressed 'Hello', flag 1 set - try { + assertFailsWith { clientReaderWithCompression.processNextFrame() - fail("") - } catch (ignored: IOException) { } } @Test fun clientIncompleteControlFrameBodyThrows() { data.write("8a0548656c".decodeHex()) // Length = 5, "Hel" - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (ignored: EOFException) { } } @Test fun serverIncompleteMessageBodyThrows() { data.write("818537fa213d7f9f4d".decodeHex()) // Length = 5, "Hel" - try { + assertFailsWith { serverReader.processNextFrame() - fail("") - } catch (ignored: EOFException) { } } @Test fun serverIncompleteControlFrameBodyThrows() { data.write("8a8537fa213d7f9f4d".decodeHex()) // Length = 5, "Hel" - try { + assertFailsWith { serverReader.processNextFrame() - fail("") - } catch (ignored: EOFException) { } } @@ -361,11 +342,10 @@ class WebSocketReaderTest { val bytes = binaryData(200) data.write("0264".decodeHex()).write(bytes, 0, 100) data.write("8264".decodeHex()).write(bytes, 100, 100) - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Expected continuation opcode. Got: 2") } } @@ -390,11 +370,10 @@ class WebSocketReaderTest { @Test fun closeLengthOfOneThrows() { data.write("880100".decodeHex()) // Close with invalid 1-byte payload - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Malformed close payload length of 1.") } } @@ -414,19 +393,17 @@ class WebSocketReaderTest { @Test fun closeOutOfRangeThrows() { data.write("88020001".decodeHex()) // Close with code 1 - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Code must be in range [1000,5000): 1") } data.write("88021388".decodeHex()) // Close with code 5000 - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message) + }.also { expected -> + assertThat(expected.message) .isEqualTo("Code must be in range [1000,5000): 5000") } } @@ -440,11 +417,10 @@ class WebSocketReaderTest { } var count = 0 while (!data.exhausted()) { - try { + assertFailsWith { clientReader.processNextFrame() - fail("") - } catch (e: ProtocolException) { - assertThat(e.message!!) + }.also { expected -> + assertThat(expected.message!!) .matches(Regex("Code \\d+ is reserved and may not be used.")) } count++ @@ -458,11 +434,10 @@ class WebSocketReaderTest { callback.assertTextMessage("Hello") data.write("c107f248cdc9c90700".decodeHex()) // Hello clientReaderWithCompression.close() - try { + assertFailsWith { clientReaderWithCompression.processNextFrame() - fail("") - } catch (e: Exception) { - assertThat(e.message!!).contains("closed") + }.also { expected -> + assertThat(expected.message!!).contains("closed") } } diff --git a/okhttp/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.kt b/okhttp/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.kt index 3052fc0ff..73644c532 100644 --- a/okhttp/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/ws/WebSocketWriterTest.kt @@ -30,7 +30,8 @@ import okio.ByteString.Companion.EMPTY import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.toByteString -import org.junit.jupiter.api.Assertions.fail +import assertk.fail +import kotlin.test.assertFailsWith import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.ExtensionContext @@ -196,20 +197,18 @@ class WebSocketWriterTest { } @Test fun closeCodeOutOfRangeThrows() { - try { + assertFailsWith { clientWriter.writeClose(98724976, "Hello".encodeUtf8()) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message).isEqualTo("Code must be in range [1000,5000): 98724976") + }.also { expected -> + assertThat(expected.message).isEqualTo("Code must be in range [1000,5000): 98724976") } } @Test fun closeReservedThrows() { - try { + assertFailsWith { clientWriter.writeClose(1005, "Hello".encodeUtf8()) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message).isEqualTo("Code 1005 is reserved and may not be used.") + }.also { expected -> + assertThat(expected.message).isEqualTo("Code 1005 is reserved and may not be used.") } } @@ -254,34 +253,31 @@ class WebSocketWriterTest { } @Test fun pingTooLongThrows() { - try { + assertFailsWith { serverWriter.writePing(binaryData(1000)) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Payload size must be less than or equal to 125" ) } } @Test fun pongTooLongThrows() { - try { + assertFailsWith { serverWriter.writePong((binaryData(1000))) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Payload size must be less than or equal to 125" ) } } @Test fun closeTooLongThrows() { - try { + assertFailsWith { val longReason: ByteString = repeat('X', 124).encodeUtf8() serverWriter.writeClose(1000, longReason) - fail() - } catch (e: IllegalArgumentException) { - assertThat(e.message).isEqualTo( + }.also { expected -> + assertThat(expected.message).isEqualTo( "Payload size must be less than or equal to 125" ) }