1
0
mirror of https://github.com/square/okhttp.git synced 2025-07-31 05:04:26 +03:00

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
This commit is contained in:
Jesse Wilson
2024-01-06 00:31:00 -05:00
committed by GitHub
parent 8ebb4b1f94
commit 23d67c304f
68 changed files with 928 additions and 1411 deletions

View File

@ -21,6 +21,8 @@ dependencies {
testImplementation(projects.okhttpTestingSupport) testImplementation(projects.okhttpTestingSupport)
testImplementation(projects.okhttpTls) testImplementation(projects.okhttpTls)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
} }
mavenPublishing { mavenPublishing {

View File

@ -40,6 +40,7 @@ import java.util.Arrays
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
import javax.net.ssl.HttpsURLConnection import javax.net.ssl.HttpsURLConnection
import kotlin.test.assertFailsWith
import okhttp3.Headers import okhttp3.Headers
import okhttp3.Protocol import okhttp3.Protocol
import okhttp3.RecordingHostnameVerifier import okhttp3.RecordingHostnameVerifier
@ -500,11 +501,10 @@ class MockWebServerTest {
val connection = url.openConnection() as HttpURLConnection val connection = url.openConnection() as HttpURLConnection
assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK) assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK)
val refusedConnection = url.openConnection() as HttpURLConnection val refusedConnection = url.openConnection() as HttpURLConnection
try { assertFailsWith<ConnectException> {
refusedConnection.getResponseCode() refusedConnection.getResponseCode()
fail<Any>("Second connection should be refused") }.also { expected ->
} catch (e: ConnectException) { assertThat(expected.message!!).contains("refused")
assertThat(e.message!!).contains("refused")
} }
} }

View File

@ -21,6 +21,8 @@ dependencies {
testImplementation(projects.okhttpTls) testImplementation(projects.okhttpTls)
testRuntimeOnly(projects.mockwebserver3Junit5) testRuntimeOnly(projects.mockwebserver3Junit5)
testImplementation(libs.junit) testImplementation(libs.junit)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
testImplementation(libs.assertk) testImplementation(libs.assertk)
} }

View File

@ -38,6 +38,7 @@ import java.nio.charset.StandardCharsets.UTF_8
import java.time.Duration import java.time.Duration
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.net.ssl.HttpsURLConnection import javax.net.ssl.HttpsURLConnection
import kotlin.test.assertFailsWith
import mockwebserver3.SocketPolicy.DisconnectAtStart import mockwebserver3.SocketPolicy.DisconnectAtStart
import mockwebserver3.SocketPolicy.DisconnectDuringRequestBody import mockwebserver3.SocketPolicy.DisconnectDuringRequestBody
import mockwebserver3.SocketPolicy.DisconnectDuringResponseBody import mockwebserver3.SocketPolicy.DisconnectDuringResponseBody
@ -496,11 +497,10 @@ class MockWebServerTest {
val connection = url.openConnection() as HttpURLConnection val connection = url.openConnection() as HttpURLConnection
assertThat(connection.responseCode).isEqualTo(HttpURLConnection.HTTP_OK) assertThat(connection.responseCode).isEqualTo(HttpURLConnection.HTTP_OK)
val refusedConnection = url.openConnection() as HttpURLConnection val refusedConnection = url.openConnection() as HttpURLConnection
try { assertFailsWith<ConnectException> {
refusedConnection.responseCode refusedConnection.responseCode
fail<Any?>("Second connection should be refused") }.also { expected ->
} catch (e: ConnectException) { assertThat(expected.message!!).contains("refused")
assertThat(e.message!!).contains("refused")
} }
} }

View File

@ -27,6 +27,8 @@ dependencies {
implementation(libs.junit.jupiter.api) implementation(libs.junit.jupiter.api)
implementation(libs.junit.jupiter.params) implementation(libs.junit.jupiter.params)
implementation(libs.assertk) implementation(libs.assertk)
implementation(libs.kotlin.test.common)
implementation(libs.kotlin.test.junit)
implementation(libs.nativeImageSvm) implementation(libs.nativeImageSvm)

View File

@ -22,6 +22,8 @@ dependencies {
testImplementation(projects.okhttpTestingSupport) testImplementation(projects.okhttpTestingSupport)
testImplementation(libs.conscrypt.openjdk) testImplementation(libs.conscrypt.openjdk)
testImplementation(libs.junit) testImplementation(libs.junit)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
testImplementation(libs.assertk) testImplementation(libs.assertk)
} }

View File

@ -21,6 +21,7 @@ import assertk.assertions.hasMessage
import assertk.assertions.isEmpty import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import java.io.IOException import java.io.IOException
import kotlin.test.assertFailsWith
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol import okhttp3.Protocol
import okhttp3.Request import okhttp3.Request
@ -32,7 +33,6 @@ import okio.ByteString.Companion.EMPTY
import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.decodeHex
import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.encodeUtf8
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
class BrotliInterceptorTest { class BrotliInterceptorTest {
@Test @Test
@ -90,12 +90,10 @@ class BrotliInterceptorTest {
header("Content-Encoding", "br") header("Content-Encoding", "br")
} }
try { assertFailsWith<IOException> {
val failingResponse = uncompress(response) val failingResponse = uncompress(response)
failingResponse.body.string() failingResponse.body.string()
}.also { ioe ->
fail("expected uncompress error")
} catch (ioe: IOException) {
assertThat(ioe).hasMessage("Brotli stream decoding failed") assertThat(ioe).hasMessage("Brotli stream decoding failed")
assertThat(ioe.cause?.javaClass?.simpleName).isEqualTo("BrotliRuntimeException") assertThat(ioe.cause?.javaClass?.simpleName).isEqualTo("BrotliRuntimeException")
} }

View File

@ -20,8 +20,9 @@ dependencies {
api(libs.squareup.okio) api(libs.squareup.okio)
api(libs.kotlin.stdlib) api(libs.kotlin.stdlib)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.annotations) testImplementation(libs.kotlin.test.annotations)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
testApi(libs.assertk) testApi(libs.assertk)
testImplementation(projects.okhttpTestingSupport) testImplementation(projects.okhttpTestingSupport)
testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.kotlinx.coroutines.test)

View File

@ -24,6 +24,7 @@ import assertk.assertions.isEqualTo
import assertk.assertions.isTrue import assertk.assertions.isTrue
import java.io.IOException import java.io.IOException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.test.assertFailsWith
import kotlin.time.Duration.Companion.seconds import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
@ -141,15 +142,12 @@ class SuspendCallTest {
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<IOException> {
call.executeAsync().use { call.executeAsync().use {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
it.body.string() it.body.string()
} }
} }
fail("No expected to get response")
} catch (ioe: IOException) {
// expected
} }
} }
} }

View File

@ -24,6 +24,8 @@ dependencies {
testImplementation(libs.squareup.okio.fakefilesystem) testImplementation(libs.squareup.okio.fakefilesystem)
testImplementation(libs.conscrypt.openjdk) testImplementation(libs.conscrypt.openjdk)
testImplementation(libs.junit) testImplementation(libs.junit)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
} }
mavenPublishing { mavenPublishing {

View File

@ -22,6 +22,7 @@ import assertk.assertions.isEqualTo
import assertk.fail import assertk.fail
import java.net.InetAddress import java.net.InetAddress
import java.net.UnknownHostException import java.net.UnknownHostException
import kotlin.test.assertFailsWith
import okhttp3.AsyncDns.Companion.TYPE_A import okhttp3.AsyncDns.Companion.TYPE_A
import okhttp3.AsyncDns.Companion.TYPE_AAAA import okhttp3.AsyncDns.Companion.TYPE_AAAA
import okhttp3.dnsoverhttps.DnsRecordCodec.decodeAnswers import okhttp3.dnsoverhttps.DnsRecordCodec.decodeAnswers
@ -80,16 +81,15 @@ class DnsRecordCodecTest {
@Test @Test
fun testGoogleDotComDecodingNxdomainFailure() { fun testGoogleDotComDecodingNxdomainFailure() {
try { assertFailsWith<UnknownHostException> {
decodeAnswers( decodeAnswers(
hostname = "sdflkhfsdlkjdf.ee", hostname = "sdflkhfsdlkjdf.ee",
byteString = ("0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b" + byteString = ("0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b" +
"00060001000007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e65" + "00060001000007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e65" +
"74c01b5adb12c100000e10000003840012750000000e10").decodeHex() "74c01b5adb12c100000e10000003840012750000000e10").decodeHex()
) )
fail("") }.also { expected ->
} catch (uhe: UnknownHostException) { assertThat(expected.message).isEqualTo("sdflkhfsdlkjdf.ee: NXDOMAIN")
assertThat(uhe.message).isEqualTo("sdflkhfsdlkjdf.ee: NXDOMAIN")
} }
} }
} }

View File

@ -27,6 +27,8 @@ dependencies {
compileOnly(libs.findbugs.jsr305) compileOnly(libs.findbugs.jsr305)
compileOnly(libs.robolectric.android) compileOnly(libs.robolectric.android)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
} }
animalsniffer { animalsniffer {

View File

@ -17,11 +17,11 @@ package okhttp3
import assertk.assertThat import assertk.assertThat
import assertk.assertions.hasMessage import assertk.assertions.hasMessage
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail
class OkHttpClientTestRuleTest { class OkHttpClientTestRuleTest {
lateinit var extensionContext: ExtensionContext lateinit var extensionContext: ExtensionContext
@ -42,10 +42,9 @@ class OkHttpClientTestRuleTest {
thread.start() thread.start()
thread.join() thread.join()
try { assertFailsWith<AssertionError> {
testRule.afterEach(extensionContext) testRule.afterEach(extensionContext)
fail("") }.also { expected ->
} catch (expected: AssertionError) {
assertThat(expected).hasMessage("uncaught exception thrown during test") assertThat(expected).hasMessage("uncaught exception thrown during test")
assertThat(expected.cause!!).hasMessage("boom!") assertThat(expected.cause!!).hasMessage("boom!")
} }

View File

@ -24,6 +24,8 @@ dependencies {
testImplementation(projects.okhttpTestingSupport) testImplementation(projects.okhttpTestingSupport)
testImplementation(projects.mockwebserver3Junit5) testImplementation(projects.mockwebserver3Junit5)
testImplementation(libs.junit) testImplementation(libs.junit)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
testImplementation(libs.assertk) testImplementation(libs.assertk)
} }

View File

@ -27,6 +27,7 @@ import java.net.ProtocolException
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Date import java.util.Date
import java.util.TimeZone import java.util.TimeZone
import kotlin.test.assertFailsWith
import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName
import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress
import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints
@ -69,10 +70,9 @@ internal class DerTest {
val derReader = DerReader(buffer) val derReader = DerReader(buffer)
try { assertFailsWith<ProtocolException> {
derReader.read("test") {} derReader.read("test") {}
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message).isEqualTo("invalid encoding for length") assertThat(expected.message).isEqualTo("invalid encoding for length")
} }
} }
@ -85,10 +85,9 @@ internal class DerTest {
val derReader = DerReader(buffer) val derReader = DerReader(buffer)
try { assertFailsWith<ProtocolException> {
derReader.read("test") {} derReader.read("test") {}
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message).isEqualTo("invalid encoding for length") assertThat(expected.message).isEqualTo("invalid encoding for length")
} }
} }
@ -127,10 +126,9 @@ internal class DerTest {
val derReader = DerReader(buffer) val derReader = DerReader(buffer)
try { assertFailsWith<ProtocolException> {
derReader.read("test") {} derReader.read("test") {}
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message).isEqualTo("length > Long.MAX_VALUE") assertThat(expected.message).isEqualTo("length > Long.MAX_VALUE")
} }
} }
@ -152,10 +150,9 @@ internal class DerTest {
val derReader = DerReader(buffer) val derReader = DerReader(buffer)
try { assertFailsWith<ProtocolException> {
derReader.read("test") {} derReader.read("test") {}
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("length encoded with more than 8 bytes is not supported") .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`() { @Test fun `cannot decode utc time with offset`() {
try { assertFailsWith<ProtocolException> {
Adapters.UTC_TIME.fromDer("17113139313231353139303231302d30383030".decodeHex()) Adapters.UTC_TIME.fromDer("17113139313231353139303231302d30383030".decodeHex())
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("Failed to parse UTCTime 191215190210-0800") assertThat(expected).hasMessage("Failed to parse UTCTime 191215190210-0800")
} }
} }
@ -651,19 +647,17 @@ internal class DerTest {
@Test fun `cannot decode malformed utc time`() { @Test fun `cannot decode malformed utc time`() {
val bytes = "170d3139313231362333303231305a".decodeHex() val bytes = "170d3139313231362333303231305a".decodeHex()
try { assertFailsWith<ProtocolException> {
Adapters.UTC_TIME.fromDer(bytes) Adapters.UTC_TIME.fromDer(bytes)
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("Failed to parse UTCTime 191216#30210Z") assertThat(expected).hasMessage("Failed to parse UTCTime 191216#30210Z")
} }
} }
@Test fun `cannot decode generalized time with offset`() { @Test fun `cannot decode generalized time with offset`() {
try { assertFailsWith<ProtocolException> {
Adapters.GENERALIZED_TIME.fromDer("181332303139313231353139303231302d30383030".decodeHex()) Adapters.GENERALIZED_TIME.fromDer("181332303139313231353139303231302d30383030".decodeHex())
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191215190210-0800") assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191215190210-0800")
} }
} }
@ -677,10 +671,9 @@ internal class DerTest {
@Test fun `cannot decode malformed generalized time`() { @Test fun `cannot decode malformed generalized time`() {
val bytes = "180f32303139313231362333303231305a".decodeHex() val bytes = "180f32303139313231362333303231305a".decodeHex()
try { assertFailsWith<ProtocolException> {
Adapters.GENERALIZED_TIME.fromDer(bytes) Adapters.GENERALIZED_TIME.fromDer(bytes)
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191216#30210Z") assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191216#30210Z")
} }
} }
@ -779,10 +772,9 @@ internal class DerTest {
@Test fun `cannot decode empty bit string`() { @Test fun `cannot decode empty bit string`() {
val bytes = "0300".decodeHex() val bytes = "0300".decodeHex()
try { assertFailsWith<ProtocolException> {
Adapters.BIT_STRING.fromDer(bytes) Adapters.BIT_STRING.fromDer(bytes)
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("malformed bit string") assertThat(expected).hasMessage("malformed bit string")
} }
} }
@ -795,41 +787,39 @@ internal class DerTest {
} }
@Test fun `cannot decode constructed octet string`() { @Test fun `cannot decode constructed octet string`() {
try { assertFailsWith<ProtocolException> {
Adapters.OCTET_STRING.fromDer( Adapters.OCTET_STRING.fromDer(
"2410040668656c6c6f200406776f726c6421".decodeHex()) "2410040668656c6c6f200406776f726c6421".decodeHex()
fail("") )
} catch (expected: ProtocolException) { }.also { expected ->
assertThat(expected).hasMessage("constructed octet strings not supported for DER") assertThat(expected).hasMessage("constructed octet strings not supported for DER")
} }
} }
@Test fun `cannot decode constructed bit string`() { @Test fun `cannot decode constructed bit string`() {
try { assertFailsWith<ProtocolException> {
Adapters.BIT_STRING.fromDer( Adapters.BIT_STRING.fromDer(
"231203070068656c6c6f20030700776f726c6421".decodeHex()) "231203070068656c6c6f20030700776f726c6421".decodeHex()
fail("") )
} catch (expected: ProtocolException) { }.also { expected ->
assertThat(expected).hasMessage("constructed bit strings not supported for DER") assertThat(expected).hasMessage("constructed bit strings not supported for DER")
} }
} }
@Test fun `cannot decode constructed string`() { @Test fun `cannot decode constructed string`() {
try { assertFailsWith<ProtocolException> {
Adapters.UTF8_STRING.fromDer( Adapters.UTF8_STRING.fromDer(
"2c100c0668656c6c6f200c06776f726c6421".decodeHex()) "2c100c0668656c6c6f200c06776f726c6421".decodeHex())
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("constructed strings not supported for DER") assertThat(expected).hasMessage("constructed strings not supported for DER")
} }
} }
@Test fun `cannot decode indefinite length bit string`() { @Test fun `cannot decode indefinite length bit string`() {
try { assertFailsWith<ProtocolException> {
Adapters.BIT_STRING.fromDer( Adapters.BIT_STRING.fromDer(
"23800303000A3B0305045F291CD00000".decodeHex()) "23800303000A3B0305045F291CD00000".decodeHex())
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("indefinite length not permitted for DER") assertThat(expected).hasMessage("indefinite length not permitted for DER")
} }
} }
@ -838,12 +828,11 @@ internal class DerTest {
val buffer = Buffer() val buffer = Buffer()
.write("3A0904034A6F6E04026573".decodeHex()) .write("3A0904034A6F6E04026573".decodeHex())
val derReader = DerReader(buffer) val derReader = DerReader(buffer)
try { assertFailsWith<Exception> {
derReader.read("test") { derReader.read("test") {
derReader.readOctetString() derReader.readOctetString()
} }
fail("") }.also { expected ->
} catch (expected: Exception) {
assertThat(expected).hasMessage("constructed octet strings not supported for DER") 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. */ /** Make the claimed length of a nested object larger than the enclosing object. */
@Test fun `large object inside small object`() { @Test fun `large object inside small object`() {
val bytes = "301b300d06092a864886f70d010101050003847fffffff000504030201".decodeHex() val bytes = "301b300d06092a864886f70d010101050003847fffffff000504030201".decodeHex()
try { assertFailsWith<ProtocolException> {
CertificateAdapters.subjectPublicKeyInfo.fromDer(bytes) CertificateAdapters.subjectPublicKeyInfo.fromDer(bytes)
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message).isEqualTo("enclosed object too large") 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. */ /** Object identifiers are nominally self-delimiting. Outrun the limit with one. */
@Test fun `variable length long outruns limit`() { @Test fun `variable length long outruns limit`() {
val bytes = "060229ffffff7f".decodeHex() val bytes = "060229ffffff7f".decodeHex()
try { assertFailsWith<ProtocolException> {
Adapters.OBJECT_IDENTIFIER.fromDer(bytes) Adapters.OBJECT_IDENTIFIER.fromDer(bytes)
fail("") }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message).isEqualTo("unexpected byte count at OBJECT IDENTIFIER") assertThat(expected.message).isEqualTo("unexpected byte count at OBJECT IDENTIFIER")
} }
} }

View File

@ -21,9 +21,9 @@ import assertk.assertions.isFalse
import assertk.assertions.isSameAs import assertk.assertions.isSameAs
import assertk.assertions.isTrue import assertk.assertions.isTrue
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.test.assertFailsWith
import okhttp3.CacheControl.Companion.parse import okhttp3.CacheControl.Companion.parse
import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.headersOf
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
class CacheControlJvmTest { class CacheControlJvmTest {
@ -192,10 +192,8 @@ class CacheControlJvmTest {
@Throws(Exception::class) @Throws(Exception::class)
fun secondsMustBeNonNegative() { fun secondsMustBeNonNegative() {
val builder = CacheControl.Builder() val builder = CacheControl.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.maxAge(-1, TimeUnit.SECONDS) builder.maxAge(-1, TimeUnit.SECONDS)
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }

View File

@ -24,6 +24,7 @@ import assertk.assertions.isFalse
import assertk.assertions.isNotNull import assertk.assertions.isNotNull
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.fail
import java.io.IOException import java.io.IOException
import java.net.CookieManager import java.net.CookieManager
import java.net.HttpURLConnection import java.net.HttpURLConnection
@ -36,6 +37,7 @@ import java.util.TimeZone
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicReference
import javax.net.ssl.HostnameVerifier import javax.net.ssl.HostnameVerifier
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.RecordedRequest import mockwebserver3.RecordedRequest
@ -58,8 +60,8 @@ import okio.Path
import okio.Path.Companion.toPath import okio.Path.Companion.toPath
import okio.buffer import okio.buffer
import okio.fakefilesystem.FakeFileSystem import okio.fakefilesystem.FakeFileSystem
import okio.use
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -692,12 +694,10 @@ class CacheTest {
) )
val bodySource = get(server.url("/")).body.source() val bodySource = get(server.url("/")).body.source()
assertThat(bodySource.readUtf8Line()).isEqualTo("ABCDE") assertThat(bodySource.readUtf8Line()).isEqualTo("ABCDE")
try { bodySource.use {
assertFailsWith<IOException> {
bodySource.readUtf8(21) bodySource.readUtf8(21)
fail<Any>("This implementation silently ignored a truncated HTTP body.") }
} catch (expected: IOException) {
} finally {
bodySource.close()
} }
assertThat(cache.writeAbortCount()).isEqualTo(1) assertThat(cache.writeAbortCount()).isEqualTo(1)
assertThat(cache.writeSuccessCount()).isEqualTo(0) assertThat(cache.writeSuccessCount()).isEqualTo(0)
@ -737,10 +737,8 @@ class CacheTest {
val `in` = response1.body.source() val `in` = response1.body.source()
assertThat(`in`.readUtf8(5)).isEqualTo("ABCDE") assertThat(`in`.readUtf8(5)).isEqualTo("ABCDE")
`in`.close() `in`.close()
try { assertFailsWith<IllegalStateException> {
`in`.readByte() `in`.readByte()
fail<Any>("Expected an IllegalStateException because the source is closed.")
} catch (expected: IllegalStateException) {
} }
assertThat(cache.writeAbortCount()).isEqualTo(1) assertThat(cache.writeAbortCount()).isEqualTo(1)
assertThat(cache.writeSuccessCount()).isEqualTo(0) assertThat(cache.writeSuccessCount()).isEqualTo(0)
@ -2916,10 +2914,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length}
// ... and nothing else. // ... and nothing else.
assertThat(i.hasNext()).isFalse() assertThat(i.hasNext()).isFalse()
try { assertFailsWith<NoSuchElementException> {
i.next() i.next()
fail<Any>()
} catch (expected: NoSuchElementException) {
} }
} }
@ -2961,10 +2957,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length}
assertThat(get(url).body.string()).isEqualTo("a") assertThat(get(url).body.string()).isEqualTo("a")
val i = cache.urls() val i = cache.urls()
assertThat(i.hasNext()).isTrue() assertThat(i.hasNext()).isTrue()
try { assertFailsWith<IllegalStateException> {
i.remove() i.remove()
fail<Any>()
} catch (expected: IllegalStateException) {
} }
} }
@ -2983,10 +2977,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length}
i.remove() i.remove()
// Too many calls to remove(). // Too many calls to remove().
try { assertFailsWith<IllegalStateException> {
i.remove() i.remove()
fail<Any>()
} catch (expected: IllegalStateException) {
} }
} }
@ -3028,10 +3020,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length}
// The URL was evicted before hasNext() made any promises. // The URL was evicted before hasNext() made any promises.
assertThat(i.hasNext()).isFalse() assertThat(i.hasNext()).isFalse()
try { assertFailsWith<NoSuchElementException> {
i.next() i.next()
fail<Any>()
} catch (expected: NoSuchElementException) {
} }
} }

View File

@ -43,7 +43,8 @@ import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.extension.RegisterExtension 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 import org.junitpioneer.jupiter.RetryingTest
@Timeout(30) @Timeout(30)
@ -160,11 +161,8 @@ class CallKotlinTest {
.header("Content-Type", "application/xml") .header("Content-Type", "application/xml")
.put(ErringRequestBody()) .put(ErringRequestBody())
.build() .build()
try { assertFailsWith<IOException> {
client.newCall(request).execute() client.newCall(request).execute()
fail("test should always throw exception")
} catch (_: IOException) {
// NOTE: expected
} }
request = Request.Builder() request = Request.Builder()
@ -229,10 +227,9 @@ class CallKotlinTest {
.build() .build()
val request = Request(server.url("/")) val request = Request(server.url("/"))
try { assertFailsWith<IOException> {
client.newCall(request).execute() client.newCall(request).execute()
fail("") }.also { expected ->
} catch (expected: IOException) {
expected.assertSuppressed { expected.assertSuppressed {
val suppressed = it.single() val suppressed = it.single()
assertThat(suppressed).isInstanceOf(IOException::class.java) assertThat(suppressed).isInstanceOf(IOException::class.java)
@ -251,10 +248,9 @@ class CallKotlinTest {
.build() .build()
val request = Request(server.url("/")) val request = Request(server.url("/"))
try { assertFailsWith<IOException> {
client.newCall(request).execute() client.newCall(request).execute()
fail("") }.also { expected ->
} catch (expected: IOException) {
expected.assertSuppressed { expected.assertSuppressed {
val suppressed = it.single() val suppressed = it.single()
assertThat(suppressed).isInstanceOf(IOException::class.java) assertThat(suppressed).isInstanceOf(IOException::class.java)

View File

@ -31,6 +31,7 @@ import assertk.assertions.isNotSameAs
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.assertions.startsWith import assertk.assertions.startsWith
import assertk.fail
import java.io.FileNotFoundException import java.io.FileNotFoundException
import java.io.IOException import java.io.IOException
import java.io.InterruptedIOException import java.io.InterruptedIOException
@ -60,6 +61,7 @@ import javax.net.ssl.SSLPeerUnverifiedException
import javax.net.ssl.SSLProtocolException import javax.net.ssl.SSLProtocolException
import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory import javax.net.ssl.SSLSocketFactory
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.QueueDispatcher import mockwebserver3.QueueDispatcher
@ -107,9 +109,9 @@ import okio.GzipSink
import okio.Path.Companion.toPath import okio.Path.Companion.toPath
import okio.buffer import okio.buffer
import okio.fakefilesystem.FakeFileSystem import okio.fakefilesystem.FakeFileSystem
import okio.use
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertArrayEquals 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.Assumptions.assumeFalse
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Disabled
@ -203,10 +205,9 @@ open class CallTest {
@Test @Test
fun invalidScheme() { fun invalidScheme() {
val requestBuilder = Request.Builder() val requestBuilder = Request.Builder()
try { assertFailsWith<IllegalArgumentException> {
requestBuilder.url("ftp://hostname/path") requestBuilder.url("ftp://hostname/path")
fail<Unit>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo("Expected URL scheme 'http' or 'https' but was 'ftp'") assertThat(expected.message).isEqualTo("Expected URL scheme 'http' or 'https' but was 'ftp'")
} }
} }
@ -214,10 +215,9 @@ open class CallTest {
@Test @Test
fun invalidPort() { fun invalidPort() {
val requestBuilder = Request.Builder() val requestBuilder = Request.Builder()
try { assertFailsWith<IllegalArgumentException> {
requestBuilder.url("http://localhost:65536/") requestBuilder.url("http://localhost:65536/")
fail<Unit>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo("Invalid URL port: \"65536\"") assertThat(expected.message).isEqualTo("Invalid URL port: \"65536\"")
} }
} }
@ -268,10 +268,8 @@ open class CallTest {
@Test @Test
fun getWithRequestBody() { fun getWithRequestBody() {
server.enqueue(MockResponse()) server.enqueue(MockResponse())
try { assertFailsWith<IllegalArgumentException> {
Request.Builder().method("GET", "abc".toRequestBody("text/plain".toMediaType())) Request.Builder().method("GET", "abc".toRequestBody("text/plain".toMediaType()))
fail<Unit>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -499,10 +497,9 @@ open class CallTest {
client = client.newBuilder() client = client.newBuilder()
.authenticator(RecordingOkAuthenticator(credential, null)) .authenticator(RecordingOkAuthenticator(credential, null))
.build() .build()
try { assertFailsWith<IOException> {
client.newCall(Request.Builder().url(server.url("/0")).build()).execute() client.newCall(Request.Builder().url(server.url("/0")).build()).execute()
fail<Unit>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("Too many follow-up requests: 21") assertThat(expected.message).isEqualTo("Too many follow-up requests: 21")
} }
} }
@ -680,17 +677,15 @@ open class CallTest {
val call = client.newCall(request) val call = client.newCall(request)
val response = call.execute() val response = call.execute()
response.body.close() response.body.close()
try { assertFailsWith<IllegalStateException> {
call.execute() call.execute()
fail<Unit>() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected.message).isEqualTo("Already Executed")
assertThat(e.message).isEqualTo("Already Executed")
} }
try { assertFailsWith<IllegalStateException> {
call.enqueue(callback) call.enqueue(callback)
fail<Unit>() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected.message).isEqualTo("Already Executed")
assertThat(e.message).isEqualTo("Already Executed")
} }
assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest") assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest")
} }
@ -709,17 +704,15 @@ open class CallTest {
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
call.enqueue(callback) call.enqueue(callback)
try { assertFailsWith<IllegalStateException> {
call.execute() call.execute()
fail<Unit>() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected.message).isEqualTo("Already Executed")
assertThat(e.message).isEqualTo("Already Executed")
} }
try { assertFailsWith<IllegalStateException> {
call.enqueue(callback) call.enqueue(callback)
fail<Unit>() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected.message).isEqualTo("Already Executed")
assertThat(e.message).isEqualTo("Already Executed")
} }
assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest") assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest")
callback.await(request.url).assertSuccessful() callback.await(request.url).assertSuccessful()
@ -782,7 +775,7 @@ open class CallTest {
val request = Request(server.url("/secret")) val request = Request(server.url("/secret"))
client.newCall(request).enqueue(object : Callback { client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) { override fun onFailure(call: Call, e: IOException) {
fail<Unit>() fail("")
} }
override fun onResponse(call: Call, response: Response) { 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. // The second byte of this request will be delayed by 750ms so we should time out after 250ms.
val startNanos = System.nanoTime() val startNanos = System.nanoTime()
try { bodySource.use {
assertFailsWith<IOException> {
bodySource.readByte() bodySource.readByte()
fail<Unit>() }.also { expected ->
} catch (expected: IOException) {
// Timed out as expected. // Timed out as expected.
val elapsedNanos = System.nanoTime() - startNanos val elapsedNanos = System.nanoTime() - startNanos
val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos) val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos)
assertThat(elapsedMillis).isLessThan(500) assertThat(elapsedMillis).isLessThan(500)
} finally { }
bodySource.close()
} }
} }
@ -947,11 +939,9 @@ open class CallTest {
.readTimeout(Duration.ofMillis(100)) .readTimeout(Duration.ofMillis(100))
.build() .build()
val request = Request.Builder().url(server.url("/")).build() val request = Request.Builder().url(server.url("/")).build()
try { assertFailsWith<InterruptedIOException> {
// If this succeeds, too many requests were made. // If this succeeds, too many requests were made.
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>()
} catch (expected: InterruptedIOException) {
} }
} }
@ -1007,10 +997,9 @@ open class CallTest {
val response = chain.proceed( val response = chain.proceed(
chain.request() chain.request()
) )
try { assertFailsWith<IllegalStateException> {
chain.proceed(chain.request()) chain.proceed(chain.request())
fail<Unit>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message!!).contains("please call response.close()") assertThat(expected.message!!).contains("please call response.close()")
} }
response response
@ -1281,10 +1270,8 @@ open class CallTest {
.hostnameVerifier(RecordingHostnameVerifier()) .hostnameVerifier(RecordingHostnameVerifier())
.build() .build()
val request = Request.Builder().url(server.url("/")).build() val request = Request.Builder().url(server.url("/")).build()
try { assertFailsWith<SSLHandshakeException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>()
} catch (expected: SSLHandshakeException) {
} }
val firstSocket = clientSocketFactory.socketsCreated[0] val firstSocket = clientSocketFactory.socketsCreated[0]
assertThat(firstSocket.enabledCipherSuites) assertThat(firstSocket.enabledCipherSuites)
@ -1331,18 +1318,24 @@ open class CallTest {
server.useHttps(handshakeCertificates.sslSocketFactory()) server.useHttps(handshakeCertificates.sslSocketFactory())
server.enqueue(MockResponse(socketPolicy = FailHandshake)) server.enqueue(MockResponse(socketPolicy = FailHandshake))
val request = Request.Builder().url(server.url("/")).build() val request = Request.Builder().url(server.url("/")).build()
try { assertFailsWith<IOException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>() }.also { expected ->
} catch (expected: SSLProtocolException) { when (expected) {
is SSLProtocolException -> {
// RI response to the FAIL_HANDSHAKE // RI response to the FAIL_HANDSHAKE
} catch (expected: SSLHandshakeException) { }
is SSLHandshakeException -> {
// Android's response to the FAIL_HANDSHAKE // Android's response to the FAIL_HANDSHAKE
} catch (expected: SSLException) { }
is SSLException -> {
// JDK 11 response to the FAIL_HANDSHAKE // JDK 11 response to the FAIL_HANDSHAKE
val jvmVersion = System.getProperty("java.specification.version") val jvmVersion = System.getProperty("java.specification.version")
assertThat(jvmVersion).isEqualTo("11") assertThat(jvmVersion).isEqualTo("11")
} }
else -> throw expected
}
}
} }
@Test @Test
@ -1416,10 +1409,9 @@ open class CallTest {
.build() .build()
server.enqueue(MockResponse()) server.enqueue(MockResponse())
val request = Request.Builder().url(server.url("/")).build() val request = Request.Builder().url(server.url("/")).build()
try { assertFailsWith<UnknownServiceException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>() }.also { expected ->
} catch (expected: UnknownServiceException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"CLEARTEXT communication not enabled for client" "CLEARTEXT communication not enabled for client"
) )
@ -1434,10 +1426,9 @@ open class CallTest {
server.useHttps(handshakeCertificates.sslSocketFactory()) server.useHttps(handshakeCertificates.sslSocketFactory())
server.enqueue(MockResponse()) server.enqueue(MockResponse())
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(server.url("/")))
try { assertFailsWith<UnknownServiceException> {
call.execute() call.execute()
fail<Unit>() }.also { expected ->
} catch (expected: UnknownServiceException) {
assertThat(expected.message).isEqualTo("H2_PRIOR_KNOWLEDGE cannot be used with HTTPS") 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. // When we pin the wrong certificate, connectivity fails.
val request = Request.Builder().url(server.url("/")).build() val request = Request.Builder().url(server.url("/")).build()
try { assertFailsWith<SSLPeerUnverifiedException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>() }.also { expected ->
} catch (expected: SSLPeerUnverifiedException) {
assertThat(expected.message!!).startsWith("Certificate pinning failure!") assertThat(expected.message!!).startsWith("Certificate pinning failure!")
} }
} }
@ -1552,12 +1542,10 @@ open class CallTest {
url = server.url("/"), url = server.url("/"),
body = "body!".toRequestBody("text/plain".toMediaType()), body = "body!".toRequestBody("text/plain".toMediaType()),
) )
try { assertFailsWith<IOException> {
client.newCall(request2).execute() client.newCall(request2).execute()
fail() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message!!).startsWith("unexpected end of stream on http://")
assertThat(e.message!!).startsWith("unexpected end of stream on http://")
// expected
} }
assertThat(listener.recordedEventTypes()).containsExactly( assertThat(listener.recordedEventTypes()).containsExactly(
@ -2401,10 +2389,9 @@ open class CallTest {
) )
) )
} }
try { assertFailsWith<IOException> {
client.newCall(Request.Builder().url(server.url("/0")).build()).execute() client.newCall(Request.Builder().url(server.url("/0")).build()).execute()
fail<Unit>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("Too many follow-up requests: 21") assertThat(expected.message).isEqualTo("Too many follow-up requests: 21")
} }
} }
@ -2473,10 +2460,8 @@ open class CallTest {
fun canceledBeforeExecute() { fun canceledBeforeExecute() {
val call = client.newCall(Request.Builder().url(server.url("/a")).build()) val call = client.newCall(Request.Builder().url(server.url("/a")).build())
call.cancel() call.cancel()
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Unit>()
} catch (expected: IOException) {
} }
assertThat(server.requestCount).isEqualTo(0) assertThat(server.requestCount).isEqualTo(0)
} }
@ -2500,10 +2485,8 @@ open class CallTest {
val call = client.newCall(Request(server.url("/").newBuilder().scheme(scheme!!).build())) val call = client.newCall(Request(server.url("/").newBuilder().scheme(scheme!!).build()))
cancelLater(call, cancelDelayMillis) cancelLater(call, cancelDelayMillis)
val startNanos = System.nanoTime() val startNanos = System.nanoTime()
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Unit>()
} catch (expected: IOException) {
} }
val elapsedNanos = System.nanoTime() - startNanos val elapsedNanos = System.nanoTime() - startNanos
assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedNanos).toFloat()) assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedNanos).toFloat())
@ -2554,10 +2537,8 @@ open class CallTest {
} }
client = client.newBuilder().eventListener(listener).build() client = client.newBuilder().eventListener(listener).build()
val call = client.newCall(Request(server.url("/a"))) val call = client.newCall(Request(server.url("/a")))
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Unit>()
} catch (expected: IOException) {
} }
} }
@ -2578,10 +2559,8 @@ open class CallTest {
val result = executor.submit<Response?> { call.execute() } val result = executor.submit<Response?> { call.execute() }
Thread.sleep(100) // wait for it to go in flight. Thread.sleep(100) // wait for it to go in flight.
call.cancel() call.cancel()
try { assertFailsWith<IOException> {
result.get()!!.body.bytes() result.get()!!.body.bytes()
fail<Unit>()
} catch (expected: IOException) {
} }
assertThat(server.requestCount).isEqualTo(1) assertThat(server.requestCount).isEqualTo(1)
} }
@ -2596,10 +2575,8 @@ open class CallTest {
return MockResponse(body = "A") return MockResponse(body = "A")
} }
} }
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Unit>()
} catch (expected: IOException) {
} }
assertThat(server.takeRequest().path).isEqualTo("/a") assertThat(server.takeRequest().path).isEqualTo("/a")
} }
@ -2746,10 +2723,8 @@ open class CallTest {
.build() .build()
val call = client.newCall(Request(server.url("/a"))) val call = client.newCall(Request(server.url("/a")))
call.cancel() call.cancel()
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Unit>()
} catch (expected: IOException) {
} }
assertThat(server.requestCount).isEqualTo(0) assertThat(server.requestCount).isEqualTo(0)
} }
@ -2938,10 +2913,8 @@ open class CallTest {
.post("abc".toRequestBody("text/plain".toMediaType())) .post("abc".toRequestBody("text/plain".toMediaType()))
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<SocketTimeoutException> {
call.execute() call.execute()
fail<Unit>()
} catch (expected: SocketTimeoutException) {
} }
val recordedRequest = server.takeRequest() val recordedRequest = server.takeRequest()
assertThat(recordedRequest.body.readUtf8()).isEqualTo("") assertThat(recordedRequest.body.readUtf8()).isEqualTo("")
@ -3045,10 +3018,8 @@ open class CallTest {
body = "abc".toRequestBody("text/plain".toMediaType()), body = "abc".toRequestBody("text/plain".toMediaType()),
) )
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<SocketTimeoutException> {
call.execute() call.execute()
fail<Unit>()
} catch (expected: SocketTimeoutException) {
} }
val recordedRequest = server.takeRequest() val recordedRequest = server.takeRequest()
assertThat(recordedRequest.body.readUtf8()).isEqualTo("abc") assertThat(recordedRequest.body.readUtf8()).isEqualTo("abc")
@ -3265,10 +3236,9 @@ open class CallTest {
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build() .build()
val request = Request("https://android.com/foo".toHttpUrl()) val request = Request("https://android.com/foo".toHttpUrl())
try { assertFailsWith<IOException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected).hasMessage("unexpected end of stream") assertThat(expected).hasMessage("unexpected end of stream")
} }
} }
@ -3409,10 +3379,8 @@ open class CallTest {
.hostnameVerifier(RecordingHostnameVerifier()) .hostnameVerifier(RecordingHostnameVerifier())
.build() .build()
val request = Request("https://android.com/foo".toHttpUrl()) val request = Request("https://android.com/foo".toHttpUrl())
try { assertFailsWith<ProtocolException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>()
} catch (expected: ProtocolException) {
} }
} }
@ -3543,10 +3511,8 @@ open class CallTest {
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.build() .build()
val request = Request(server.url("/")) val request = Request(server.url("/"))
try { assertFailsWith<IOException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Unit>()
} catch (expected: IOException) {
} }
} }
@ -3613,20 +3579,18 @@ open class CallTest {
@Test @Test
fun requestHeaderNameWithSpaceForbidden() { fun requestHeaderNameWithSpaceForbidden() {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder().addHeader("a b", "c") Request.Builder().addHeader("a b", "c")
fail<Unit>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo("Unexpected char 0x20 at 1 in header name: a b") assertThat(expected.message).isEqualTo("Unexpected char 0x20 at 1 in header name: a b")
} }
} }
@Test @Test
fun requestHeaderNameWithTabForbidden() { fun requestHeaderNameWithTabForbidden() {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder().addHeader("a\tb", "c") Request.Builder().addHeader("a\tb", "c")
fail<Unit>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo("Unexpected char 0x09 at 1 in header name: a\tb") 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) val latch = CountDownLatch(1)
client.newCall(request).enqueue(object : Callback { client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) { override fun onFailure(call: Call, e: IOException) {
fail<Unit>() fail("")
} }
override fun onResponse(call: Call, response: Response) { 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.body.string()).isEqualTo("this is the redirect target")
assertThat(response.priorResponse?.body?.contentType()) assertThat(response.priorResponse?.body?.contentType())
.isEqualTo("text/plain; charset=UTF-8".toMediaType()) .isEqualTo("text/plain; charset=UTF-8".toMediaType())
try { assertFailsWith<IllegalStateException> {
response.priorResponse?.body?.string() response.priorResponse?.body?.string()
fail<Unit>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message!!).contains("Unreadable ResponseBody!") assertThat(expected.message!!).contains("Unreadable ResponseBody!")
} }
} }
@ -4270,10 +4233,9 @@ open class CallTest {
body = requestBody, body = requestBody,
) )
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Unit>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("write body fail!") assertThat(expected.message).isEqualTo("write body fail!")
} }
} }

View File

@ -19,10 +19,10 @@ import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import java.security.cert.Certificate import java.security.cert.Certificate
import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLPeerUnverifiedException
import kotlin.test.assertFailsWith
import okhttp3.internal.tls.CertificateChainCleaner.Companion.get import okhttp3.internal.tls.CertificateChainCleaner.Companion.get
import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.HeldCertificate import okhttp3.tls.HeldCertificate
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
class CertificateChainCleanerTest { class CertificateChainCleanerTest {
@ -60,10 +60,8 @@ class CertificateChainCleanerTest {
.serialNumber(1L) .serialNumber(1L)
.build() .build()
val cleaner = get() val cleaner = get()
try { assertFailsWith<SSLPeerUnverifiedException> {
cleaner.clean(list(root), "hostname") cleaner.clean(list(root), "hostname")
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
} }
@ -276,10 +274,8 @@ class CertificateChainCleanerTest {
} }
val root = heldCertificates[heldCertificates.size - 1].certificate val root = heldCertificates[heldCertificates.size - 1].certificate
val cleaner = get(root) val cleaner = get(root)
try { assertFailsWith<SSLPeerUnverifiedException> {
cleaner.clean(certificates, "hostname") cleaner.clean(certificates, "hostname")
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
} }

View File

@ -18,35 +18,32 @@ package okhttp3
import assertk.assertThat import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo import assertk.assertions.isNotEqualTo
import assertk.fail
import java.util.Arrays import java.util.Arrays
import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLPeerUnverifiedException
import kotlin.test.assertFailsWith
import okhttp3.CertificatePinner.Companion.pin import okhttp3.CertificatePinner.Companion.pin
import okhttp3.CertificatePinner.Companion.sha1Hash import okhttp3.CertificatePinner.Companion.sha1Hash
import okhttp3.tls.HeldCertificate import okhttp3.tls.HeldCertificate
import okio.ByteString.Companion.decodeBase64 import okio.ByteString.Companion.decodeBase64
import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
class CertificatePinnerTest { class CertificatePinnerTest {
@Test @Test
fun malformedPin() { fun malformedPin() {
val builder = CertificatePinner.Builder() val builder = CertificatePinner.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.add("example.com", "md5/DmxUShsZuNiqPQsX2Oi9uv2sCnw=") builder.add("example.com", "md5/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test @Test
fun malformedBase64() { fun malformedBase64() {
val builder = CertificatePinner.Builder() val builder = CertificatePinner.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.add("example.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw*") builder.add("example.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw*")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -100,10 +97,8 @@ class CertificatePinnerTest {
val certificatePinner = CertificatePinner.Builder() val certificatePinner = CertificatePinner.Builder()
.add("example.com", certA1Sha256Pin) .add("example.com", certA1Sha256Pin)
.build() .build()
try { assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("example.com", certB1.certificate) certificatePinner.check("example.com", certB1.certificate)
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
} }
@ -156,10 +151,8 @@ class CertificatePinnerTest {
val certificatePinner = CertificatePinner.Builder() val certificatePinner = CertificatePinner.Builder()
.add("*.example.com", certA1Sha256Pin) .add("*.example.com", certA1Sha256Pin)
.build() .build()
try { assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("a.example.com", listOf(certB1.certificate)) certificatePinner.check("a.example.com", listOf(certB1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
} }
@ -188,10 +181,8 @@ class CertificatePinnerTest {
.add("*.example.com", certA1Sha256Pin) .add("*.example.com", certA1Sha256Pin)
.add("a.example.com", certB1Sha256Pin) .add("a.example.com", certB1Sha256Pin)
.build() .build()
try { assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("a.example.com", listOf(certC1.certificate)) certificatePinner.check("a.example.com", listOf(certC1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
} }
@ -202,25 +193,17 @@ class CertificatePinnerTest {
.build() .build()
// Should be pinned: // Should be pinned:
try { assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("example.co.uk", listOf(certB1.certificate)) certificatePinner.check("example.co.uk", listOf(certB1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
try { assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("foo.example.co.uk", listOf(certB1.certificate)) certificatePinner.check("foo.example.co.uk", listOf(certB1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
try { assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("foo.bar.example.co.uk", listOf(certB1.certificate)) certificatePinner.check("foo.bar.example.co.uk", listOf(certB1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
try { assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("foo.bar.baz.example.co.uk", listOf(certB1.certificate)) certificatePinner.check("foo.bar.baz.example.co.uk", listOf(certB1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
// Should not be pinned: // Should not be pinned:
@ -232,40 +215,31 @@ class CertificatePinnerTest {
@Test @Test
fun testBadPin() { fun testBadPin() {
try { assertFailsWith<IllegalArgumentException> {
CertificatePinner.Pin( CertificatePinner.Pin(
"example.co.uk", "example.co.uk",
"sha256/a" "sha256/a"
) )
fail<Any>()
} catch (iae: IllegalArgumentException) {
// expected
} }
} }
@Test @Test
fun testBadAlgorithm() { fun testBadAlgorithm() {
try { assertFailsWith<IllegalArgumentException> {
CertificatePinner.Pin( CertificatePinner.Pin(
"example.co.uk", "example.co.uk",
"sha512/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" "sha512/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
) )
fail<Any>()
} catch (iae: IllegalArgumentException) {
// expected
} }
} }
@Test @Test
fun testBadHost() { fun testBadHost() {
try { assertFailsWith<IllegalArgumentException> {
CertificatePinner.Pin( CertificatePinner.Pin(
"example.*", "example.*",
"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
) )
fail<Any>()
} catch (iae: IllegalArgumentException) {
// expected
} }
} }

View File

@ -36,7 +36,8 @@ import okhttp3.CertificatePinner.Companion.pin
import okhttp3.testing.PlatformRule import okhttp3.testing.PlatformRule
import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.HeldCertificate 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.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -238,7 +239,7 @@ class ConnectionCoalescingTest {
} }
override fun onFailure(call: Call, e: IOException) { override fun onFailure(call: Call, e: IOException) {
fail<Any?>() fail("")
} }
}) })
val client2 = client.newBuilder() val client2 = client.newBuilder()
@ -255,10 +256,8 @@ class ConnectionCoalescingTest {
server.enqueue(MockResponse()) server.enqueue(MockResponse())
assert200Http2Response(execute(url), server.hostName) assert200Http2Response(execute(url), server.hostName)
val differentDnsUrl = url.newBuilder().host("differentdns.com").build() val differentDnsUrl = url.newBuilder().host("differentdns.com").build()
try { assertFailsWith<IOException> {
execute(differentDnsUrl) execute(differentDnsUrl)
fail<Any?>("expected a failed attempt to connect")
} catch (expected: IOException) {
} }
} }
@ -275,11 +274,9 @@ class ConnectionCoalescingTest {
.body("unexpected call") .body("unexpected call")
.build() .build()
) )
try { assertFailsWith<IOException> {
val response = execute(url) val response = execute(url)
response.close() response.close()
fail<Any?>("expected a failed attempt to connect")
} catch (expected: IOException) {
} }
} }
@ -290,10 +287,8 @@ class ConnectionCoalescingTest {
server.enqueue(MockResponse()) server.enqueue(MockResponse())
assert200Http2Response(execute(url), server.hostName) assert200Http2Response(execute(url), server.hostName)
val nonsanUrl = url.newBuilder().host("nonsan.com").build() val nonsanUrl = url.newBuilder().host("nonsan.com").build()
try { assertFailsWith<SSLPeerUnverifiedException> {
execute(nonsanUrl) execute(nonsanUrl)
fail<Any?>("expected a failed attempt to connect")
} catch (expected: SSLPeerUnverifiedException) {
} }
} }
@ -306,11 +301,9 @@ class ConnectionCoalescingTest {
.build() .build()
) )
server.enqueue(MockResponse()) server.enqueue(MockResponse())
try { assertFailsWith<SSLPeerUnverifiedException> {
val response = execute(url) val response = execute(url)
response.close() response.close()
fail<Any?>("expected a failed attempt to connect")
} catch (expected: SSLPeerUnverifiedException) {
} }
} }
@ -339,10 +332,8 @@ class ConnectionCoalescingTest {
server.enqueue(MockResponse()) server.enqueue(MockResponse())
assert200Http2Response(execute(url), server.hostName) assert200Http2Response(execute(url), server.hostName)
val sanUrl = url.newBuilder().host("san.com").build() val sanUrl = url.newBuilder().host("san.com").build()
try { assertFailsWith<IOException> {
execute(sanUrl) execute(sanUrl)
fail<Any?>("expected a failed attempt to connect")
} catch (expected: IOException) {
} }
} }
@ -359,10 +350,8 @@ class ConnectionCoalescingTest {
.build() .build()
) )
server.enqueue(MockResponse()) server.enqueue(MockResponse())
try { assertFailsWith<SSLPeerUnverifiedException> {
execute(url) execute(url)
fail<Any?>("expected a failed attempt to connect")
} catch (expected: SSLPeerUnverifiedException) {
} }
} }

View File

@ -20,12 +20,14 @@ import assertk.assertions.containsExactly
import assertk.assertions.hasMessage import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isIn import assertk.assertions.isIn
import assertk.fail
import java.io.IOException import java.io.IOException
import java.net.InetSocketAddress import java.net.InetSocketAddress
import java.net.UnknownHostException import java.net.UnknownHostException
import java.time.Duration import java.time.Duration
import java.util.Arrays import java.util.Arrays
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy.FailHandshake import mockwebserver3.SocketPolicy.FailHandshake
@ -103,10 +105,9 @@ open class ConnectionListenerTest {
val call = client.newCall(Request.Builder() val call = client.newCall(Request.Builder()
.url(server!!.url("/")) .url(server!!.url("/"))
.build()) .build())
try { assertFailsWith<IOException> {
call.execute() call.execute()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isIn("timeout", "Read timed out") assertThat(expected.message).isIn("timeout", "Read timed out")
} }
assertThat(listener.recordedEventTypes()).containsExactly( assertThat(listener.recordedEventTypes()).containsExactly(
@ -219,10 +220,8 @@ open class ConnectionListenerTest {
val call = client.newCall(Request.Builder() val call = client.newCall(Request.Builder()
.url(server!!.url("/")) .url(server!!.url("/"))
.build()) .build())
try { assertFailsWith<IOException> {
call.execute() call.execute()
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (expected: IOException) {
} }
val address = client.dns.lookup(server!!.hostName)[0] val address = client.dns.lookup(server!!.hostName)[0]
val expectedAddress = InetSocketAddress(address, server!!.port) val expectedAddress = InetSocketAddress(address, server!!.port)

View File

@ -17,8 +17,12 @@ package okhttp3
import assertk.assertThat import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isIn
import java.io.IOException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLException import javax.net.ssl.SSLException
import kotlin.math.exp
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy.DisconnectAfterRequest import mockwebserver3.SocketPolicy.DisconnectAfterRequest
@ -31,7 +35,6 @@ import okhttp3.internal.closeQuietly
import okhttp3.testing.PlatformRule import okhttp3.testing.PlatformRule
import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HandshakeCertificates
import org.bouncycastle.tls.TlsFatalAlert import org.bouncycastle.tls.TlsFatalAlert
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -241,11 +244,13 @@ class ConnectionReuseTest {
.build() .build()
// This client fails to connect because the new SSL socket factory refuses. // This client fails to connect because the new SSL socket factory refuses.
try { assertFailsWith<IOException> {
anotherClient.newCall(request).execute() anotherClient.newCall(request).execute()
fail<Any?>() }.also { expected ->
} catch (expected: SSLException) { when (expected) {
} catch (expected: TlsFatalAlert) { is SSLException, is TlsFatalAlert -> {}
else -> throw expected
}
} }
} }

View File

@ -26,11 +26,11 @@ import assertk.assertions.isTrue
import java.util.concurrent.CopyOnWriteArraySet import java.util.concurrent.CopyOnWriteArraySet
import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory import javax.net.ssl.SSLSocketFactory
import kotlin.test.assertFailsWith
import okhttp3.internal.applyConnectionSpec import okhttp3.internal.applyConnectionSpec
import okhttp3.internal.platform.Platform.Companion.isAndroid import okhttp3.internal.platform.Platform.Companion.isAndroid
import okhttp3.testing.PlatformRule import okhttp3.testing.PlatformRule
import okhttp3.testing.PlatformVersion.majorVersion import okhttp3.testing.PlatformVersion.majorVersion
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
@ -40,12 +40,11 @@ class ConnectionSpecTest {
@Test @Test
fun noTlsVersions() { fun noTlsVersions() {
try { assertFailsWith<IllegalArgumentException> {
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(*arrayOf<String>()) .tlsVersions(*arrayOf<String>())
.build() .build()
fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("At least one TLS version is required") .isEqualTo("At least one TLS version is required")
} }
@ -53,12 +52,11 @@ class ConnectionSpecTest {
@Test @Test
fun noCipherSuites() { fun noCipherSuites() {
try { assertFailsWith<IllegalArgumentException> {
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.cipherSuites(*arrayOf<CipherSuite>()) .cipherSuites(*arrayOf<CipherSuite>())
.build() .build()
fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("At least one cipher suite is required") .isEqualTo("At least one cipher suite is required")
} }

View File

@ -32,7 +32,8 @@ import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.internal.UTC import okhttp3.internal.UTC
import okhttp3.internal.http.MAX_DATE import okhttp3.internal.http.MAX_DATE
import okhttp3.internal.parseCookie 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.Test
import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.ParameterizedTest
@ -446,18 +447,14 @@ class CookieTest {
} }
@Test fun builderNameValidation() { @Test fun builderNameValidation() {
try { assertFailsWith<IllegalArgumentException> {
Cookie.Builder().name(" a ") Cookie.Builder().name(" a ")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun builderValueValidation() { @Test fun builderValueValidation() {
try { assertFailsWith<IllegalArgumentException> {
Cookie.Builder().value(" b ") Cookie.Builder().value(" b ")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -492,10 +489,8 @@ class CookieTest {
} }
@Test fun builderDomainValidation() { @Test fun builderDomainValidation() {
try { assertFailsWith<IllegalArgumentException> {
Cookie.Builder().hostOnlyDomain("a/b") Cookie.Builder().hostOnlyDomain("a/b")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -520,10 +515,8 @@ class CookieTest {
} }
@Test fun builderPathValidation() { @Test fun builderPathValidation() {
try { assertFailsWith<IllegalArgumentException> {
Cookie.Builder().path("foo") Cookie.Builder().path("foo")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }

View File

@ -23,6 +23,7 @@ import assertk.assertions.isFalse
import assertk.assertions.isGreaterThan import assertk.assertions.isGreaterThan
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.fail
import java.net.CookieHandler import java.net.CookieHandler
import java.net.CookieManager import java.net.CookieManager
import java.net.CookiePolicy import java.net.CookiePolicy
@ -35,7 +36,6 @@ import mockwebserver3.MockWebServer
import okhttp3.Cookie.Companion.parse import okhttp3.Cookie.Companion.parse
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.java.net.cookiejar.JavaNetCookieJar import okhttp3.java.net.cookiejar.JavaNetCookieJar
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
@ -252,7 +252,7 @@ class CookiesTest {
assertThat(request.headers["Cookie"]).isEqualTo("c=cookie") assertThat(request.headers["Cookie"]).isEqualTo("c=cookie")
for (header in redirectTarget.takeRequest().headers.names()) { for (header in redirectTarget.takeRequest().headers.names()) {
if (header.startsWith("Cookie")) { if (header.startsWith("Cookie")) {
fail<Any>(header) fail(header)
} }
} }
} }

View File

@ -13,7 +13,8 @@ import java.net.UnknownHostException
import java.util.concurrent.CountDownLatch import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean 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.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -44,19 +45,15 @@ class DispatcherTest {
@Test @Test
fun maxRequestsZero() { fun maxRequestsZero() {
try { assertFailsWith<IllegalArgumentException> {
dispatcher.maxRequests = 0 dispatcher.maxRequests = 0
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test @Test
fun maxPerHostZero() { fun maxPerHostZero() {
try { assertFailsWith<IllegalArgumentException> {
dispatcher.maxRequestsPerHost = 0 dispatcher.maxRequestsPerHost = 0
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }

View File

@ -42,7 +42,8 @@ import okhttp3.testing.PlatformRule
import okio.BufferedSink import okio.BufferedSink
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertTrue 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.BeforeEach
import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
@ -87,10 +88,8 @@ class DuplexTest {
.post(AsyncRequestBody()) .post(AsyncRequestBody())
.build() .build()
) )
try { assertFailsWith<ProtocolException> {
call.execute() call.execute()
fail<Any?>()
} catch (expected: ProtocolException) {
} }
} }
@ -369,11 +368,10 @@ class DuplexTest {
.isEqualTo("this is /b") .isEqualTo("this is /b")
} }
val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink() val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink()
try { assertFailsWith<IOException> {
requestBody.writeUtf8("request body\n") requestBody.writeUtf8("request body\n")
requestBody.flush() requestBody.flush()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("stream was reset: CANCEL") .isEqualTo("stream was reset: CANCEL")
} }
@ -431,11 +429,10 @@ class DuplexTest {
// First duplex request is detached with violence. // First duplex request is detached with violence.
val requestBody1 = (call.request().body as AsyncRequestBody?)!!.takeSink() val requestBody1 = (call.request().body as AsyncRequestBody?)!!.takeSink()
try { assertFailsWith<IOException> {
requestBody1.writeUtf8("not authenticated\n") requestBody1.writeUtf8("not authenticated\n")
requestBody1.flush() requestBody1.flush()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("stream was reset: CANCEL") .isEqualTo("stream was reset: CANCEL")
} }
@ -469,11 +466,10 @@ class DuplexTest {
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS) call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
assertTrue(call.isCanceled()) assertTrue(call.isCanceled())
} }
} }
@ -631,11 +627,10 @@ class DuplexTest {
.readTimeout(1000, TimeUnit.MILLISECONDS) .readTimeout(1000, TimeUnit.MILLISECONDS)
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
} }
} }
@ -658,11 +653,10 @@ class DuplexTest {
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
val response = call.execute() val response = call.execute()
try { assertFailsWith<IOException> {
response.body.string() response.body.string()
fail<Any?>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
} }
} }

View File

@ -78,7 +78,8 @@ import org.hamcrest.Matcher
import org.hamcrest.MatcherAssert import org.hamcrest.MatcherAssert
import org.junit.Assume import org.junit.Assume
import org.junit.jupiter.api.AfterEach 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.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -221,10 +222,9 @@ class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isIn("timeout", "Read timed out") assertThat(expected.message).isIn("timeout", "Read timed out")
} }
assertThat(listener.recordedEventTypes()).containsExactly( assertThat(listener.recordedEventTypes()).containsExactly(
@ -254,10 +254,9 @@ class EventListenerTest {
.build() .build()
) )
val response = call.execute() val response = call.execute()
try { assertFailsWith<IOException> {
response.body.string() response.body.string()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("unexpected end of stream") assertThat(expected.message).isEqualTo("unexpected end of stream")
} }
assertThat(listener.recordedEventTypes()).containsExactly( assertThat(listener.recordedEventTypes()).containsExactly(
@ -279,10 +278,9 @@ class EventListenerTest {
.build() .build()
) )
call.cancel() call.cancel()
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("Canceled") assertThat(expected.message).isEqualTo("Canceled")
} }
assertThat(listener.recordedEventTypes()).containsExactly( assertThat(listener.recordedEventTypes()).containsExactly(
@ -618,10 +616,8 @@ class EventListenerTest {
.url("http://fakeurl/") .url("http://fakeurl/")
.build() .build()
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>()
} catch (expected: IOException) {
} }
listener.removeUpToEvent<DnsStart>() listener.removeUpToEvent<DnsStart>()
val callFailed: CallFailed = listener.removeUpToEvent<CallFailed>() val callFailed: CallFailed = listener.removeUpToEvent<CallFailed>()
@ -640,10 +636,8 @@ class EventListenerTest {
.url("http://fakeurl/") .url("http://fakeurl/")
.build() .build()
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>()
} catch (expected: IOException) {
} }
listener.removeUpToEvent<DnsStart>() listener.removeUpToEvent<DnsStart>()
val callFailed: CallFailed = listener.removeUpToEvent<CallFailed>() val callFailed: CallFailed = listener.removeUpToEvent<CallFailed>()
@ -689,10 +683,8 @@ class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>()
} catch (expected: IOException) {
} }
val address = client.dns.lookup(server.hostName)[0] val address = client.dns.lookup(server.hostName)[0]
val expectedAddress = InetSocketAddress(address, server.port) val expectedAddress = InetSocketAddress(address, server.port)
@ -860,10 +852,8 @@ class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>()
} catch (expected: IOException) {
} }
val secureStart = listener.removeUpToEvent<SecureConnectStart>() val secureStart = listener.removeUpToEvent<SecureConnectStart>()
assertThat(secureStart.call).isSameAs(call) assertThat(secureStart.call).isSameAs(call)
@ -1093,10 +1083,8 @@ class EventListenerTest {
Assume.assumeThat(response, matchesProtocol(Protocol.HTTP_2)) Assume.assumeThat(response, matchesProtocol(Protocol.HTTP_2))
} }
assertThat(response.protocol).isEqualTo(expectedProtocol) assertThat(response.protocol).isEqualTo(expectedProtocol)
try { assertFailsWith<IOException> {
response.body.string() response.body.string()
fail<Any?>()
} catch (expected: IOException) {
} }
val callFailed = listener.removeUpToEvent<CallFailed>() val callFailed = listener.removeUpToEvent<CallFailed>()
assertThat(callFailed.ioe).isNotNull() assertThat(callFailed.ioe).isNotNull()
@ -1209,10 +1197,8 @@ class EventListenerTest {
.post(request) .post(request)
.build() .build()
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>()
} catch (expected: IOException) {
} }
if (expectedProtocol != null) { if (expectedProtocol != null) {
val connectionAcquired = listener.removeUpToEvent<ConnectionAcquired>() val connectionAcquired = listener.removeUpToEvent<ConnectionAcquired>()
@ -1285,10 +1271,8 @@ class EventListenerTest {
.post(requestBody) .post(requestBody)
.build() .build()
) )
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>()
} catch (expected: IOException) {
} }
assertThat(listener.recordedEventTypes()).containsExactly( assertThat(listener.recordedEventTypes()).containsExactly(
"CallStart", "CallStart",

View File

@ -19,6 +19,7 @@ import assertk.assertThat
import assertk.assertions.hasMessage import assertk.assertions.hasMessage
import assertk.assertions.hasSize import assertk.assertions.hasSize
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.fail
import java.io.IOException import java.io.IOException
import java.net.Inet4Address import java.net.Inet4Address
import java.net.Inet6Address import java.net.Inet6Address
@ -28,7 +29,6 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.net.SocketFactory import javax.net.SocketFactory
import kotlin.test.assertFailsWith import kotlin.test.assertFailsWith
import kotlin.test.fail
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy.ResetStreamAtStart import mockwebserver3.SocketPolicy.ResetStreamAtStart
@ -241,11 +241,10 @@ class FastFallbackTest {
.callTimeout(1_000, TimeUnit.MILLISECONDS) .callTimeout(1_000, TimeUnit.MILLISECONDS)
.build() .build()
val call = client.newCall(Request(url)) val call = client.newCall(Request(url))
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail("expected a timeout") }.also { expected ->
} catch (e: IOException) { assertThat(expected).hasMessage("timeout")
assertThat(e).hasMessage("timeout")
} }
} }

View File

@ -25,7 +25,8 @@ import java.io.IOException
import java.security.cert.Certificate import java.security.cert.Certificate
import okhttp3.Handshake.Companion.handshake import okhttp3.Handshake.Companion.handshake
import okhttp3.tls.HeldCertificate import okhttp3.tls.HeldCertificate
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.Test
class HandshakeTest { class HandshakeTest {
@ -89,10 +90,9 @@ class HandshakeTest {
null null
) )
try { assertFailsWith<IOException> {
sslSession.handshake() sslSession.handshake()
fail() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected).hasMessage("cipherSuite == SSL_NULL_WITH_NULL_NULL") assertThat(expected).hasMessage("cipherSuite == SSL_NULL_WITH_NULL_NULL")
} }
} }
@ -106,10 +106,9 @@ class HandshakeTest {
null null
) )
try { assertFailsWith<IOException> {
sslSession.handshake() sslSession.handshake()
fail() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected).hasMessage("cipherSuite == TLS_NULL_WITH_NULL_NULL") assertThat(expected).hasMessage("cipherSuite == TLS_NULL_WITH_NULL_NULL")
} }
} }

View File

@ -20,6 +20,7 @@ import assertk.assertions.containsExactly
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import java.time.Instant import java.time.Instant
import java.util.Date import java.util.Date
import kotlin.test.assertFailsWith
import kotlin.test.fail import kotlin.test.fail
import okhttp3.Headers.Companion.toHeaders import okhttp3.Headers.Companion.toHeaders
import okhttp3.internal.EMPTY_HEADERS import okhttp3.internal.EMPTY_HEADERS
@ -98,41 +99,32 @@ class HeadersJvmTest {
} }
@Test fun addThrowsOnEmptyName() { @Test fun addThrowsOnEmptyName() {
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add(": bar") Headers.Builder().add(": bar")
fail()
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add(" : bar") Headers.Builder().add(" : bar")
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun addThrowsOnNoColon() { @Test fun addThrowsOnNoColon() {
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("foo bar") Headers.Builder().add("foo bar")
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun addThrowsOnMultiColon() { @Test fun addThrowsOnMultiColon() {
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add(":status: 200 OK") Headers.Builder().add(":status: 200 OK")
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun addUnsafeNonAsciiRejectsUnicodeName() { @Test fun addUnsafeNonAsciiRejectsUnicodeName() {
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder() Headers.Builder()
.addUnsafeNonAscii("héader1", "value1") .addUnsafeNonAscii("héader1", "value1")
.build() .build()
fail("Should have complained about invalid value") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") 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 // Fails on JS, ClassCastException: Illegal cast
@Test fun ofMapThrowsOnNull() { @Test fun ofMapThrowsOnNull() {
try { assertFailsWith<NullPointerException> {
(mapOf("User-Agent" to null) as Map<String, String>).toHeaders() (mapOf("User-Agent" to null) as Map<String, String>).toHeaders()
fail()
} catch (expected: NullPointerException) {
} }
} }

View File

@ -19,6 +19,7 @@ import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo import assertk.assertions.isNotEqualTo
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertFailsWith
import kotlin.test.fail import kotlin.test.fail
import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.headersOf
import okhttp3.Headers.Companion.toHeaders import okhttp3.Headers.Companion.toHeaders
@ -31,18 +32,14 @@ class HeadersTest {
} }
@Test fun ofThrowsOddNumberOfHeaders() { @Test fun ofThrowsOddNumberOfHeaders() {
try { assertFailsWith<IllegalArgumentException> {
headersOf("User-Agent", "OkHttp", "Content-Length") headersOf("User-Agent", "OkHttp", "Content-Length")
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun ofThrowsOnEmptyName() { @Test fun ofThrowsOnEmptyName() {
try { assertFailsWith<IllegalArgumentException> {
headersOf("", "OkHttp") headersOf("", "OkHttp")
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -62,26 +59,20 @@ class HeadersTest {
} }
@Test fun ofRejectsNullChar() { @Test fun ofRejectsNullChar() {
try { assertFailsWith<IllegalArgumentException> {
headersOf("User-Agent", "Square\u0000OkHttp") headersOf("User-Agent", "Square\u0000OkHttp")
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun ofMapThrowsOnEmptyName() { @Test fun ofMapThrowsOnEmptyName() {
try { assertFailsWith<IllegalArgumentException> {
mapOf("" to "OkHttp").toHeaders() mapOf("" to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun ofMapThrowsOnBlankName() { @Test fun ofMapThrowsOnBlankName() {
try { assertFailsWith<IllegalArgumentException> {
mapOf(" " to "OkHttp").toHeaders() mapOf(" " to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -109,107 +100,93 @@ class HeadersTest {
} }
@Test fun ofMapRejectsNullCharInName() { @Test fun ofMapRejectsNullCharInName() {
try { assertFailsWith<IllegalArgumentException> {
mapOf("User-\u0000Agent" to "OkHttp").toHeaders() mapOf("User-\u0000Agent" to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun ofMapRejectsNullCharInValue() { @Test fun ofMapRejectsNullCharInValue() {
try { assertFailsWith<IllegalArgumentException> {
mapOf("User-Agent" to "Square\u0000OkHttp").toHeaders() mapOf("User-Agent" to "Square\u0000OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test fun builderRejectsUnicodeInHeaderName() { @Test fun builderRejectsUnicodeInHeaderName() {
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("héader1", "value1") Headers.Builder().add("héader1", "value1")
fail("Should have complained about invalid name") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") .isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
} }
} }
@Test fun builderRejectsUnicodeInHeaderValue() { @Test fun builderRejectsUnicodeInHeaderValue() {
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("header1", "valué1") Headers.Builder().add("header1", "valué1")
fail("Should have complained about invalid value") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1") .isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
} }
} }
@Test fun varargFactoryRejectsUnicodeInHeaderName() { @Test fun varargFactoryRejectsUnicodeInHeaderName() {
try { assertFailsWith<IllegalArgumentException> {
headersOf("héader1", "value1") headersOf("héader1", "value1")
fail("Should have complained about invalid value") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") .isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
} }
} }
@Test fun varargFactoryRejectsUnicodeInHeaderValue() { @Test fun varargFactoryRejectsUnicodeInHeaderValue() {
try { assertFailsWith<IllegalArgumentException> {
headersOf("header1", "valué1") headersOf("header1", "valué1")
fail("Should have complained about invalid value") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1") .isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
} }
} }
@Test fun mapFactoryRejectsUnicodeInHeaderName() { @Test fun mapFactoryRejectsUnicodeInHeaderName() {
try { assertFailsWith<IllegalArgumentException> {
mapOf("héader1" to "value1").toHeaders() mapOf("héader1" to "value1").toHeaders()
fail("Should have complained about invalid value") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1") .isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
} }
} }
@Test fun mapFactoryRejectsUnicodeInHeaderValue() { @Test fun mapFactoryRejectsUnicodeInHeaderValue() {
try { assertFailsWith<IllegalArgumentException> {
mapOf("header1" to "valué1").toHeaders() mapOf("header1" to "valué1").toHeaders()
fail("Should have complained about invalid value") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1") .isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
} }
} }
@Test fun sensitiveHeadersNotIncludedInExceptions() { @Test fun sensitiveHeadersNotIncludedInExceptions() {
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Authorization", "valué1") Headers.Builder().add("Authorization", "valué1")
fail("Should have complained about invalid name") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Authorization value") .isEqualTo("Unexpected char 0xe9 at 4 in Authorization value")
} }
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Cookie", "valué1") Headers.Builder().add("Cookie", "valué1")
fail("Should have complained about invalid name") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Cookie value") .isEqualTo("Unexpected char 0xe9 at 4 in Cookie value")
} }
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Proxy-Authorization", "valué1") Headers.Builder().add("Proxy-Authorization", "valué1")
fail("Should have complained about invalid name") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Proxy-Authorization value") .isEqualTo("Unexpected char 0xe9 at 4 in Proxy-Authorization value")
} }
try { assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Set-Cookie", "valué1") Headers.Builder().add("Set-Cookie", "valué1")
fail("Should have complained about invalid name") }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Set-Cookie value") .isEqualTo("Unexpected char 0xe9 at 4 in Set-Cookie value")
} }
@ -286,33 +263,25 @@ class HeadersTest {
@Test fun nameIndexesAreStrict() { @Test fun nameIndexesAreStrict() {
val headers = headersOf("a", "b", "c", "d") val headers = headersOf("a", "b", "c", "d")
try { assertFailsWith<IndexOutOfBoundsException> {
headers.name(-1) headers.name(-1)
fail()
} catch (expected: IndexOutOfBoundsException) {
} }
assertThat(headers.name(0)).isEqualTo("a") assertThat(headers.name(0)).isEqualTo("a")
assertThat(headers.name(1)).isEqualTo("c") assertThat(headers.name(1)).isEqualTo("c")
try { assertFailsWith<IndexOutOfBoundsException> {
headers.name(2) headers.name(2)
fail()
} catch (expected: IndexOutOfBoundsException) {
} }
} }
@Test fun valueIndexesAreStrict() { @Test fun valueIndexesAreStrict() {
val headers = headersOf("a", "b", "c", "d") val headers = headersOf("a", "b", "c", "d")
try { assertFailsWith<IndexOutOfBoundsException> {
headers.value(-1) headers.value(-1)
fail()
} catch (expected: IndexOutOfBoundsException) {
} }
assertThat(headers.value(0)).isEqualTo("b") assertThat(headers.value(0)).isEqualTo("b")
assertThat(headers.value(1)).isEqualTo("d") assertThat(headers.value(1)).isEqualTo("d")
try { assertFailsWith<IndexOutOfBoundsException> {
headers.value(2) headers.value(2)
fail()
} catch (expected: IndexOutOfBoundsException) {
} }
} }
} }

View File

@ -21,6 +21,7 @@ import assertk.assertions.isEqualTo
import assertk.assertions.isNotNull import assertk.assertions.isNotNull
import assertk.assertions.isNull import assertk.assertions.isNull
import javax.net.ssl.SSLException import javax.net.ssl.SSLException
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import okhttp3.testing.PlatformRule import okhttp3.testing.PlatformRule
@ -29,7 +30,6 @@ import okhttp3.tls.HeldCertificate
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail
class InsecureForHostTest { class InsecureForHostTest {
@RegisterExtension @JvmField val platform = PlatformRule() @RegisterExtension @JvmField val platform = PlatformRule()
@ -90,10 +90,8 @@ class InsecureForHostTest {
.build() .build()
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(server.url("/")))
try { assertFailsWith<SSLException> {
call.execute() call.execute()
fail("")
} catch (expected: SSLException) {
} }
} }
@ -112,10 +110,8 @@ class InsecureForHostTest {
.build() .build()
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(server.url("/")))
try { assertFailsWith<SSLException> {
call.execute() call.execute()
fail("")
} catch (expected: SSLException) {
} }
} }
} }

View File

@ -48,7 +48,8 @@ import okio.GzipSink
import okio.Sink import okio.Sink
import okio.Source import okio.Source
import okio.buffer 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.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -109,10 +110,9 @@ class InterceptorTest {
val request = Request.Builder() val request = Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build() .build()
try { assertFailsWith<IllegalStateException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"network interceptor $interceptor must call proceed() exactly once" "network interceptor $interceptor must call proceed() exactly once"
) )
@ -133,10 +133,9 @@ class InterceptorTest {
val request = Request.Builder() val request = Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build() .build()
try { assertFailsWith<IllegalStateException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"network interceptor $interceptor must call proceed() exactly once" "network interceptor $interceptor must call proceed() exactly once"
) )
@ -166,10 +165,9 @@ class InterceptorTest {
val request = Request.Builder() val request = Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build() .build()
try { assertFailsWith<IllegalStateException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"network interceptor $interceptor must retain the same host and port" "network interceptor $interceptor must retain the same host and port"
) )
@ -491,10 +489,9 @@ class InterceptorTest {
val request = Request.Builder() val request = Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build() .build()
try { assertFailsWith<RuntimeException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Any>() }.also { expected ->
} catch (expected: RuntimeException) {
assertThat(expected.message).isEqualTo("boom!") assertThat(expected.message).isEqualTo("boom!")
} }
} }
@ -605,10 +602,8 @@ class InterceptorTest {
.build() .build()
val call = client.newCall(request1) val call = client.newCall(request1)
val startNanos = System.nanoTime() val startNanos = System.nanoTime()
try { assertFailsWith<SocketTimeoutException> {
call.execute() call.execute()
fail<Any>()
} catch (expected: SocketTimeoutException) {
} }
val elapsedNanos = System.nanoTime() - startNanos val elapsedNanos = System.nanoTime() - startNanos
org.junit.jupiter.api.Assertions.assertTrue( org.junit.jupiter.api.Assertions.assertTrue(
@ -646,10 +641,8 @@ class InterceptorTest {
val call = client.newCall(request1) val call = client.newCall(request1)
val response = call.execute() val response = call.execute()
val body = response.body val body = response.body
try { assertFailsWith<SocketTimeoutException> {
body.string() body.string()
fail<Any>()
} catch (expected: SocketTimeoutException) {
} }
} }
@ -663,10 +656,9 @@ class InterceptorTest {
} }
val request1 = Request.Builder().url(server.url("/")).build() val request1 = Request.Builder().url(server.url("/")).build()
val call = client.newCall(request1) val call = client.newCall(request1)
try { assertFailsWith<IllegalStateException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Timeouts can't be adjusted in a network interceptor") .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 request1 = Request.Builder().url(server.url("/")).build()
val call = client.newCall(request1) val call = client.newCall(request1)
try { assertFailsWith<IllegalStateException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Timeouts can't be adjusted in a network interceptor") .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 request1 = Request.Builder().url(server.url("/")).build()
val call = client.newCall(request1) val call = client.newCall(request1)
try { assertFailsWith<IllegalStateException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("Timeouts can't be adjusted in a network interceptor") .isEqualTo("Timeouts can't be adjusted in a network interceptor")
} }
@ -739,10 +729,8 @@ class InterceptorTest {
.post(data.toRequestBody("text/plain".toMediaType())) .post(data.toRequestBody("text/plain".toMediaType()))
.build() .build()
val call = client.newCall(request1) val call = client.newCall(request1)
try { assertFailsWith<SocketTimeoutException> {
call.execute() // we want this call to throw a SocketTimeoutException call.execute() // we want this call to throw a SocketTimeoutException
fail<Any>()
} catch (expected: SocketTimeoutException) {
} }
} }
@ -764,10 +752,8 @@ class InterceptorTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>()
} catch (expected: IOException) {
} }
assertThat(callRef.get()).isSameAs(call) assertThat(callRef.get()).isSameAs(call)
} }

View File

@ -19,6 +19,7 @@ import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import java.io.IOException import java.io.IOException
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
import kotlin.test.assertFailsWith
import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.headersOf
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MediaType.Companion.toMediaTypeOrNull
@ -26,17 +27,15 @@ import okhttp3.RequestBody.Companion.toRequestBody
import okio.Buffer import okio.Buffer
import okio.BufferedSink import okio.BufferedSink
import okio.utf8Size import okio.utf8Size
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
class MultipartBodyTest { class MultipartBodyTest {
@Test @Test
fun onePartRequired() { fun onePartRequired() {
try { assertFailsWith<IllegalStateException> {
MultipartBody.Builder().build() MultipartBody.Builder().build()
fail<Any>() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Multipart body must have at least one part.") .isEqualTo("Multipart body must have at least one part.")
} }
} }
@ -241,26 +240,22 @@ class MultipartBodyTest {
@Test @Test
fun contentTypeHeaderIsForbidden() { fun contentTypeHeaderIsForbidden() {
val multipart = MultipartBody.Builder() val multipart = MultipartBody.Builder()
try { assertFailsWith<IllegalArgumentException> {
multipart.addPart( multipart.addPart(
headersOf("Content-Type", "text/plain"), headersOf("Content-Type", "text/plain"),
"Hello, World!".toRequestBody(null) "Hello, World!".toRequestBody(null)
) )
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test @Test
fun contentLengthHeaderIsForbidden() { fun contentLengthHeaderIsForbidden() {
val multipart = MultipartBody.Builder() val multipart = MultipartBody.Builder()
try { assertFailsWith<IllegalArgumentException> {
multipart.addPart( multipart.addPart(
headersOf("Content-Length", "13"), headersOf("Content-Length", "13"),
"Hello, World!".toRequestBody(null) "Hello, World!".toRequestBody(null)
) )
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }

View File

@ -27,7 +27,8 @@ import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer 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.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -116,16 +117,12 @@ class MultipartReaderTest {
) )
val part = parts.nextPart()!! val part = parts.nextPart()!!
try { assertFailsWith<EOFException> {
assertThat(part.body.readUtf8()).isEqualTo("abcd\r\nefgh\r\n") assertThat(part.body.readUtf8()).isEqualTo("abcd\r\nefgh\r\n")
fail()
} catch (expected: EOFException) {
} }
try { assertFailsWith<EOFException> {
assertThat(parts.nextPart()).isNull() assertThat(parts.nextPart()).isNull()
fail()
} catch (expected: EOFException) {
} }
} }
@ -141,10 +138,8 @@ class MultipartReaderTest {
source = Buffer().writeUtf8(multipart) source = Buffer().writeUtf8(multipart)
) )
try { assertFailsWith<EOFException> {
parts.nextPart() parts.nextPart()
fail()
} catch (expected: EOFException) {
} }
} }
@ -243,11 +238,10 @@ class MultipartReaderTest {
val partAbc = parts.nextPart()!! val partAbc = parts.nextPart()!!
val partMno = parts.nextPart()!! val partMno = parts.nextPart()!!
try { assertFailsWith<IllegalStateException> {
partAbc.body.request(20) partAbc.body.request(20)
fail() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected).hasMessage("closed")
assertThat(e).hasMessage("closed")
} }
assertThat(partMno.body.readUtf8()).isEqualTo("mnop") assertThat(partMno.body.readUtf8()).isEqualTo("mnop")
@ -271,11 +265,10 @@ class MultipartReaderTest {
val part = parts.nextPart()!! val part = parts.nextPart()!!
parts.close() parts.close()
try { assertFailsWith<IllegalStateException> {
part.body.request(10) part.body.request(10)
fail() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected).hasMessage("closed")
assertThat(e).hasMessage("closed")
} }
} }
@ -287,11 +280,10 @@ class MultipartReaderTest {
parts.close() parts.close()
try { assertFailsWith<IllegalStateException> {
parts.nextPart() parts.nextPart()
fail() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected).hasMessage("closed")
assertThat(e).hasMessage("closed")
} }
} }
@ -306,10 +298,9 @@ class MultipartReaderTest {
source = Buffer().writeUtf8(multipart) source = Buffer().writeUtf8(multipart)
) )
try { assertFailsWith<ProtocolException> {
parts.nextPart() parts.nextPart()
fail() }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("expected at least 1 part") assertThat(expected).hasMessage("expected at least 1 part")
} }
} }
@ -415,10 +406,9 @@ class MultipartReaderTest {
source = Buffer().writeUtf8(multipart) source = Buffer().writeUtf8(multipart)
) )
try { assertFailsWith<ProtocolException> {
parts.nextPart() parts.nextPart()
fail() }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("unexpected characters after boundary") assertThat(expected).hasMessage("unexpected characters after boundary")
} }
} }
@ -438,10 +428,9 @@ class MultipartReaderTest {
) )
parts.nextPart() parts.nextPart()
try { assertFailsWith<ProtocolException> {
parts.nextPart() parts.nextPart()
fail() }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("unexpected characters after boundary") assertThat(expected).hasMessage("unexpected characters after boundary")
} }
} }
@ -505,10 +494,8 @@ class MultipartReaderTest {
source = Buffer() source = Buffer()
) )
try { assertFailsWith<EOFException> {
parts.nextPart() parts.nextPart()
fail()
} catch (expected: EOFException) {
} }
} }

View File

@ -43,7 +43,8 @@ import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotSame import org.junit.jupiter.api.Assertions.assertNotSame
import org.junit.jupiter.api.Assertions.assertSame 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.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
@ -154,10 +155,8 @@ class OkHttpClientTest {
@Test fun setProtocolsRejectsHttp10() { @Test fun setProtocolsRejectsHttp10() {
val builder = OkHttpClient.Builder() val builder = OkHttpClient.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.protocols(listOf(Protocol.HTTP_1_0, Protocol.HTTP_1_1)) builder.protocols(listOf(Protocol.HTTP_1_0, Protocol.HTTP_1_1))
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -170,10 +169,9 @@ class OkHttpClientTest {
@Test fun nullInterceptorInList() { @Test fun nullInterceptorInList() {
val builder = OkHttpClient.Builder() val builder = OkHttpClient.Builder()
builder.interceptors().addAll(listOf(null) as List<Interceptor>) builder.interceptors().addAll(listOf(null) as List<Interceptor>)
try { assertFailsWith<IllegalStateException> {
builder.build() builder.build()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message).isEqualTo("Null interceptor: [null]") assertThat(expected.message).isEqualTo("Null interceptor: [null]")
} }
} }
@ -181,20 +179,18 @@ class OkHttpClientTest {
@Test fun nullNetworkInterceptorInList() { @Test fun nullNetworkInterceptorInList() {
val builder = OkHttpClient.Builder() val builder = OkHttpClient.Builder()
builder.networkInterceptors().addAll(listOf(null) as List<Interceptor>) builder.networkInterceptors().addAll(listOf(null) as List<Interceptor>)
try { assertFailsWith<IllegalStateException> {
builder.build() builder.build()
fail<Any>() }.also { expected ->
} catch (expected: IllegalStateException) {
assertThat(expected.message).isEqualTo("Null network interceptor: [null]") assertThat(expected.message).isEqualTo("Null network interceptor: [null]")
} }
} }
@Test fun testH2PriorKnowledgeOkHttpClientConstructionFallback() { @Test fun testH2PriorKnowledgeOkHttpClientConstructionFallback() {
try { assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder() OkHttpClient.Builder()
.protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)) .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1))
fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"protocols containing h2_prior_knowledge cannot use other protocols: " "protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, http/1.1]" + "[h2_prior_knowledge, http/1.1]"
@ -203,11 +199,10 @@ class OkHttpClientTest {
} }
@Test fun testH2PriorKnowledgeOkHttpClientConstructionDuplicates() { @Test fun testH2PriorKnowledgeOkHttpClientConstructionDuplicates() {
try { assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder() OkHttpClient.Builder()
.protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)) .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE))
fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"protocols containing h2_prior_knowledge cannot use other protocols: " "protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, h2_prior_knowledge]" + "[h2_prior_knowledge, h2_prior_knowledge]"
@ -234,10 +229,8 @@ class OkHttpClientTest {
@Test fun sslSocketFactorySetAsSocketFactory() { @Test fun sslSocketFactorySetAsSocketFactory() {
val builder = OkHttpClient.Builder() val builder = OkHttpClient.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.socketFactory(SSLSocketFactory.getDefault()) builder.socketFactory(SSLSocketFactory.getDefault())
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -245,10 +238,8 @@ class OkHttpClientTest {
val client = OkHttpClient.Builder() val client = OkHttpClient.Builder()
.connectionSpecs(listOf(ConnectionSpec.CLEARTEXT)) .connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))
.build() .build()
try { assertFailsWith<IllegalStateException> {
client.sslSocketFactory client.sslSocketFactory
fail<Any>()
} catch (expected: IllegalStateException) {
} }
} }
@ -281,11 +272,10 @@ class OkHttpClientTest {
Protocol.HTTP_1_1, Protocol.HTTP_1_1,
null null
) )
try { assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder() OkHttpClient.Builder()
.protocols(protocols as List<Protocol>) .protocols(protocols as List<Protocol>)
fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo("protocols must not contain null") assertThat(expected.message).isEqualTo("protocols must not contain null")
} }
} }
@ -420,10 +410,9 @@ class OkHttpClientTest {
@Test fun minWebSocketMessageToCompressNegative() { @Test fun minWebSocketMessageToCompressNegative() {
val builder = OkHttpClient.Builder() val builder = OkHttpClient.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.minWebSocketMessageToCompress(-1024) builder.minWebSocketMessageToCompress(-1024)
fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message) assertThat(expected.message)
.isEqualTo("minWebSocketMessageToCompress must be positive: -1024") .isEqualTo("minWebSocketMessageToCompress must be positive: -1024")
} }

View File

@ -22,8 +22,8 @@ import assertk.assertions.isEqualTo
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.assertions.isSameAs import assertk.assertions.isSameAs
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.fail
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertFailsWith
import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.headersOf
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
@ -146,15 +146,11 @@ class RequestCommonTest {
@Test @Test
fun emptyNameForbidden() { fun emptyNameForbidden() {
val builder = Request.Builder() val builder = Request.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.header("", "Value") builder.header("", "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.addHeader("", "Value") builder.addHeader("", "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
} }
@ -162,10 +158,8 @@ class RequestCommonTest {
fun headerAllowsTabOnlyInValues() { fun headerAllowsTabOnlyInValues() {
val builder = Request.Builder() val builder = Request.Builder()
builder.header("key", "sample\tvalue") builder.header("key", "sample\tvalue")
try { assertFailsWith<IllegalArgumentException> {
builder.header("sample\tkey", "value") builder.header("sample\tkey", "value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
} }
@ -182,25 +176,17 @@ class RequestCommonTest {
private fun assertForbiddenHeader(s: String) { private fun assertForbiddenHeader(s: String) {
val builder = Request.Builder() val builder = Request.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.header(s, "Value") builder.header(s, "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.addHeader(s, "Value") builder.addHeader(s, "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.header("Name", s) builder.header("Name", s)
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.addHeader("Name", s) builder.addHeader("Name", s)
fail("")
} catch (expected: IllegalArgumentException) {
} }
} }

View File

@ -26,7 +26,7 @@ import java.io.File
import java.io.FileWriter import java.io.FileWriter
import java.net.URI import java.net.URI
import java.util.UUID import java.util.UUID
import kotlin.test.fail import kotlin.test.assertFailsWith
import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.headersOf
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
@ -264,15 +264,11 @@ class RequestTest {
@Test @Test
fun emptyNameForbidden() { fun emptyNameForbidden() {
val builder = Request.Builder() val builder = Request.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.header("", "Value") builder.header("", "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.addHeader("", "Value") builder.addHeader("", "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
} }
@ -280,10 +276,8 @@ class RequestTest {
fun headerAllowsTabOnlyInValues() { fun headerAllowsTabOnlyInValues() {
val builder = Request.Builder() val builder = Request.Builder()
builder.header("key", "sample\tvalue") builder.header("key", "sample\tvalue")
try { assertFailsWith<IllegalArgumentException> {
builder.header("sample\tkey", "value") builder.header("sample\tkey", "value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
} }
@ -300,25 +294,17 @@ class RequestTest {
private fun assertForbiddenHeader(s: String) { private fun assertForbiddenHeader(s: String) {
val builder = Request.Builder() val builder = Request.Builder()
try { assertFailsWith<IllegalArgumentException> {
builder.header(s, "Value") builder.header(s, "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.addHeader(s, "Value") builder.addHeader(s, "Value")
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.header("Name", s) builder.header("Name", s)
fail("")
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
builder.addHeader("Name", s) builder.addHeader("Name", s)
fail("")
} catch (expected: IllegalArgumentException) {
} }
} }

View File

@ -18,11 +18,13 @@ package okhttp3
import assertk.assertThat import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.fail
import java.io.IOException import java.io.IOException
import java.io.InputStreamReader import java.io.InputStreamReader
import java.io.Reader import java.io.Reader
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertFailsWith
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.internal.and import okhttp3.internal.and
@ -300,11 +302,10 @@ class ResponseBodyJvmTest {
return Buffer().writeUtf8("hello") return Buffer().writeUtf8("hello")
} }
} }
try { assertFailsWith<IOException> {
body.bytes() body.bytes()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Content-Length (10) and stream length (5) disagree" "Content-Length (10) and stream length (5) disagree"
) )
} }
@ -325,11 +326,10 @@ class ResponseBodyJvmTest {
throw AssertionError() throw AssertionError()
} }
} }
try { assertFailsWith<IOException> {
body.bytes() body.bytes()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Cannot buffer entire body for content length: 2147483648" "Cannot buffer entire body for content length: 2147483648"
) )
} }
@ -391,11 +391,10 @@ class ResponseBodyJvmTest {
return Buffer().writeUtf8("hello") return Buffer().writeUtf8("hello")
} }
} }
try { assertFailsWith<IOException> {
body.byteString() body.byteString()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Content-Length (10) and stream length (5) disagree" "Content-Length (10) and stream length (5) disagree"
) )
} }
@ -416,11 +415,10 @@ class ResponseBodyJvmTest {
throw AssertionError() throw AssertionError()
} }
} }
try { assertFailsWith<IOException> {
body.byteString() body.byteString()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Cannot buffer entire body for content length: 2147483648" "Cannot buffer entire body for content length: 2147483648"
) )
} }

View File

@ -36,7 +36,8 @@ import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail import assertk.fail
import kotlin.test.assertFailsWith
@Timeout(30) @Timeout(30)
@Tag("Slowish") @Tag("Slowish")
@ -152,15 +153,11 @@ class ServerTruncatesRequestTest {
call.execute().use { response -> call.execute().use { response ->
assertThat(response.body.string()).isEqualTo("abc") assertThat(response.body.string()).isEqualTo("abc")
val requestBodyOut = requestBody.takeSink() val requestBodyOut = requestBody.takeSink()
try { assertFailsWith<IOException> {
SlowRequestBody.writeTo(requestBodyOut) SlowRequestBody.writeTo(requestBodyOut)
fail("")
} catch (expected: IOException) {
} }
try { assertFailsWith<IOException> {
requestBodyOut.close() requestBodyOut.close()
fail("")
} catch (expected: IOException) {
} }
} }
@ -266,10 +263,9 @@ class ServerTruncatesRequestTest {
) )
) )
try { assertFailsWith<IOException> {
callA.execute() callA.execute()
fail("") }.also { expected ->
} catch (expected: IOException) {
assertThat(expected).hasMessage("boom") assertThat(expected).hasMessage("boom")
} }

View File

@ -28,6 +28,7 @@ import assertk.assertions.isLessThan
import assertk.assertions.isNotEmpty import assertk.assertions.isNotEmpty
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.fail
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
import java.io.InputStream import java.io.InputStream
@ -64,6 +65,7 @@ import javax.net.ssl.SSLProtocolException
import javax.net.ssl.TrustManager import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager import javax.net.ssl.X509TrustManager
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy import mockwebserver3.SocketPolicy
@ -97,7 +99,6 @@ import okio.buffer
import okio.utf8Size import okio.utf8Size
import org.bouncycastle.tls.TlsFatalAlert import org.bouncycastle.tls.TlsFatalAlert
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
@ -209,10 +210,8 @@ class URLConnectionTest {
.status("HTP/1.1 200 OK") .status("HTP/1.1 200 OK")
.build()) .build())
val request = newRequest("/") val request = newRequest("/")
try { assertFailsWith<IOException> {
getResponse(request) getResponse(request)
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -222,10 +221,8 @@ class URLConnectionTest {
.status("HTTP/1.1 2147483648 OK") .status("HTTP/1.1 2147483648 OK")
.build()) .build())
val request = newRequest("/") val request = newRequest("/")
try { assertFailsWith<IOException> {
getResponse(request) getResponse(request)
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -235,10 +232,8 @@ class URLConnectionTest {
.status("HTTP/1.1 00a OK") .status("HTTP/1.1 00a OK")
.build()) .build())
val request = newRequest("/") val request = newRequest("/")
try { assertFailsWith<IOException> {
getResponse(request) getResponse(request)
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -248,10 +243,8 @@ class URLConnectionTest {
.status(" HTTP/1.1 2147483648 OK") .status(" HTTP/1.1 2147483648 OK")
.build()) .build())
val request = newRequest("/") val request = newRequest("/")
try { assertFailsWith<IOException> {
getResponse(request) getResponse(request)
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -259,10 +252,8 @@ class URLConnectionTest {
fun connectRetriesUntilConnectedOrFailed() { fun connectRetriesUntilConnectedOrFailed() {
val request = newRequest("/foo") val request = newRequest("/foo")
server.shutdown() server.shutdown()
try { assertFailsWith<IOException> {
getResponse(request) getResponse(request)
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -369,14 +360,12 @@ class URLConnectionTest {
client = client.newBuilder() client = client.newBuilder()
.dns(FakeDns()) .dns(FakeDns())
.build() .build()
try { assertFailsWith<UnknownHostException> {
getResponse( getResponse(
Request.Builder() Request.Builder()
.url("http://1234.1.1.1/index.html".toHttpUrl()) .url("http://1234.1.1.1/index.html".toHttpUrl())
.build() .build()
) )
fail<Any>()
} catch (expected: UnknownHostException) {
} }
} }
@ -582,13 +571,13 @@ class URLConnectionTest {
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(sslSocketFactory2, trustManager) .sslSocketFactory(sslSocketFactory2, trustManager)
.build() .build()
try { assertFailsWith<IOException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>( }.also { expected ->
"without an SSL socket factory, the connection should fail" when (expected) {
) is SSLException, is TlsFatalAlert -> {}
} catch (expected: SSLException) { else -> throw expected
} catch (expected: TlsFatalAlert) { }
} }
} }
@ -632,10 +621,9 @@ class URLConnectionTest {
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager
) )
.build() .build()
try { assertFailsWith<IOException> {
getResponse(newRequest("/foo")) getResponse(newRequest("/foo"))
fail<Any>() }.also { expected ->
} catch (expected: IOException) {
expected.assertSuppressed { throwables: List<Throwable>? -> expected.assertSuppressed { throwables: List<Throwable>? ->
assertThat(throwables!!.size).isEqualTo(1) assertThat(throwables!!.size).isEqualTo(1)
} }
@ -690,15 +678,19 @@ class URLConnectionTest {
// Flaky https://github.com/square/okhttp/issues/5222 // Flaky https://github.com/square/okhttp/issues/5222
server.useHttps(handshakeCertificates.sslSocketFactory()) server.useHttps(handshakeCertificates.sslSocketFactory())
server.enqueue(MockResponse()) // unused server.enqueue(MockResponse()) // unused
try { assertFailsWith<IOException> {
getResponse(newRequest("/foo")) getResponse(newRequest("/foo"))
fail<Any>() }.also { expected ->
} catch (expected: SSLHandshakeException) { when (expected) {
is SSLHandshakeException -> {
// Allow conscrypt to fail in different ways // Allow conscrypt to fail in different ways
if (!platform.isConscrypt()) { if (!platform.isConscrypt()) {
assertThat(expected.cause!!).isInstanceOf<CertificateException>() assertThat(expected.cause!!).isInstanceOf<CertificateException>()
} }
} catch (expected: TlsFatalAlert) { }
is TlsFatalAlert -> {}
else -> throw expected
}
} }
assertThat(server.requestCount).isEqualTo(0) assertThat(server.requestCount).isEqualTo(0)
} }
@ -752,11 +744,9 @@ class URLConnectionTest {
.setHeader("Content-Length", "5") .setHeader("Content-Length", "5")
.socketPolicy(DisconnectAtEnd) .socketPolicy(DisconnectAtEnd)
.build()) .build())
try { assertFailsWith<ProtocolException> {
val response = getResponse(newRequest("/")) val response = getResponse(newRequest("/"))
response.body.source().readUtf8(5) response.body.source().readUtf8(5)
fail<Any>()
} catch (expected: ProtocolException) {
} }
} }
@ -797,10 +787,8 @@ class URLConnectionTest {
client = client.newBuilder() client = client.newBuilder()
.socketFactory(uselessSocketFactory) .socketFactory(uselessSocketFactory)
.build() .build()
try { assertFailsWith<IllegalArgumentException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
client = client.newBuilder() client = client.newBuilder()
.socketFactory(SocketFactory.getDefault()) .socketFactory(SocketFactory.getDefault())
@ -846,11 +834,9 @@ class URLConnectionTest {
builder.addHeader("Transfer-encoding: chunked") builder.addHeader("Transfer-encoding: chunked")
builder.socketPolicy(DisconnectAtEnd) builder.socketPolicy(DisconnectAtEnd)
server.enqueue(builder.build()) server.enqueue(builder.build())
try { assertFailsWith<IOException> {
val response = getResponse(newRequest("/")) val response = getResponse(newRequest("/"))
response.body.source().readUtf8(7) response.body.source().readUtf8(7)
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -1121,14 +1107,12 @@ class URLConnectionTest {
val inputStream = response.body.byteStream() val inputStream = response.body.byteStream()
assertThat(inputStream.read().toChar()).isEqualTo('A') assertThat(inputStream.read().toChar()).isEqualTo('A')
call.cancel() call.cancel()
try { assertFailsWith<IOException> {
// Reading 'B' may succeed if it's buffered. // Reading 'B' may succeed if it's buffered.
inputStream.read() inputStream.read()
// But 'C' shouldn't be buffered (the response is throttled) and this should fail. // But 'C' shouldn't be buffered (the response is throttled) and this should fail.
inputStream.read() inputStream.read()
fail<Any>("Expected a connection closed exception")
} catch (expected: IOException) {
} }
inputStream.close() inputStream.close()
} }
@ -1149,10 +1133,9 @@ class URLConnectionTest {
.build() .build()
val call = client.newCall(newRequest("/")) val call = client.newCall(newRequest("/"))
callReference.set(call) callReference.set(call)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>("Connection should not be established") }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("Canceled") assertThat(expected.message).isEqualTo("Canceled")
} }
} }
@ -1164,10 +1147,8 @@ class URLConnectionTest {
) )
val call = client.newCall(newRequest("/")) val call = client.newCall(newRequest("/"))
call.cancel() call.cancel()
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -1219,10 +1200,8 @@ class URLConnectionTest {
.isFalse() .isFalse()
inputStream.mark(5) inputStream.mark(5)
assertThat(readAscii(inputStream, 5)).isEqualTo("ABCDE") assertThat(readAscii(inputStream, 5)).isEqualTo("ABCDE")
try { assertFailsWith<IOException> {
inputStream.reset() inputStream.reset()
fail<Any>()
} catch (expected: IOException) {
} }
assertThat(readAscii(inputStream, Int.MAX_VALUE)).isEqualTo( assertThat(readAscii(inputStream, Int.MAX_VALUE)).isEqualTo(
"FGHIJKLMNOPQRSTUVWXYZ" "FGHIJKLMNOPQRSTUVWXYZ"
@ -1262,12 +1241,10 @@ class URLConnectionTest {
.addHeader("Transfer-encoding: chunked") .addHeader("Transfer-encoding: chunked")
.build() .build()
) )
try { assertFailsWith<IOException> {
getResponse(newRequest("/")).use { response -> getResponse(newRequest("/")).use { response ->
response.body.string() response.body.string()
fail<Any>()
} }
} catch (expected: IOException) {
} }
} }
@ -1280,12 +1257,10 @@ class URLConnectionTest {
.addHeader("Transfer-encoding: chunked") .addHeader("Transfer-encoding: chunked")
.build() .build()
) )
try { assertFailsWith<IOException> {
getResponse(newRequest("/")).use { response -> getResponse(newRequest("/")).use { response ->
readAscii(response.body.byteStream(), Int.MAX_VALUE) readAscii(response.body.byteStream(), Int.MAX_VALUE)
fail<Any>()
} }
} catch (expected: IOException) {
} }
} }
@ -1311,12 +1286,10 @@ class URLConnectionTest {
.socketPolicy(DisconnectAtEnd) .socketPolicy(DisconnectAtEnd)
.build() .build()
) )
try { assertFailsWith<IOException> {
getResponse(newRequest("/")).use { response -> getResponse(newRequest("/")).use { response ->
readAscii(response.body.byteStream(), Int.MAX_VALUE) readAscii(response.body.byteStream(), Int.MAX_VALUE)
fail<Any>()
} }
} catch (expected: IOException) {
} }
} }
@ -1777,13 +1750,11 @@ class URLConnectionTest {
} }
private fun assertMethodForbidsRequestBody(requestMethod: String) { private fun assertMethodForbidsRequestBody(requestMethod: String) {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.method(requestMethod, "abc".toRequestBody(null)) .method(requestMethod, "abc".toRequestBody(null))
.build() .build()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -1796,13 +1767,11 @@ class URLConnectionTest {
} }
private fun assertMethodForbidsNoRequestBody(requestMethod: String) { private fun assertMethodForbidsNoRequestBody(requestMethod: String) {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.method(requestMethod, null) .method(requestMethod, null)
.build() .build()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -2672,10 +2641,9 @@ class URLConnectionTest {
) )
) )
} }
try { assertFailsWith<ProtocolException> {
getResponse(newRequest("/0")) getResponse(newRequest("/0"))
fail<Any>() }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"Too many follow-up requests: 21" "Too many follow-up requests: 21"
) )
@ -2781,10 +2749,8 @@ class URLConnectionTest {
assertThat(source.readByte()).isEqualTo('A'.code.toByte()) assertThat(source.readByte()).isEqualTo('A'.code.toByte())
assertThat(source.readByte()).isEqualTo('B'.code.toByte()) assertThat(source.readByte()).isEqualTo('B'.code.toByte())
assertThat(source.readByte()).isEqualTo('C'.code.toByte()) assertThat(source.readByte()).isEqualTo('C'.code.toByte())
try { assertFailsWith<SocketTimeoutException> {
source.readByte() // If Content-Length was accurate, this would return -1 immediately. source.readByte() // If Content-Length was accurate, this would return -1 immediately.
fail<Any>()
} catch (expected: SocketTimeoutException) {
} }
source.close() source.close()
} }
@ -2831,10 +2797,8 @@ class URLConnectionTest {
} }
}, },
) )
try { assertFailsWith<SocketTimeoutException> {
getResponse(request) getResponse(request)
fail<Any>()
} catch (expected: SocketTimeoutException) {
} }
} }
@ -2938,10 +2902,9 @@ class URLConnectionTest {
body = "This body is not allowed!", body = "This body is not allowed!",
) )
) )
try { assertFailsWith<IOException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("HTTP 204 had non-zero Content-Length: 25") 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)) assertThat(readAscii(response.body.byteStream(), Int.MAX_VALUE))
.isEqualTo("abc") .isEqualTo("abc")
try { assertFailsWith<IllegalStateException> {
sinkReference.get().flush() sinkReference.get().flush()
fail<Any>()
} catch (expected: IllegalStateException) {
} }
try { assertFailsWith<IllegalStateException> {
sinkReference.get().write("ghi".toByteArray()) sinkReference.get().write("ghi".toByteArray())
sinkReference.get().emit() sinkReference.get().emit()
fail<Any>()
} catch (expected: IllegalStateException) {
} }
} }
@Test @Test
fun getHeadersThrows() { fun getHeadersThrows() {
server.enqueue(MockResponse(socketPolicy = SocketPolicy.DisconnectAtStart)) server.enqueue(MockResponse(socketPolicy = SocketPolicy.DisconnectAtStart))
try { assertFailsWith<IOException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -3029,19 +2986,15 @@ class URLConnectionTest {
client = client.newBuilder() client = client.newBuilder()
.dns(FakeDns()) .dns(FakeDns())
.build() .build()
try { assertFailsWith<IOException> {
getResponse(Request("http://host.unlikelytld".toHttpUrl())) getResponse(Request("http://host.unlikelytld".toHttpUrl()))
fail<Any>()
} catch (expected: IOException) {
} }
} }
@Test @Test
fun malformedUrlThrowsUnknownHostException() { fun malformedUrlThrowsUnknownHostException() {
try { assertFailsWith<IOException> {
getResponse(Request("http://-/foo.html".toHttpUrl())) getResponse(Request("http://-/foo.html".toHttpUrl()))
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -3056,10 +3009,8 @@ class URLConnectionTest {
source1.timeout().timeout(100, TimeUnit.MILLISECONDS) source1.timeout().timeout(100, TimeUnit.MILLISECONDS)
assertThat(readAscii(source1.inputStream(), Int.MAX_VALUE)).isEqualTo("ABC") assertThat(readAscii(source1.inputStream(), Int.MAX_VALUE)).isEqualTo("ABC")
server.shutdown() server.shutdown()
try { assertFailsWith<ConnectException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>()
} catch (expected: ConnectException) {
} }
} }
@ -3084,13 +3035,11 @@ class URLConnectionTest {
@Test @Test
fun getOutputStreamOnGetFails() { fun getOutputStreamOnGetFails() {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.method("GET", "abc".toRequestBody(null)) .method("GET", "abc".toRequestBody(null))
.build() .build()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -3163,13 +3112,11 @@ class URLConnectionTest {
@Test @Test
fun doOutputForMethodThatDoesntSupportOutput() { fun doOutputForMethodThatDoesntSupportOutput() {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.method("HEAD", "".toRequestBody(null)) .method("HEAD", "".toRequestBody(null))
.build() .build()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -3314,15 +3261,13 @@ class URLConnectionTest {
sink.writeUtf8("abc") sink.writeUtf8("abc")
} }
} }
try { assertFailsWith<IOException> {
getResponse( getResponse(
Request( Request(
url = server.url("/b"), url = server.url("/b"),
body = requestBody, body = requestBody,
) )
) )
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -3340,15 +3285,13 @@ class URLConnectionTest {
sink.writeUtf8("abcd") sink.writeUtf8("abcd")
} }
} }
try { assertFailsWith<IOException> {
getResponse( getResponse(
Request( Request(
url = server.url("/b"), url = server.url("/b"),
body = requestBody, body = requestBody,
) )
) )
fail<Any>()
} catch (expected: IOException) {
} }
} }
@ -3356,20 +3299,20 @@ class URLConnectionTest {
@Disabled @Disabled
fun testPooledConnectionsDetectHttp10() { fun testPooledConnectionsDetectHttp10() {
// TODO: write a test that shows pooled connections detect HTTP/1.0 (vs. HTTP/1.1) // TODO: write a test that shows pooled connections detect HTTP/1.0 (vs. HTTP/1.1)
fail<Any>("TODO") fail("TODO")
} }
@Test @Test
@Disabled @Disabled
fun postBodiesRetransmittedOnAuthProblems() { fun postBodiesRetransmittedOnAuthProblems() {
fail<Any>("TODO") fail("TODO")
} }
@Test @Test
@Disabled @Disabled
fun cookiesAndTrailers() { fun cookiesAndTrailers() {
// Do cookie headers get processed too many times? // Do cookie headers get processed too many times?
fail<Any>("TODO") fail("TODO")
} }
@Test @Test
@ -3402,13 +3345,11 @@ class URLConnectionTest {
@Test @Test
fun emptyRequestHeaderNameIsStrict() { fun emptyRequestHeaderNameIsStrict() {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.header("", "A") .header("", "A")
.build() .build()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -3430,35 +3371,25 @@ class URLConnectionTest {
@Test @Test
fun requestHeaderValidationIsStrict() { fun requestHeaderValidationIsStrict() {
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.addHeader("a\tb", "Value") .addHeader("a\tb", "Value")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.addHeader("Name", "c\u007fd") .addHeader("Name", "c\u007fd")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.addHeader("", "Value") .addHeader("", "Value")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.addHeader("\ud83c\udf69", "Value") .addHeader("\ud83c\udf69", "Value")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
try { assertFailsWith<IllegalArgumentException> {
Request.Builder() Request.Builder()
.addHeader("Name", "\u2615\ufe0f") .addHeader("Name", "\u2615\ufe0f")
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -3481,19 +3412,19 @@ class URLConnectionTest {
@Test @Test
@Disabled @Disabled
fun deflateCompression() { fun deflateCompression() {
fail<Any>("TODO") fail("TODO")
} }
@Test @Test
@Disabled @Disabled
fun postBodiesRetransmittedOnIpAddressProblems() { fun postBodiesRetransmittedOnIpAddressProblems() {
fail<Any>("TODO") fail("TODO")
} }
@Test @Test
@Disabled @Disabled
fun pooledConnectionProblemsNotReportedToProxySelector() { fun pooledConnectionProblemsNotReportedToProxySelector() {
fail<Any>("TODO") fail("TODO")
} }
@Test @Test
@ -3607,10 +3538,9 @@ class URLConnectionTest {
client = client.newBuilder() client = client.newBuilder()
.authenticator(RecordingOkAuthenticator(credential, null)) .authenticator(RecordingOkAuthenticator(credential, null))
.build() .build()
try { assertFailsWith<ProtocolException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>() }.also { expected ->
} catch (expected: ProtocolException) {
assertThat(expected.message).isEqualTo("Too many follow-up requests: 21") assertThat(expected.message).isEqualTo("Too many follow-up requests: 21")
} }
} }
@ -3708,21 +3638,17 @@ class URLConnectionTest {
@Test @Test
fun setProtocolsWithoutHttp11() { fun setProtocolsWithoutHttp11() {
try { assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder() OkHttpClient.Builder()
.protocols(Arrays.asList(Protocol.HTTP_2)) .protocols(Arrays.asList(Protocol.HTTP_2))
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test @Test
fun setProtocolsWithNull() { fun setProtocolsWithNull() {
try { assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder() OkHttpClient.Builder()
.protocols(Arrays.asList(Protocol.HTTP_1_1, null)) .protocols(Arrays.asList(Protocol.HTTP_1_1, null))
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -3770,19 +3696,26 @@ class URLConnectionTest {
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager
) )
.build() .build()
try { assertFailsWith<IOException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>() }.also { expected ->
} catch (expected: SSLProtocolException) { when (expected) {
is SSLProtocolException -> {
// RI response to the FAIL_HANDSHAKE // RI response to the FAIL_HANDSHAKE
} catch (expected: SSLHandshakeException) { }
is SSLHandshakeException -> {
// Android's response to the FAIL_HANDSHAKE // Android's response to the FAIL_HANDSHAKE
} catch (expected: SSLException) { }
is SSLException -> {
// JDK 1.9 response to the FAIL_HANDSHAKE // JDK 1.9 response to the FAIL_HANDSHAKE
// javax.net.ssl.SSLException: Unexpected handshake message: client_hello // javax.net.ssl.SSLException: Unexpected handshake message: client_hello
} catch (expected: SocketException) { }
is SocketException -> {
// Conscrypt's response to the FAIL_HANDSHAKE // Conscrypt's response to the FAIL_HANDSHAKE
} }
else -> throw expected
}
}
} }
/** /**
@ -3868,28 +3801,22 @@ class URLConnectionTest {
@Test @Test
fun urlWithSpaceInHost() { fun urlWithSpaceInHost() {
try { assertFailsWith<IllegalArgumentException> {
"http://and roid.com/".toHttpUrl() "http://and roid.com/".toHttpUrl()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test @Test
fun urlWithSpaceInHostViaHttpProxy() { fun urlWithSpaceInHostViaHttpProxy() {
try { assertFailsWith<IllegalArgumentException> {
"http://and roid.com/".toHttpUrl() "http://and roid.com/".toHttpUrl()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@Test @Test
fun urlHostWithNul() { fun urlHostWithNul() {
try { assertFailsWith<IllegalArgumentException> {
"http://host\u0000/".toHttpUrl() "http://host\u0000/".toHttpUrl()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -3909,10 +3836,8 @@ class URLConnectionTest {
@Test @Test
fun urlWithBadAsciiHost() { fun urlWithBadAsciiHost() {
try { assertFailsWith<IllegalArgumentException> {
"http://host\u0001/".toHttpUrl() "http://host\u0001/".toHttpUrl()
fail<Any>()
} catch (expected: IllegalArgumentException) {
} }
} }
@ -3920,11 +3845,9 @@ class URLConnectionTest {
@Test @Test
fun setSslSocketFactoryFailsOnJdk9() { fun setSslSocketFactoryFailsOnJdk9() {
platform.assumeJdk9() platform.assumeJdk9()
try { assertFailsWith<UnsupportedOperationException> {
client.newBuilder() client.newBuilder()
.sslSocketFactory(handshakeCertificates.sslSocketFactory()) .sslSocketFactory(handshakeCertificates.sslSocketFactory())
fail<Any>()
} catch (expected: UnsupportedOperationException) {
} }
} }
@ -3935,10 +3858,9 @@ class URLConnectionTest {
.dns { hostname: String? -> throw RuntimeException("boom!") } .dns { hostname: String? -> throw RuntimeException("boom!") }
.build() .build()
server.enqueue(MockResponse()) server.enqueue(MockResponse())
try { assertFailsWith<RuntimeException> {
getResponse(newRequest("/")) getResponse(newRequest("/"))
fail<Any>() }.also { expected ->
} catch (expected: RuntimeException) {
assertThat(expected.message).isEqualTo("boom!") assertThat(expected.message).isEqualTo("boom!")
} }
} }

View File

@ -17,6 +17,7 @@ package okhttp3
import assertk.assertThat import assertk.assertThat
import assertk.assertions.startsWith import assertk.assertions.startsWith
import kotlin.test.assertFailsWith
import kotlin.test.fail import kotlin.test.fail
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.internal.idn.Punycode import okhttp3.internal.idn.Punycode
@ -142,10 +143,8 @@ class UrlComponentEncodingTester private constructor() {
private fun testForbidden(codePoint: Int, codePointString: String, component: Component) { private fun testForbidden(codePoint: Int, codePointString: String, component: Component) {
val builder = "http://host/".toHttpUrl().newBuilder() val builder = "http://host/".toHttpUrl().newBuilder()
try { assertFailsWith<IllegalArgumentException> {
component[builder] = codePointString component[builder] = codePointString
fail("Accepted forbidden code point $component $codePoint")
} catch (expected: IllegalArgumentException) {
} }
} }

View File

@ -27,13 +27,13 @@ import java.time.Duration
import java.util.concurrent.CountDownLatch import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicReference
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.TestUtil.repeat import okhttp3.TestUtil.repeat
import okhttp3.testing.Flaky import okhttp3.testing.Flaky
import okio.BufferedSink import okio.BufferedSink
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -85,11 +85,10 @@ class WholeOperationTimeoutTest {
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS) call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue() assertThat(call.isCanceled()).isTrue()
} }
} }
@ -134,11 +133,10 @@ class WholeOperationTimeoutTest {
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS) call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue() assertThat(call.isCanceled()).isTrue()
} }
} }
@ -188,11 +186,10 @@ class WholeOperationTimeoutTest {
call.timeout().timeout(250, TimeUnit.MILLISECONDS) call.timeout().timeout(250, TimeUnit.MILLISECONDS)
val response = call.execute() val response = call.execute()
Thread.sleep(500) Thread.sleep(500)
try { assertFailsWith<IOException> {
response.body.source().readUtf8() response.body.source().readUtf8()
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue() assertThat(call.isCanceled()).isTrue()
} }
} }
@ -223,12 +220,10 @@ class WholeOperationTimeoutTest {
} catch (e: InterruptedException) { } catch (e: InterruptedException) {
throw AssertionError() throw AssertionError()
} }
try { assertFailsWith<IOException> {
response.body.source().readUtf8() response.body.source().readUtf8()
fail<Any>() }.also { expected ->
} catch (e: IOException) { exceptionRef.set(expected)
exceptionRef.set(e)
} finally {
latch.countDown() latch.countDown()
} }
} }
@ -281,11 +276,10 @@ class WholeOperationTimeoutTest {
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS) call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue() assertThat(call.isCanceled()).isTrue()
} }
} }
@ -307,11 +301,10 @@ class WholeOperationTimeoutTest {
val request = Request.Builder().url(server.url("/")).build() val request = Request.Builder().url(server.url("/")).build()
val call = client.newCall(request) val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS) call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("timeout")
assertThat(e.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue() assertThat(call.isCanceled()).isTrue()
} }
} }

View File

@ -41,7 +41,8 @@ import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assumptions import org.junit.jupiter.api.Assumptions
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Timeout 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.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource 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 { cache = DiskLruCache(filesystem, cacheDir, appVersion, 2, Int.MAX_VALUE.toLong(), taskRunner).also {
toClose.add(it) toClose.add(it)
} }
try { assertFailsWith<IOException> {
cache["k1"] cache["k1"]
fail("")
} catch (_: IOException) {
} }
// Now let it operate normally. // Now let it operate normally.
@ -146,49 +145,43 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class) @ArgumentsSource(FileSystemParamProvider::class)
fun validateKey(parameters: Pair<FileSystem, Boolean>) { fun validateKey(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
var key: String? = null var key = ""
try { assertFailsWith<IllegalArgumentException> {
key = "has_space " key = "has_space "
cache.edit(key) cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.") }.also { expected ->
} catch (iae: IllegalArgumentException) { assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
} }
try { assertFailsWith<IllegalArgumentException> {
key = "has_CR\r" key = "has_CR\r"
cache.edit(key) cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.") }.also { expected ->
} catch (iae: IllegalArgumentException) { assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
} }
try { assertFailsWith<IllegalArgumentException> {
key = "has_LF\n" key = "has_LF\n"
cache.edit(key) cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.") }.also { expected ->
} catch (iae: IllegalArgumentException) { assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
} }
try { assertFailsWith<IllegalArgumentException> {
key = "has_invalid/" key = "has_invalid/"
cache.edit(key) cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.") }.also { expected ->
} catch (iae: IllegalArgumentException) { assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
} }
try { assertFailsWith<IllegalArgumentException> {
key = "has_invalid\u2603" key = "has_invalid\u2603"
cache.edit(key) cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.") }.also { expected ->
} catch (iae: IllegalArgumentException) { assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
} }
try { assertFailsWith<IllegalArgumentException> {
key = ("this_is_way_too_long_this_is_way_too_long_this_is_way_too_long_" + 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") "this_is_way_too_long_this_is_way_too_long_this_is_way_too_long")
cache.edit(key) cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was too long.") }.also { expected ->
} catch (iae: IllegalArgumentException) { assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
} }
// Test valid cases. // Test valid cases.
@ -544,10 +537,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class) @ArgumentsSource(FileSystemParamProvider::class)
fun keyWithSpaceNotPermitted(parameters: Pair<FileSystem, Boolean>) { fun keyWithSpaceNotPermitted(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
try { assertFailsWith<IllegalArgumentException> {
cache.edit("my key") cache.edit("my key")
fail("")
} catch (_: IllegalArgumentException) {
} }
} }
@ -555,10 +546,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class) @ArgumentsSource(FileSystemParamProvider::class)
fun keyWithNewlineNotPermitted(parameters: Pair<FileSystem, Boolean>) { fun keyWithNewlineNotPermitted(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
try { assertFailsWith<IllegalArgumentException> {
cache.edit("my\nkey") cache.edit("my\nkey")
fail("")
} catch (_: IllegalArgumentException) {
} }
} }
@ -566,10 +555,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class) @ArgumentsSource(FileSystemParamProvider::class)
fun keyWithCarriageReturnNotPermitted(parameters: Pair<FileSystem, Boolean>) { fun keyWithCarriageReturnNotPermitted(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
try { assertFailsWith<IllegalArgumentException> {
cache.edit("my\rkey") cache.edit("my\rkey")
fail("")
} catch (_: IllegalArgumentException) {
} }
} }
@ -579,10 +566,8 @@ class DiskLruCacheTest {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
val creator = cache.edit("k1")!! val creator = cache.edit("k1")!!
creator.setString(1, "A") creator.setString(1, "A")
try { assertFailsWith<IllegalStateException> {
creator.commit() creator.commit()
fail("")
} catch (_: IllegalStateException) {
} }
assertThat(filesystem.exists(getCleanFile("k1", 0))).isFalse() assertThat(filesystem.exists(getCleanFile("k1", 0))).isFalse()
assertThat(filesystem.exists(getCleanFile("k1", 1))).isFalse() assertThat(filesystem.exists(getCleanFile("k1", 1))).isFalse()
@ -789,10 +774,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class) @ArgumentsSource(FileSystemParamProvider::class)
fun constructorDoesNotAllowZeroCacheSize(parameters: Pair<FileSystem, Boolean>) { fun constructorDoesNotAllowZeroCacheSize(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
try { assertFailsWith<IllegalArgumentException> {
DiskLruCache(filesystem, cacheDir, appVersion, 2, 0, taskRunner) DiskLruCache(filesystem, cacheDir, appVersion, 2, 0, taskRunner)
fail("")
} catch (_: IllegalArgumentException) {
} }
} }
@ -800,10 +783,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class) @ArgumentsSource(FileSystemParamProvider::class)
fun constructorDoesNotAllowZeroValuesPerEntry(parameters: Pair<FileSystem, Boolean>) { fun constructorDoesNotAllowZeroValuesPerEntry(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
try { assertFailsWith<IllegalArgumentException> {
DiskLruCache(filesystem, cacheDir, appVersion, 0, 10, taskRunner) DiskLruCache(filesystem, cacheDir, appVersion, 0, 10, taskRunner)
fail("")
} catch (_: IllegalArgumentException) {
} }
} }
@ -1426,10 +1407,8 @@ class DiskLruCacheTest {
it.assertValue(1, "c2") it.assertValue(1, "c2")
} }
assertThat(iterator.hasNext()).isFalse() assertThat(iterator.hasNext()).isFalse()
try { assertFailsWith<NoSuchElementException> {
iterator.next() iterator.next()
fail("")
} catch (_: NoSuchElementException) {
} }
} }
@ -1500,10 +1479,8 @@ class DiskLruCacheTest {
setUp(parameters.first, parameters.second) setUp(parameters.first, parameters.second)
set("a", "a1", "a2") set("a", "a1", "a2")
val iterator = cache.snapshots() val iterator = cache.snapshots()
try { assertFailsWith<IllegalStateException> {
iterator.remove() iterator.remove()
fail("")
} catch (_: IllegalStateException) {
} }
} }
@ -1516,10 +1493,8 @@ class DiskLruCacheTest {
iterator.next().use { iterator.next().use {
iterator.remove() iterator.remove()
} }
try { assertFailsWith<IllegalStateException> {
iterator.remove() iterator.remove()
fail("")
} catch (_: IllegalStateException) {
} }
} }
@ -2322,30 +2297,20 @@ class DiskLruCacheTest {
private fun sourceAsString(source: Source) = source.buffer().readUtf8() private fun sourceAsString(source: Source) = source.buffer().readUtf8()
private fun Editor.assertInoperable() { private fun Editor.assertInoperable() {
try { assertFailsWith<IllegalStateException> {
setString(0, "A") setString(0, "A")
fail("")
} catch (_: IllegalStateException) {
} }
try { assertFailsWith<IllegalStateException> {
newSource(0) newSource(0)
fail("")
} catch (_: IllegalStateException) {
} }
try { assertFailsWith<IllegalStateException> {
newSink(0) newSink(0)
fail("")
} catch (_: IllegalStateException) {
} }
try { assertFailsWith<IllegalStateException> {
commit() commit()
fail("")
} catch (_: IllegalStateException) {
} }
try { assertFailsWith<IllegalStateException> {
abort() abort()
fail("")
} catch (_: IllegalStateException) {
} }
} }

View File

@ -27,7 +27,8 @@ import okio.buffer
import okio.sink import okio.sink
import okio.source import okio.source
import org.junit.jupiter.api.AfterEach 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.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.api.io.TempDir
@ -165,10 +166,8 @@ class FileOperatorTest {
randomAccessFile!!.getChannel() randomAccessFile!!.getChannel()
) )
val buffer = Buffer() val buffer = Buffer()
try { assertFailsWith<IndexOutOfBoundsException> {
operator.read(0, buffer, -1L) operator.read(0, buffer, -1L)
fail<Any>()
} catch (expected: IndexOutOfBoundsException) {
} }
} }
@ -178,15 +177,11 @@ class FileOperatorTest {
randomAccessFile!!.getChannel() randomAccessFile!!.getChannel()
) )
val buffer = Buffer().writeUtf8("abc") val buffer = Buffer().writeUtf8("abc")
try { assertFailsWith<IndexOutOfBoundsException> {
operator.write(0, buffer, -1L) operator.write(0, buffer, -1L)
fail<Any>()
} catch (expected: IndexOutOfBoundsException) {
} }
try { assertFailsWith<IndexOutOfBoundsException> {
operator.write(0, buffer, 4L) operator.write(0, buffer, 4L)
fail<Any>()
} catch (expected: IndexOutOfBoundsException) {
} }
} }

View File

@ -24,6 +24,7 @@ import java.io.File
import java.io.IOException import java.io.IOException
import java.util.concurrent.Callable import java.util.concurrent.Callable
import java.util.concurrent.Executors import java.util.concurrent.Executors
import kotlin.test.assertFailsWith
import okhttp3.internal.cache2.Relay.Companion.edit import okhttp3.internal.cache2.Relay.Companion.edit
import okhttp3.internal.cache2.Relay.Companion.read import okhttp3.internal.cache2.Relay.Companion.read
import okio.Buffer import okio.Buffer
@ -163,10 +164,9 @@ class RelayTest {
assertThat(source1.readUtf8(10)).isEqualTo("abcdefghij") assertThat(source1.readUtf8(10)).isEqualTo("abcdefghij")
source1.close() // Not exhausted! source1.close() // Not exhausted!
assertThat(relay1.isClosed).isTrue() assertThat(relay1.isClosed).isTrue()
try { assertFailsWith<IOException> {
read(file) read(file)
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("unreadable cache file") assertThat(expected.message).isEqualTo("unreadable cache file")
} }
assertFile(Relay.PREFIX_DIRTY, -1L, -1, null, null) assertFile(Relay.PREFIX_DIRTY, -1L, -1, null, null)

View File

@ -26,7 +26,8 @@ import okhttp3.TestLogHandler
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail import assertk.fail
import kotlin.test.assertFailsWith
class TaskRunnerTest { class TaskRunnerTest {
private val taskFaker = TaskFaker() private val taskFaker = TaskFaker()
@ -618,14 +619,12 @@ class TaskRunnerTest {
@Test fun scheduleThrowsWhenShutdown() { @Test fun scheduleThrowsWhenShutdown() {
redQueue.shutdown() redQueue.shutdown()
try { assertFailsWith<RejectedExecutionException> {
redQueue.schedule(object : Task("task", cancelable = false) { redQueue.schedule(object : Task("task", cancelable = false) {
override fun runOnce(): Long { override fun runOnce(): Long {
return -1L return -1L
} }
}, 100.µs) }, 100.µs)
fail("")
} catch (_: RejectedExecutionException) {
} }
taskFaker.assertNoMoreTasks() taskFaker.assertNoMoreTasks()

View File

@ -26,7 +26,8 @@ import okhttp3.FakeRoutePlanner.ConnectState.TLS_CONNECTED
import okhttp3.internal.concurrent.TaskFaker import okhttp3.internal.concurrent.TaskFaker
import okhttp3.testing.Flaky import okhttp3.testing.Flaky
import org.junit.jupiter.api.AfterEach 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.junit.jupiter.api.Test
import org.junitpioneer.jupiter.RetryingTest import org.junitpioneer.jupiter.RetryingTest
@ -325,11 +326,10 @@ internal class FastFallbackExchangeFinderTest {
plan0.tcpConnectThrowable = IOException("boom!") plan0.tcpConnectThrowable = IOException("boom!")
taskRunner.newQueue().execute("connect") { taskRunner.newQueue().execute("connect") {
try { assertFailsWith<IOException> {
finder.find() finder.find()
fail() }.also { expected ->
} catch (e: IOException) { assertThat(expected).hasMessage("boom!")
assertThat(e).hasMessage("boom!")
} }
} }
@ -374,12 +374,11 @@ internal class FastFallbackExchangeFinderTest {
plan1.tcpConnectThrowable = IOException("boom 1!") plan1.tcpConnectThrowable = IOException("boom 1!")
taskRunner.newQueue().execute("connect") { taskRunner.newQueue().execute("connect") {
try { assertFailsWith<IOException> {
finder.find() finder.find()
fail() }.also { expected ->
} catch (e: IOException) { assertThat(expected).hasMessage("boom 0!")
assertThat(e).hasMessage("boom 0!") assertThat(expected.suppressed.single()).hasMessage("boom 1!")
assertThat(e.suppressed.single()).hasMessage("boom 1!")
} }
} }
@ -403,11 +402,10 @@ internal class FastFallbackExchangeFinderTest {
routePlanner.addPlan() // This plan should not be used. routePlanner.addPlan() // This plan should not be used.
taskRunner.newQueue().execute("connect") { taskRunner.newQueue().execute("connect") {
try { assertFailsWith<IllegalStateException> {
finder.find() finder.find()
fail() }.also { expected ->
} catch (e: IllegalStateException) { assertThat(expected).hasMessage("boom!")
assertThat(e).hasMessage("boom!")
} }
} }
@ -427,11 +425,10 @@ internal class FastFallbackExchangeFinderTest {
plan0.planningThrowable = UnknownServiceException("boom!") plan0.planningThrowable = UnknownServiceException("boom!")
taskRunner.newQueue().execute("connect") { taskRunner.newQueue().execute("connect") {
try { assertFailsWith<UnknownServiceException> {
finder.find() finder.find()
fail() }.also { expected ->
} catch (e: UnknownServiceException) { assertThat(expected).hasMessage("boom!")
assertThat(e).hasMessage("boom!")
} }
} }

View File

@ -29,6 +29,7 @@ import java.net.ProxySelector
import java.net.SocketAddress import java.net.SocketAddress
import java.net.URI import java.net.URI
import java.net.UnknownHostException import java.net.UnknownHostException
import kotlin.test.assertFailsWith
import okhttp3.Address import okhttp3.Address
import okhttp3.Call import okhttp3.Call
import okhttp3.EventListener import okhttp3.EventListener
@ -41,7 +42,6 @@ import okhttp3.internal.connection.RouteSelector.Companion.socketHost
import okhttp3.internal.http.RecordingProxySelector import okhttp3.internal.http.RecordingProxySelector
import okhttp3.testing.PlatformRule import okhttp3.testing.PlatformRule
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension 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) assertRoute(selection.next(), address, Proxy.NO_PROXY, dns.lookup(uriHost, 0), uriPort)
dns.assertRequests(uriHost) dns.assertRequests(uriHost)
assertThat(selection.hasNext()).isFalse() assertThat(selection.hasNext()).isFalse()
try { assertFailsWith<NoSuchElementException> {
selection.next() selection.next()
fail<Any>()
} catch (expected: NoSuchElementException) {
} }
assertThat(routeSelector.hasNext()).isFalse() assertThat(routeSelector.hasNext()).isFalse()
try { assertFailsWith<NoSuchElementException> {
routeSelector.next() routeSelector.next()
fail<Any>()
} catch (expected: NoSuchElementException) {
} }
} }
@ -113,16 +109,12 @@ class RouteSelectorTest {
selection = routeSelector.next() selection = routeSelector.next()
assertRoute(selection.next(), address, Proxy.NO_PROXY, dns.lookup(uriHost, 0), uriPort) assertRoute(selection.next(), address, Proxy.NO_PROXY, dns.lookup(uriHost, 0), uriPort)
assertThat(selection.hasNext()).isFalse() assertThat(selection.hasNext()).isFalse()
try { assertFailsWith<NoSuchElementException> {
selection.next() selection.next()
fail<Any>()
} catch (expected: NoSuchElementException) {
} }
assertThat(routeSelector.hasNext()).isFalse() assertThat(routeSelector.hasNext()).isFalse()
try { assertFailsWith<NoSuchElementException> {
routeSelector.next() routeSelector.next()
fail<Any>()
} catch (expected: NoSuchElementException) {
} }
} }
@ -279,10 +271,8 @@ class RouteSelectorTest {
assertThat(selection1.hasNext()).isFalse() assertThat(selection1.hasNext()).isFalse()
assertThat(routeSelector.hasNext()).isTrue() assertThat(routeSelector.hasNext()).isTrue()
dns.clear(proxyBHost) dns.clear(proxyBHost)
try { assertFailsWith<UnknownHostException> {
routeSelector.next() routeSelector.next()
fail<Any>()
} catch (expected: UnknownHostException) {
} }
dns.assertRequests(proxyBHost) dns.assertRequests(proxyBHost)
assertThat(routeSelector.hasNext()).isTrue() assertThat(routeSelector.hasNext()).isTrue()

View File

@ -20,6 +20,7 @@ import assertk.assertions.contains
import assertk.assertions.doesNotContain import assertk.assertions.doesNotContain
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.startsWith import assertk.assertions.startsWith
import assertk.fail
import java.io.IOException import java.io.IOException
import java.net.ServerSocket import java.net.ServerSocket
import java.net.Socket import java.net.Socket
@ -27,6 +28,7 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.net.ServerSocketFactory import javax.net.ServerSocketFactory
import javax.net.SocketFactory import javax.net.SocketFactory
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import okhttp3.Call 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.Tag
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail
import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource import org.junit.jupiter.params.provider.ArgumentsSource
@ -168,10 +169,9 @@ class CancelTest {
) )
) )
cancelLater(call, 500) cancelLater(call, 500)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail("") }.also { expected ->
} catch (expected: IOException) {
assertEquals(cancelMode == INTERRUPT, Thread.interrupted()) assertEquals(cancelMode == INTERRUPT, Thread.interrupted())
} }
} }
@ -195,11 +195,10 @@ class CancelTest {
cancelLater(call, 500) cancelLater(call, 500)
val responseBody = response.body.byteStream() val responseBody = response.body.byteStream()
val buffer = ByteArray(1024) val buffer = ByteArray(1024)
try { assertFailsWith<IOException> {
while (responseBody.read(buffer) != -1) { while (responseBody.read(buffer) != -1) {
} }
fail("Expected connection to be closed") }.also { expected ->
} catch (expected: IOException) {
assertEquals(cancelMode == INTERRUPT, Thread.interrupted()) assertEquals(cancelMode == INTERRUPT, Thread.interrupted())
} }
responseBody.close() responseBody.close()
@ -227,11 +226,10 @@ class CancelTest {
val cancelLatch = cancelLater(call, 500) val cancelLatch = cancelLater(call, 500)
val responseBody = response.body.byteStream() val responseBody = response.body.byteStream()
val buffer = ByteArray(1024) val buffer = ByteArray(1024)
try { assertFailsWith<IOException> {
while (responseBody.read(buffer) != -1) { while (responseBody.read(buffer) != -1) {
} }
fail("Expected connection to be closed") }.also { expected ->
} catch (expected: IOException) {
assertEquals(cancelMode == INTERRUPT, Thread.interrupted()) assertEquals(cancelMode == INTERRUPT, Thread.interrupted())
} }
responseBody.close() responseBody.close()

View File

@ -20,7 +20,8 @@ import assertk.assertions.isEqualTo
import java.net.ProtocolException import java.net.ProtocolException
import okhttp3.Protocol import okhttp3.Protocol
import okhttp3.internal.http.StatusLine.Companion.parse 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 import org.junit.jupiter.api.Test
class StatusLineTest { class StatusLineTest {
@ -117,10 +118,8 @@ class StatusLineTest {
} }
private fun assertInvalid(statusLine: String) { private fun assertInvalid(statusLine: String) {
try { assertFailsWith<ProtocolException> {
parse(statusLine) parse(statusLine)
fail<Any>("")
} catch (expected: ProtocolException) {
} }
} }
} }

View File

@ -32,7 +32,8 @@ import okhttp3.testing.PlatformRule
import okio.Buffer import okio.Buffer
import okio.BufferedSink import okio.BufferedSink
import org.junit.jupiter.api.AfterEach 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.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -93,16 +94,14 @@ class ThreadInterruptTest {
sink.flush() sink.flush()
sleep(100) sleep(100)
} }
fail<Any>("Expected connection to be closed") fail("Expected connection to be closed")
} }
}) })
.build() .build()
) )
interruptLater(500) interruptLater(500)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>("")
} catch (expected: IOException) {
} }
} }
@ -124,11 +123,9 @@ class ThreadInterruptTest {
interruptLater(500) interruptLater(500)
val responseBody = response.body.byteStream() val responseBody = response.body.byteStream()
val buffer = ByteArray(1024) val buffer = ByteArray(1024)
try { assertFailsWith<IOException> {
while (responseBody.read(buffer) != -1) { while (responseBody.read(buffer) != -1) {
} }
fail<Any>("Expected connection to be interrupted")
} catch (expected: IOException) {
} }
responseBody.close() responseBody.close()
} }

View File

@ -17,7 +17,7 @@ package okhttp3.internal.http2
import okio.BufferedSource import okio.BufferedSource
import okio.ByteString import okio.ByteString
import org.junit.jupiter.api.Assertions.fail import assertk.fail
internal open class BaseTestHandler : Http2Reader.Handler { internal open class BaseTestHandler : Http2Reader.Handler {
override fun data( override fun data(
@ -26,7 +26,7 @@ internal open class BaseTestHandler : Http2Reader.Handler {
source: BufferedSource, source: BufferedSource,
length: Int, length: Int,
) { ) {
fail<Any>() fail("")
} }
override fun headers( override fun headers(
@ -35,25 +35,25 @@ internal open class BaseTestHandler : Http2Reader.Handler {
associatedStreamId: Int, associatedStreamId: Int,
headerBlock: List<Header>, headerBlock: List<Header>,
) { ) {
fail<Any>() fail("")
} }
override fun rstStream( override fun rstStream(
streamId: Int, streamId: Int,
errorCode: ErrorCode, errorCode: ErrorCode,
) { ) {
fail<Any>() fail("")
} }
override fun settings( override fun settings(
clearPrevious: Boolean, clearPrevious: Boolean,
settings: Settings, settings: Settings,
) { ) {
fail<Any>() fail("")
} }
override fun ackSettings() { override fun ackSettings() {
fail<Any>() fail("")
} }
override fun ping( override fun ping(
@ -61,7 +61,7 @@ internal open class BaseTestHandler : Http2Reader.Handler {
payload1: Int, payload1: Int,
payload2: Int, payload2: Int,
) { ) {
fail<Any>() fail("")
} }
override fun goAway( override fun goAway(
@ -69,14 +69,14 @@ internal open class BaseTestHandler : Http2Reader.Handler {
errorCode: ErrorCode, errorCode: ErrorCode,
debugData: ByteString, debugData: ByteString,
) { ) {
fail<Any>() fail("")
} }
override fun windowUpdate( override fun windowUpdate(
streamId: Int, streamId: Int,
windowSizeIncrement: Long, windowSizeIncrement: Long,
) { ) {
fail<Any>() fail("")
} }
override fun priority( override fun priority(
@ -85,7 +85,7 @@ internal open class BaseTestHandler : Http2Reader.Handler {
weight: Int, weight: Int,
exclusive: Boolean, exclusive: Boolean,
) { ) {
fail<Any>() fail("")
} }
override fun pushPromise( override fun pushPromise(
@ -93,7 +93,7 @@ internal open class BaseTestHandler : Http2Reader.Handler {
associatedStreamId: Int, associatedStreamId: Int,
headerBlock: List<Header>, headerBlock: List<Header>,
) { ) {
fail<Any>() fail("")
} }
override fun alternateService( override fun alternateService(
@ -104,6 +104,6 @@ internal open class BaseTestHandler : Http2Reader.Handler {
port: Int, port: Int,
maxAge: Long, maxAge: Long,
) { ) {
fail<Any>() fail("")
} }
} }

View File

@ -19,8 +19,10 @@ import assertk.assertThat
import assertk.assertions.containsExactly import assertk.assertions.containsExactly
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.fail
import java.io.IOException import java.io.IOException
import java.util.Arrays import java.util.Arrays
import kotlin.test.assertFailsWith
import okhttp3.TestUtil.headerEntries import okhttp3.TestUtil.headerEntries
import okio.Buffer import okio.Buffer
import okio.ByteString import okio.ByteString
@ -337,11 +339,10 @@ class HpackTest {
@Test @Test
fun readIndexedHeaderFieldIndex0() { fun readIndexedHeaderFieldIndex0() {
bytesIn.writeByte(0x80) // == Indexed - Add idx = 0 bytesIn.writeByte(0x80) // == Indexed - Add idx = 0
try { assertFailsWith<IOException> {
hpackReader!!.readHeaders() hpackReader!!.readHeaders()
org.junit.jupiter.api.Assertions.fail<Any>("") }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("index == 0")
assertThat(e.message).isEqualTo("index == 0")
} }
} }
@ -349,11 +350,10 @@ class HpackTest {
@Test @Test
fun readIndexedHeaderFieldTooLargeIndex() { fun readIndexedHeaderFieldTooLargeIndex() {
bytesIn.writeShort(0xff00) // == Indexed - Add idx = 127 bytesIn.writeShort(0xff00) // == Indexed - Add idx = 127
try { assertFailsWith<IOException> {
hpackReader!!.readHeaders() hpackReader!!.readHeaders()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("Header index too large 127")
assertThat(e.message).isEqualTo("Header index too large 127")
} }
} }
@ -362,11 +362,10 @@ class HpackTest {
fun readIndexedHeaderFieldInsidiousIndex() { fun readIndexedHeaderFieldInsidiousIndex() {
bytesIn.writeByte(0xff) // == Indexed - Add == bytesIn.writeByte(0xff) // == Indexed - Add ==
bytesIn.write("8080808008".decodeHex()) // idx = -2147483521 bytesIn.write("8080808008".decodeHex()) // idx = -2147483521
try { assertFailsWith<IOException> {
hpackReader!!.readHeaders() hpackReader!!.readHeaders()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("Header index too large -2147483521")
assertThat(e.message).isEqualTo("Header index too large -2147483521")
} }
} }
@ -389,11 +388,10 @@ class HpackTest {
bytesIn.writeByte(0x3f) // encode size 4097 bytesIn.writeByte(0x3f) // encode size 4097
bytesIn.writeByte(0xe2) bytesIn.writeByte(0xe2)
bytesIn.writeByte(0x1f) bytesIn.writeByte(0x1f)
try { assertFailsWith<IOException> {
hpackReader!!.readHeaders() hpackReader!!.readHeaders()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("Invalid dynamic table size update 4097")
assertThat(e.message).isEqualTo("Invalid dynamic table size update 4097")
} }
} }
@ -402,11 +400,10 @@ class HpackTest {
fun readHeaderTableStateChangeInsidiousMaxHeaderByteCount() { fun readHeaderTableStateChangeInsidiousMaxHeaderByteCount() {
bytesIn.writeByte(0x3f) bytesIn.writeByte(0x3f)
bytesIn.write("e1ffffff07".decodeHex()) // count = -2147483648 bytesIn.write("e1ffffff07".decodeHex()) // count = -2147483648
try { assertFailsWith<IOException> {
hpackReader!!.readHeaders() hpackReader!!.readHeaders()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Invalid dynamic table size update -2147483648") .isEqualTo("Invalid dynamic table size update -2147483648")
} }
} }
@ -483,11 +480,10 @@ class HpackTest {
// Indexed name (idx = 4) -> :authority // Indexed name (idx = 4) -> :authority
bytesIn.writeByte(0x0f) // Literal value (len = 15) bytesIn.writeByte(0x0f) // Literal value (len = 15)
bytesIn.writeUtf8("www.example.com") bytesIn.writeUtf8("www.example.com")
try { assertFailsWith<IOException> {
hpackReader!!.readHeaders() hpackReader!!.readHeaders()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("Header index too large 78")
assertThat(e.message).isEqualTo("Header index too large 78")
} }
} }
@ -817,7 +813,7 @@ class HpackTest {
@Test @Test
fun mixedCaseHeaderNameIsMalformed() { fun mixedCaseHeaderNameIsMalformed() {
try { assertFailsWith<IOException> {
newReader( newReader(
byteStream( byteStream(
0, 0,
@ -831,9 +827,8 @@ class HpackTest {
'R'.code 'R'.code
) )
).readHeaders() ).readHeaders()
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"PROTOCOL_ERROR response malformed: mixed case name: Foo" "PROTOCOL_ERROR response malformed: mixed case name: Foo"
) )
} }

View File

@ -46,7 +46,8 @@ import okio.Source
import okio.buffer import okio.buffer
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertArrayEquals 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.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
@ -237,19 +238,16 @@ class Http2ConnectionTest {
val sink1 = stream1.getSink().buffer() val sink1 = stream1.getSink().buffer()
val sink2 = stream2.getSink().buffer() val sink2 = stream2.getSink().buffer()
sink1.writeUtf8("abc") sink1.writeUtf8("abc")
try { assertFailsWith<IOException> {
sink2.writeUtf8("abc") sink2.writeUtf8("abc")
sink2.flush() sink2.flush()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM") assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM")
} }
sink1.writeUtf8("def") sink1.writeUtf8("def")
sink1.close() sink1.close()
try { assertFailsWith<ConnectionShutdownException> {
connection.newStream(headerEntries("c", "cola"), true) connection.newStream(headerEntries("c", "cola"), true)
fail<Any?>()
} catch (expected: ConnectionShutdownException) {
} }
assertThat(stream1.isOpen).isTrue() assertThat(stream1.isOpen).isTrue()
assertThat(stream2.isOpen).isFalse() assertThat(stream2.isOpen).isFalse()
@ -494,15 +492,11 @@ class Http2ConnectionTest {
.build() .build()
connection.start( /* sendConnectionPreface = */false) connection.start( /* sendConnectionPreface = */false)
socket.shutdownOutput() socket.shutdownOutput()
try { assertFailsWith<IOException> {
connection.newStream(headerEntries("a", longString), false) connection.newStream(headerEntries("a", longString), false)
fail<Any?>()
} catch (expected: IOException) {
} }
try { assertFailsWith<IOException> {
connection.newStream(headerEntries("b", longString), false) connection.newStream(headerEntries("b", longString), false)
fail<Any?>()
} catch (expected: IOException) {
} }
} }
@ -676,10 +670,9 @@ class Http2ConnectionTest {
connection.writePingAndAwaitPong() connection.writePingAndAwaitPong()
val sink = stream.getSink().buffer() val sink = stream.getSink().buffer()
sink.writeUtf8("abc") sink.writeUtf8("abc")
try { assertFailsWith<StreamResetException> {
sink.close() sink.close()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.NO_ERROR) assertThat(expected.errorCode).isEqualTo(ErrorCode.NO_ERROR)
} }
assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android")) assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android"))
@ -746,10 +739,8 @@ class Http2ConnectionTest {
val connection = connect(peer) val connection = connect(peer)
val stream = connection.newStream(headerEntries("a", "artichaut"), true) val stream = connection.newStream(headerEntries("a", "artichaut"), true)
connection.writePingAndAwaitPong() connection.writePingAndAwaitPong()
try { assertFailsWith<IllegalStateException> {
stream.trailers() stream.trailers()
fail<Any?>()
} catch (expected: IllegalStateException) {
} }
} }
@ -767,10 +758,8 @@ class Http2ConnectionTest {
val connection = connect(peer) val connection = connect(peer)
val stream = connection.newStream(headerEntries("a", "artichaut"), true) val stream = connection.newStream(headerEntries("a", "artichaut"), true)
connection.writePingAndAwaitPong() connection.writePingAndAwaitPong()
try { assertFailsWith<StreamResetException> {
stream.trailers() stream.trailers()
fail<Any?>()
} catch (expected: StreamResetException) {
} }
} }
@ -788,10 +777,8 @@ class Http2ConnectionTest {
val stream = connection.newStream(headerEntries("a", "android"), true) val stream = connection.newStream(headerEntries("a", "android"), true)
// finish the stream // finish the stream
stream.writeHeaders(headerEntries("b", "berserk"), true, false) stream.writeHeaders(headerEntries("b", "berserk"), true, false)
try { assertFailsWith<IllegalStateException> {
stream.enqueueTrailers(headersOf("trailers", "boom")) stream.enqueueTrailers(headersOf("trailers", "boom"))
fail<Any?>()
} catch (expected: IllegalStateException) {
} }
} }
@ -1092,18 +1079,15 @@ class Http2ConnectionTest {
val stream = connection.newStream(headerEntries("a", "android"), true) val stream = connection.newStream(headerEntries("a", "android"), true)
val out = stream.getSink().buffer() val out = stream.getSink().buffer()
connection.writePingAndAwaitPong() // Ensure that the RST_CANCEL has been received. connection.writePingAndAwaitPong() // Ensure that the RST_CANCEL has been received.
try { assertFailsWith<IOException> {
out.writeUtf8("square") out.writeUtf8("square")
out.flush() out.flush()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream was reset: CANCEL") assertThat(expected.message).isEqualTo("stream was reset: CANCEL")
} }
try {
out.close()
fail<Any?>()
} catch (expected: IOException) {
// Close throws because buffered data wasn't flushed. // Close throws because buffered data wasn't flushed.
assertFailsWith<IOException> {
out.close()
} }
assertThat(connection.openStreamCount()).isEqualTo(0) assertThat(connection.openStreamCount()).isEqualTo(0)
@ -1133,17 +1117,15 @@ class Http2ConnectionTest {
val source = stream.getSource() val source = stream.getSource()
val out = stream.getSink().buffer() val out = stream.getSink().buffer()
source.close() source.close()
try { assertFailsWith<IOException> {
source.read(Buffer(), 1) source.read(Buffer(), 1)
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream closed") assertThat(expected.message).isEqualTo("stream closed")
} }
try { assertFailsWith<IOException> {
out.writeUtf8("a") out.writeUtf8("a")
out.flush() out.flush()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream finished") assertThat(expected.message).isEqualTo("stream finished")
} }
assertThat(connection.openStreamCount()).isEqualTo(0) assertThat(connection.openStreamCount()).isEqualTo(0)
@ -1177,10 +1159,9 @@ class Http2ConnectionTest {
val source = stream.getSource() val source = stream.getSource()
val out = stream.getSink().buffer() val out = stream.getSink().buffer()
source.close() source.close()
try { assertFailsWith<IOException> {
source.read(Buffer(), 1) source.read(Buffer(), 1)
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream closed") assertThat(expected.message).isEqualTo("stream closed")
} }
out.writeUtf8("square") out.writeUtf8("square")
@ -1327,10 +1308,9 @@ class Http2ConnectionTest {
// Play it back. // Play it back.
val connection = connect(peer) val connection = connect(peer)
val stream = connection.newStream(headerEntries("a", "android"), false) val stream = connection.newStream(headerEntries("a", "android"), false)
try { assertFailsWith<IOException> {
stream.takeHeaders() stream.takeHeaders()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM") assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM")
} }
assertThat(connection.openStreamCount()).isEqualTo(0) assertThat(connection.openStreamCount()).isEqualTo(0)
@ -1363,19 +1343,16 @@ class Http2ConnectionTest {
val sink1 = stream1.getSink().buffer() val sink1 = stream1.getSink().buffer()
val sink2 = stream2.getSink().buffer() val sink2 = stream2.getSink().buffer()
sink1.writeUtf8("abc") sink1.writeUtf8("abc")
try { assertFailsWith<IOException> {
sink2.writeUtf8("abc") sink2.writeUtf8("abc")
sink2.flush() sink2.flush()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM") assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM")
} }
sink1.writeUtf8("def") sink1.writeUtf8("def")
sink1.close() sink1.close()
try { assertFailsWith<ConnectionShutdownException> {
connection.newStream(headerEntries("c", "cola"), false) connection.newStream(headerEntries("c", "cola"), false)
fail<Any?>()
} catch (expected: ConnectionShutdownException) {
} }
assertThat(stream1.isOpen).isTrue() assertThat(stream1.isOpen).isTrue()
assertThat(stream2.isOpen).isFalse() assertThat(stream2.isOpen).isFalse()
@ -1444,23 +1421,19 @@ class Http2ConnectionTest {
assertThat(connection.openStreamCount()).isEqualTo(1) assertThat(connection.openStreamCount()).isEqualTo(1)
connection.close() connection.close()
assertThat(connection.openStreamCount()).isEqualTo(0) assertThat(connection.openStreamCount()).isEqualTo(0)
try { assertFailsWith<ConnectionShutdownException> {
connection.newStream(headerEntries("b", "banana"), false) connection.newStream(headerEntries("b", "banana"), false)
fail<Any?>()
} catch (expected: ConnectionShutdownException) {
} }
val sink = stream.getSink().buffer() val sink = stream.getSink().buffer()
try { assertFailsWith<IOException> {
sink.writeByte(0) sink.writeByte(0)
sink.flush() sink.flush()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream finished") assertThat(expected.message).isEqualTo("stream finished")
} }
try { assertFailsWith<IOException> {
stream.getSource().read(Buffer(), 1) stream.getSource().read(Buffer(), 1)
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("stream was reset: CANCEL") assertThat(expected.message).isEqualTo("stream was reset: CANCEL")
} }
@ -1487,10 +1460,8 @@ class Http2ConnectionTest {
val stream = connection.newStream(headerEntries("b", "banana"), false) val stream = connection.newStream(headerEntries("b", "banana"), false)
stream.readTimeout().timeout(500, TimeUnit.MILLISECONDS) stream.readTimeout().timeout(500, TimeUnit.MILLISECONDS)
val startNanos = System.nanoTime() val startNanos = System.nanoTime()
try { assertFailsWith<InterruptedIOException> {
stream.takeHeaders() stream.takeHeaders()
fail<Any?>()
} catch (expected: InterruptedIOException) {
} }
val elapsedNanos = System.nanoTime() - startNanos val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle() awaitWatchdogIdle()
@ -1530,10 +1501,8 @@ class Http2ConnectionTest {
val source = stream.getSource().buffer() val source = stream.getSource().buffer()
source.require(3) source.require(3)
val startNanos = System.nanoTime() val startNanos = System.nanoTime()
try { assertFailsWith<InterruptedIOException> {
source.require(4) source.require(4)
fail<Any?>()
} catch (expected: InterruptedIOException) {
} }
val elapsedNanos = System.nanoTime() - startNanos val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle() awaitWatchdogIdle()
@ -1583,10 +1552,8 @@ class Http2ConnectionTest {
stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS) stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS)
val startNanos = System.nanoTime() val startNanos = System.nanoTime()
sink.write(Buffer().writeUtf8("f"), 1) sink.write(Buffer().writeUtf8("f"), 1)
try { assertFailsWith<InterruptedIOException> {
sink.flush() // This will time out waiting on the write window. sink.flush() // This will time out waiting on the write window.
fail<Any?>()
} catch (expected: InterruptedIOException) {
} }
val elapsedNanos = System.nanoTime() - startNanos val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle() awaitWatchdogIdle()
@ -1628,10 +1595,8 @@ class Http2ConnectionTest {
stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS) stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS)
sink.write(Buffer().writeUtf8("abcdef"), 6) sink.write(Buffer().writeUtf8("abcdef"), 6)
val startNanos = System.nanoTime() val startNanos = System.nanoTime()
try { assertFailsWith<InterruptedIOException> {
sink.flush() // This will time out waiting on the write window. sink.flush() // This will time out waiting on the write window.
fail<Any?>()
} catch (expected: InterruptedIOException) {
} }
val elapsedNanos = System.nanoTime() - startNanos val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle() awaitWatchdogIdle()
@ -1835,10 +1800,8 @@ class Http2ConnectionTest {
val stream = connection.newStream(headerEntries("b", "banana"), false) val stream = connection.newStream(headerEntries("b", "banana"), false)
assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android")) assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android"))
val source = stream.getSource() val source = stream.getSource()
try { assertFailsWith<EOFException> {
source.buffer().readByteString(101) source.buffer().readByteString(101)
fail<Any?>()
} catch (expected: EOFException) {
} }
} }
@ -1914,10 +1877,9 @@ class Http2ConnectionTest {
.build() .build()
connection.start( /* sendConnectionPreface = */false) connection.start( /* sendConnectionPreface = */false)
val stream = connection.newStream(headerEntries("b", "banana"), false) val stream = connection.newStream(headerEntries("b", "banana"), false)
try { assertFailsWith<IOException> {
stream.takeHeaders() stream.takeHeaders()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(expected.message).isEqualTo("Expected a SETTINGS frame but was HEADERS") assertThat(expected.message).isEqualTo("Expected a SETTINGS frame but was HEADERS")
} }

View File

@ -40,7 +40,8 @@ import okio.ByteString.Companion.decodeHex
import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.encodeUtf8
import okio.GzipSink import okio.GzipSink
import okio.buffer import okio.buffer
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.Test
class Http2Test { class Http2Test {
@ -265,11 +266,10 @@ class Http2Test {
frame.writeInt(0) // Settings are always on the connection stream 0. frame.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(2) frame.writeShort(2)
frame.writeInt(2) frame.writeInt(2)
try { assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler()) reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>("") }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1")
assertThat(e.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.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(4) // SETTINGS_INITIAL_WINDOW_SIZE frame.writeShort(4) // SETTINGS_INITIAL_WINDOW_SIZE
frame.writeInt(Int.MIN_VALUE) frame.writeInt(Int.MIN_VALUE)
try { assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler()) reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1" "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.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE
frame.writeInt(Int.MIN_VALUE) frame.writeInt(Int.MIN_VALUE)
try { assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler()) reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: -2147483648" "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.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE
frame.writeInt(2.0.pow(14.0).toInt() - 1) frame.writeInt(2.0.pow(14.0).toInt() - 1)
try { assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler()) reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383")
assertThat(e.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.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE
frame.writeInt(2.0.pow(24.0).toInt()) frame.writeInt(2.0.pow(24.0).toInt())
try { assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler()) reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216")
assertThat(e.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216")
} }
} }
@ -419,11 +415,10 @@ class Http2Test {
frame.writeByte(FLAG_NONE) frame.writeByte(FLAG_NONE)
frame.writeInt(0) frame.writeInt(0)
frame.write(payload) frame.write(payload)
try { assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler()) reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message).isEqualTo("PROTOCOL_ERROR: TYPE_DATA streamId == 0")
assertThat(e.message).isEqualTo("PROTOCOL_ERROR: TYPE_DATA streamId == 0")
} }
} }
@ -438,11 +433,10 @@ class Http2Test {
frame.writeByte(FLAG_COMPRESSED) frame.writeByte(FLAG_COMPRESSED)
frame.writeInt(expectedStreamId and 0x7fffffff) frame.writeInt(expectedStreamId and 0x7fffffff)
zipped.readAll(frame) zipped.readAll(frame)
try { assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler()) reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>() }.also { expected ->
} catch (e: IOException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA") .isEqualTo("PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA")
} }
} }
@ -536,11 +530,10 @@ class Http2Test {
} }
@Test fun tooLargeDataFrame() { @Test fun tooLargeDataFrame() {
try { assertFailsWith<IllegalArgumentException> {
sendDataFrame(Buffer().write(ByteArray(0x1000000))) sendDataFrame(Buffer().write(ByteArray(0x1000000)))
fail<Any>() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216")
assertThat(e.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216")
} }
} }
@ -563,18 +556,16 @@ class Http2Test {
} }
@Test fun badWindowSizeIncrement() { @Test fun badWindowSizeIncrement() {
try { assertFailsWith<IllegalArgumentException> {
windowUpdate(0) windowUpdate(0)
fail<Any>() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0") .isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0")
} }
try { assertFailsWith<IllegalArgumentException> {
windowUpdate(0x80000000L) windowUpdate(0x80000000L)
fail<Any>() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648") .isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648")
} }
} }
@ -630,12 +621,11 @@ class Http2Test {
@Test fun frameSizeError() { @Test fun frameSizeError() {
val writer = Http2Writer(Buffer(), true) val writer = Http2Writer(Buffer(), true)
try { assertFailsWith<IllegalArgumentException> {
writer.frameHeader(0, 16777216, Http2.TYPE_DATA, FLAG_NONE) writer.frameHeader(0, 16777216, Http2.TYPE_DATA, FLAG_NONE)
fail<Any>() }.also { expected ->
} catch (e: IllegalArgumentException) {
// TODO: real max is based on settings between 16384 and 16777215 // 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() { @Test fun streamIdHasReservedBit() {
val writer = Http2Writer(Buffer(), true) val writer = Http2Writer(Buffer(), true)
try { assertFailsWith<IllegalArgumentException> {
var streamId = 3 var streamId = 3
streamId = streamId or (1L shl 31).toInt() // set reserved bit streamId = streamId or (1L shl 31).toInt() // set reserved bit
writer.frameHeader(streamId, Http2.INITIAL_MAX_FRAME_SIZE, Http2.TYPE_DATA, FLAG_NONE) writer.frameHeader(streamId, Http2.INITIAL_MAX_FRAME_SIZE, Http2.TYPE_DATA, FLAG_NONE)
fail<Any>() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message).isEqualTo("reserved bit set: -2147483645")
assertThat(e.message).isEqualTo("reserved bit set: -2147483645")
} }
} }

View File

@ -21,8 +21,10 @@ import assertk.assertions.hasMessage
import assertk.assertions.isCloseTo import assertk.assertions.isCloseTo
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isFalse import assertk.assertions.isFalse
import assertk.assertions.isIn
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.fail
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
import java.net.HttpURLConnection import java.net.HttpURLConnection
@ -38,6 +40,7 @@ import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicReference
import javax.net.ssl.SSLException import javax.net.ssl.SSLException
import kotlin.test.assertFailsWith
import mockwebserver3.Dispatcher import mockwebserver3.Dispatcher
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
@ -85,9 +88,9 @@ import okio.Buffer
import okio.BufferedSink import okio.BufferedSink
import okio.GzipSink import okio.GzipSink
import okio.buffer import okio.buffer
import org.bouncycastle.tls.TlsFatalAlert
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertArrayEquals 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.Assumptions.assumeTrue
import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
@ -546,10 +549,9 @@ class HttpOverHttp2Test {
// Make a call expecting a timeout reading the response headers. // Make a call expecting a timeout reading the response headers.
val call1 = client.newCall(Request(server.url("/"))) val call1 = client.newCall(Request(server.url("/")))
try { assertFailsWith<SocketTimeoutException> {
call1.execute() call1.execute()
fail<Any?>("Should have timed out!") }.also { expected ->
} catch (expected: SocketTimeoutException) {
assertThat(expected.message).isEqualTo("timeout") assertThat(expected.message).isEqualTo("timeout")
} }
@ -613,10 +615,9 @@ class HttpOverHttp2Test {
// Make a call expecting a timeout reading the response body. // Make a call expecting a timeout reading the response body.
val call1 = client.newCall(Request(server.url("/"))) val call1 = client.newCall(Request(server.url("/")))
val response1 = call1.execute() val response1 = call1.execute()
try { assertFailsWith<SocketTimeoutException> {
response1.body.string() response1.body.string()
fail<Any?>("Should have timed out!") }.also { expected ->
} catch (expected: SocketTimeoutException) {
assertThat(expected.message).isEqualTo("timeout") assertThat(expected.message).isEqualTo("timeout")
} }
@ -659,10 +660,8 @@ class HttpOverHttp2Test {
) )
val response1 = call1.execute() val response1 = call1.execute()
assertThat(response1.body.string()).isEqualTo("A") assertThat(response1.body.string()).isEqualTo("A")
try { assertFailsWith<IOException> {
call2.execute() call2.execute()
fail<Any?>()
} catch (expected: IOException) {
} }
// Confirm that the connection was reused. // Confirm that the connection was reused.
@ -825,10 +824,9 @@ class HttpOverHttp2Test {
) )
server.enqueue(MockResponse(body = "abc")) server.enqueue(MockResponse(body = "abc"))
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(server.url("/")))
try { assertFailsWith<StreamResetException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
} }
} }
@ -876,10 +874,9 @@ class HttpOverHttp2Test {
) )
val request = Request(server.url("/")) val request = Request(server.url("/"))
try { assertFailsWith<StreamResetException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
} }
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection. assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection.
@ -899,10 +896,9 @@ class HttpOverHttp2Test {
val request = Request(server.url("/")) val request = Request(server.url("/"))
// First call fails because it only has one route. // First call fails because it only has one route.
try { assertFailsWith<StreamResetException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
} }
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
@ -929,10 +925,9 @@ class HttpOverHttp2Test {
val request = Request(server.url("/")) val request = Request(server.url("/"))
// First call makes a new connection and fails because it is the only route. // First call makes a new connection and fails because it is the only route.
try { assertFailsWith<StreamResetException> {
client.newCall(request).execute() client.newCall(request).execute()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
} }
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection. assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection.
@ -968,10 +963,9 @@ class HttpOverHttp2Test {
MockResponse(body = "abc") MockResponse(body = "abc")
) )
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(server.url("/")))
try { assertFailsWith<StreamResetException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM) assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
} }
} }
@ -1150,7 +1144,7 @@ class HttpOverHttp2Test {
} }
override fun onResponse(call: Call, response: Response) { override fun onResponse(call: Call, response: Response) {
fail<Any?>() fail("")
} }
}) })
assertThat(server.takeRequest().sequenceNumber) assertThat(server.takeRequest().sequenceNumber)
@ -1194,10 +1188,9 @@ class HttpOverHttp2Test {
.retryOnConnectionFailure(false) .retryOnConnectionFailure(false)
.build() .build()
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(server.url("/")))
try { assertFailsWith<StreamResetException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(errorCode) assertThat(expected.errorCode).isEqualTo(errorCode)
} }
} }
@ -1235,7 +1228,7 @@ class HttpOverHttp2Test {
.build() .build()
val callback: Callback = object : Callback { val callback: Callback = object : Callback {
override fun onFailure(call: Call, e: IOException) { override fun onFailure(call: Call, e: IOException) {
fail<Any?>() fail("")
} }
override fun onResponse(call: Call, response: Response) { 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. // Make a call. It'll fail as soon as our pings detect a problem.
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(server.url("/")))
val executeAtNanos = System.nanoTime() val executeAtNanos = System.nanoTime()
try { assertFailsWith<StreamResetException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (expected: StreamResetException) {
assertThat(expected.message).isEqualTo( assertThat(expected.message).isEqualTo(
"stream was reset: PROTOCOL_ERROR" "stream was reset: PROTOCOL_ERROR"
) )
@ -1478,19 +1470,19 @@ class HttpOverHttp2Test {
// The first call times out. // The first call times out.
val call1 = client.newCall(Request(server.url("/"))) val call1 = client.newCall(Request(server.url("/")))
try { assertFailsWith<IOException> {
call1.execute() call1.execute()
fail<Any?>() }.also { expected ->
} catch (expected: SocketTimeoutException) { when (expected) {
} catch (expected: SSLException) { is SocketTimeoutException, is SSLException -> {}
else -> throw expected
}
} }
// The second call times out because it uses the same bad connection. // The second call times out because it uses the same bad connection.
val call2 = client.newCall(Request(server.url("/"))) val call2 = client.newCall(Request(server.url("/")))
try { assertFailsWith<SocketTimeoutException> {
call2.execute() call2.execute()
fail<Any?>()
} catch (expected: SocketTimeoutException) {
} }
// But after the degraded pong timeout, that connection is abandoned. // But after the degraded pong timeout, that connection is abandoned.
@ -1520,12 +1512,10 @@ class HttpOverHttp2Test {
// The first call times out. // The first call times out.
val call1 = client.newCall(Request(server.url("/"))) val call1 = client.newCall(Request(server.url("/")))
try { assertFailsWith<SocketTimeoutException> {
call1.execute().use { response -> call1.execute().use { response ->
response.body.string() response.body.string()
fail<Any?>()
} }
} catch (expected: SocketTimeoutException) {
} }
// The second call succeeds. // The second call succeeds.
@ -1881,7 +1871,7 @@ class HttpOverHttp2Test {
val latch = CountDownLatch(2) val latch = CountDownLatch(2)
val callback: Callback = object : Callback { val callback: Callback = object : Callback {
override fun onResponse(call: Call, response: Response) { override fun onResponse(call: Call, response: Response) {
fail<Any?>() fail("")
} }
override fun onFailure(call: Call, e: IOException) { override fun onFailure(call: Call, e: IOException) {
@ -1897,7 +1887,7 @@ class HttpOverHttp2Test {
server.shutdown() server.shutdown()
} }
} catch (e: IOException) { } catch (e: IOException) {
fail<Any?>() fail("")
} }
} }
})).build() })).build()
@ -1930,10 +1920,9 @@ class HttpOverHttp2Test {
) )
) )
callReference.set(call) callReference.set(call)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any?>() }.also { expected ->
} catch (expected: IOException) {
assertThat(call.isCanceled()).isTrue() assertThat(call.isCanceled()).isTrue()
} }
val recordedRequest = server.takeRequest() val recordedRequest = server.takeRequest()

View File

@ -20,7 +20,7 @@ import assertk.assertions.isEqualTo
import assertk.assertions.isNull import assertk.assertions.isNull
import assertk.assertions.isTrue import assertk.assertions.isTrue
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.fail import kotlin.test.assertFailsWith
import okhttp3.internal.toCanonicalHost import okhttp3.internal.toCanonicalHost
import okio.Buffer import okio.Buffer
import okio.FileSystem import okio.FileSystem
@ -157,17 +157,14 @@ class PublicSuffixDatabaseTest {
path = "/xxx.gz".toPath() path = "/xxx.gz".toPath()
) )
lateinit var firstFailure: Exception lateinit var firstFailure: Exception
try { assertFailsWith<Exception> {
badPublicSuffixDatabase.getEffectiveTldPlusOne("squareup.com") badPublicSuffixDatabase.getEffectiveTldPlusOne("squareup.com")
fail("Read shouldn't have worked") }.also { e ->
} catch (e: Exception) {
firstFailure = e firstFailure = e
} }
try { assertFailsWith<Exception> {
badPublicSuffixDatabase.getEffectiveTldPlusOne("squareup.com") badPublicSuffixDatabase.getEffectiveTldPlusOne("squareup.com")
fail("Read shouldn't have worked") }.also { e ->
} catch (e: Exception) {
// expected
assertEquals(firstFailure.toString(), e.toString()) assertEquals(firstFailure.toString(), e.toString())
} }
} }

View File

@ -19,6 +19,7 @@ import assertk.assertThat
import assertk.assertions.contains import assertk.assertions.contains
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.startsWith import assertk.assertions.startsWith
import java.io.IOException
import java.security.SecureRandom import java.security.SecureRandom
import java.security.cert.X509Certificate import java.security.cert.X509Certificate
import javax.net.ssl.KeyManager import javax.net.ssl.KeyManager
@ -26,6 +27,7 @@ import javax.net.ssl.SSLHandshakeException
import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLPeerUnverifiedException
import javax.net.ssl.SSLSocketFactory import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager import javax.net.ssl.TrustManager
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy.DisconnectAtEnd import mockwebserver3.SocketPolicy.DisconnectAtEnd
@ -40,7 +42,6 @@ import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.HeldCertificate import okhttp3.tls.HeldCertificate
import okhttp3.tls.internal.TlsUtil.newKeyManager import okhttp3.tls.internal.TlsUtil.newKeyManager
import okhttp3.tls.internal.TlsUtil.newTrustManager import okhttp3.tls.internal.TlsUtil.newTrustManager
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.extension.RegisterExtension
@ -266,10 +267,9 @@ class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<SSLPeerUnverifiedException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (expected: SSLPeerUnverifiedException) {
// Certificate pinning fails! // Certificate pinning fails!
assertThat(expected.message!!).startsWith("Certificate pinning failure!") assertThat(expected.message!!).startsWith("Certificate pinning failure!")
} }
@ -351,16 +351,21 @@ class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (expected: SSLHandshakeException) { when (expected) {
is SSLHandshakeException -> {
// On Android, the handshake fails before the certificate pinner runs. // On Android, the handshake fails before the certificate pinner runs.
assertThat(expected.message!!).contains("Could not validate certificate") assertThat(expected.message!!).contains("Could not validate certificate")
} catch (expected: SSLPeerUnverifiedException) { }
is SSLPeerUnverifiedException -> {
// On OpenJDK, the handshake succeeds but the certificate pinner fails. // On OpenJDK, the handshake succeeds but the certificate pinner fails.
assertThat(expected.message!!).startsWith("Certificate pinning failure!") assertThat(expected.message!!).startsWith("Certificate pinning failure!")
} }
else -> throw expected
}
}
} }
/** /**
@ -485,16 +490,21 @@ class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<IOException> {
call.execute() call.execute()
.use { response -> fail<Any>("expected connection failure but got $response") } }.also { expected ->
} catch (expected: SSLPeerUnverifiedException) { when (expected) {
is SSLPeerUnverifiedException -> {
// Certificate pinning fails! // Certificate pinning fails!
assertThat(expected.message!!).startsWith("Certificate pinning failure!") assertThat(expected.message!!).startsWith("Certificate pinning failure!")
} catch (expected: SSLHandshakeException) { }
is SSLHandshakeException -> {
// We didn't have the opportunity to do certificate pinning because the handshake failed. // We didn't have the opportunity to do certificate pinning because the handshake failed.
assertThat(expected.message!!).contains("this is not a CA certificate") assertThat(expected.message!!).contains("this is not a CA certificate")
} }
else -> throw expected
}
}
} }
/** /**
@ -581,11 +591,8 @@ class CertificatePinnerChainValidationTest {
.url(server.url("/")) .url(server.url("/"))
.build() .build()
val call = client.newCall(request) val call = client.newCall(request)
try { assertFailsWith<SSLHandshakeException> {
call.execute().use { response -> call.execute()
fail<Any>("expected connection failure but got $response")
}
} catch (expected: SSLHandshakeException) {
} }
} }

View File

@ -34,6 +34,7 @@ import javax.net.ssl.SSLPeerUnverifiedException
import javax.net.ssl.SSLSocketFactory import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager import javax.net.ssl.TrustManager
import javax.security.auth.x500.X500Principal import javax.security.auth.x500.X500Principal
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.junit5.internal.MockWebServerExtension import mockwebserver3.junit5.internal.MockWebServerExtension
@ -48,7 +49,6 @@ import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.HeldCertificate import okhttp3.tls.HeldCertificate
import okhttp3.tls.internal.TlsUtil.newKeyManager import okhttp3.tls.internal.TlsUtil.newKeyManager
import okhttp3.tls.internal.TlsUtil.newTrustManager import okhttp3.tls.internal.TlsUtil.newTrustManager
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -210,19 +210,25 @@ class ClientAuthTest {
server.useHttps(socketFactory) server.useHttps(socketFactory)
server.requireClientAuth() server.requireClientAuth()
val call = client.newCall(Request.Builder().url(server.url("/")).build()) val call = client.newCall(Request.Builder().url(server.url("/")).build())
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (expected: SSLHandshakeException) { when (expected) {
is SSLHandshakeException -> {
// JDK 11+ // JDK 11+
} catch (expected: SSLException) { }
is SSLException -> {
// javax.net.ssl.SSLException: readRecord // javax.net.ssl.SSLException: readRecord
} catch (expected: SocketException) { }
is SocketException -> {
// Conscrypt, JDK 8 (>= 292), JDK 9 // Conscrypt, JDK 8 (>= 292), JDK 9
} catch (expected: IOException) { }
else -> {
assertThat(expected.message).isEqualTo("exhausted all routes") assertThat(expected.message).isEqualTo("exhausted all routes")
} }
} }
}
}
@Test @Test
fun commonNameIsNotTrusted() { fun commonNameIsNotTrusted() {
@ -237,10 +243,8 @@ class ClientAuthTest {
server.useHttps(socketFactory) server.useHttps(socketFactory)
server.requireClientAuth() server.requireClientAuth()
val call = client.newCall(Request.Builder().url(server.url("/")).build()) val call = client.newCall(Request.Builder().url(server.url("/")).build())
try { assertFailsWith<SSLPeerUnverifiedException> {
call.execute() call.execute()
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
} }
} }
@ -257,21 +261,28 @@ class ClientAuthTest {
server.useHttps(socketFactory) server.useHttps(socketFactory)
server.requireClientAuth() server.requireClientAuth()
val call = client.newCall(Request.Builder().url(server.url("/")).build()) val call = client.newCall(Request.Builder().url(server.url("/")).build())
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>() }.also { expected ->
} catch (expected: SSLHandshakeException) { when (expected) {
is SSLHandshakeException -> {
// JDK 11+ // JDK 11+
} catch (expected: SSLException) { }
is SSLException -> {
// javax.net.ssl.SSLException: readRecord // javax.net.ssl.SSLException: readRecord
} catch (expected: SocketException) { }
is SocketException -> {
// Conscrypt, JDK 8 (>= 292), JDK 9 // Conscrypt, JDK 8 (>= 292), JDK 9
} catch (expected: ConnectionShutdownException) { }
is ConnectionShutdownException -> {
// It didn't fail until it reached the application layer. // It didn't fail until it reached the application layer.
} catch (expected: IOException) { }
else -> {
assertThat(expected.message).isEqualTo("exhausted all routes") assertThat(expected.message).isEqualTo("exhausted all routes")
} }
} }
}
}
@Test @Test
fun invalidClientAuthEvents() { fun invalidClientAuthEvents() {
@ -296,10 +307,8 @@ class ClientAuthTest {
server.useHttps(socketFactory) server.useHttps(socketFactory)
server.requireClientAuth() server.requireClientAuth()
val call = client.newCall(Request.Builder().url(server.url("/")).build()) val call = client.newCall(Request.Builder().url(server.url("/")).build())
try { assertFailsWith<IOException> {
call.execute() call.execute()
fail<Any>()
} catch (expected: IOException) {
} }
// Observed Events are variable // Observed Events are variable

View File

@ -19,12 +19,12 @@ import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isLessThan import assertk.assertions.isLessThan
import java.io.EOFException import java.io.EOFException
import kotlin.test.assertFailsWith
import okhttp3.TestUtil.fragmentBuffer import okhttp3.TestUtil.fragmentBuffer
import okio.Buffer import okio.Buffer
import okio.ByteString import okio.ByteString
import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.decodeHex
import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.encodeUtf8
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
internal class MessageDeflaterInflaterTest { internal class MessageDeflaterInflaterTest {
@ -110,10 +110,8 @@ internal class MessageDeflaterInflaterTest {
val deflater = MessageDeflater(true) val deflater = MessageDeflater(true)
deflater.close() deflater.close()
try { assertFailsWith<Exception> {
deflater.deflate("Hello deflate!".encodeUtf8()) deflater.deflate("Hello deflate!".encodeUtf8())
fail()
} catch (expected: Exception) {
} }
} }
@ -122,10 +120,8 @@ internal class MessageDeflaterInflaterTest {
inflater.close() inflater.close()
try { assertFailsWith<Exception> {
inflater.inflate("f240e30300".decodeHex()) inflater.inflate("f240e30300".decodeHex())
fail()
} catch (expected: Exception) {
} }
} }

View File

@ -26,6 +26,7 @@ import java.io.IOException
import java.net.ProtocolException import java.net.ProtocolException
import java.net.SocketTimeoutException import java.net.SocketTimeoutException
import java.util.Random import java.util.Random
import kotlin.test.assertFailsWith
import okhttp3.Headers import okhttp3.Headers
import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.headersOf
import okhttp3.Protocol import okhttp3.Protocol
@ -98,10 +99,9 @@ class RealWebSocketTest {
@Test @Test
fun clientCloseWith0Fails() { fun clientCloseWith0Fails() {
try { assertFailsWith<IllegalArgumentException> {
client.webSocket!!.close(0, null) client.webSocket!!.close(0, null)
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat("Code must be in range [1000,5000): 0") assertThat("Code must be in range [1000,5000): 0")
.isEqualTo(expected.message) .isEqualTo(expected.message)
} }

View File

@ -38,6 +38,7 @@ import java.util.Random
import java.util.concurrent.CountDownLatch import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.assertFailsWith
import mockwebserver3.Dispatcher import mockwebserver3.Dispatcher
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
@ -607,10 +608,9 @@ class WebSocketHttpTest {
val server = serverListener.assertOpen() val server = serverListener.assertOpen()
clientListener.assertOpen() clientListener.assertOpen()
val reason = repeat('X', 124) val reason = repeat('X', 124)
try { assertFailsWith<IllegalArgumentException> {
webSocket.close(1000, reason) webSocket.close(1000, reason)
org.junit.jupiter.api.Assertions.fail<Any>() }.also { expected ->
} catch (expected: IllegalArgumentException) {
assertThat(expected.message).isEqualTo("reason.size() > 123: $reason") assertThat(expected.message).isEqualTo("reason.size() > 123: $reason")
} }
webSocket.close(1000, null) webSocket.close(1000, null)

View File

@ -24,6 +24,7 @@ import java.io.EOFException
import java.io.IOException import java.io.IOException
import java.net.ProtocolException import java.net.ProtocolException
import java.util.Random import java.util.Random
import kotlin.test.assertFailsWith
import okhttp3.internal.format import okhttp3.internal.format
import okio.Buffer import okio.Buffer
import okio.ByteString import okio.ByteString
@ -75,92 +76,83 @@ class WebSocketReaderTest {
@Test fun controlFramesMustBeFinal() { @Test fun controlFramesMustBeFinal() {
data.write("0a00".decodeHex()) // Empty pong. data.write("0a00".decodeHex()) // Empty pong.
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Control frames must be final.") .isEqualTo("Control frames must be final.")
} }
} }
@Test fun reservedFlag1IsUnsupportedWithNoCompression() { @Test fun reservedFlag1IsUnsupportedWithNoCompression() {
data.write("ca00".decodeHex()) // Empty pong, flag 1 set. data.write("ca00".decodeHex()) // Empty pong, flag 1 set.
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message).isEqualTo("Unexpected rsv1 flag")
assertThat(e.message).isEqualTo("Unexpected rsv1 flag")
} }
} }
@Test fun reservedFlag1IsUnsupportedForControlFrames() { @Test fun reservedFlag1IsUnsupportedForControlFrames() {
data.write("ca00".decodeHex()) // Empty pong, flag 1 set. data.write("ca00".decodeHex()) // Empty pong, flag 1 set.
try { assertFailsWith<ProtocolException> {
clientReaderWithCompression.processNextFrame() clientReaderWithCompression.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message).isEqualTo("Unexpected rsv1 flag")
assertThat(e.message).isEqualTo("Unexpected rsv1 flag")
} }
} }
@Test fun reservedFlag1IsUnsupportedForContinuationFrames() { @Test fun reservedFlag1IsUnsupportedForContinuationFrames() {
data.write("c000".decodeHex()) // Empty continuation, flag 1 set. data.write("c000".decodeHex()) // Empty continuation, flag 1 set.
try { assertFailsWith<ProtocolException> {
clientReaderWithCompression.processNextFrame() clientReaderWithCompression.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message).isEqualTo("Unexpected rsv1 flag")
assertThat(e.message).isEqualTo("Unexpected rsv1 flag")
} }
} }
@Test fun reservedFlags2and3AreUnsupported() { @Test fun reservedFlags2and3AreUnsupported() {
data.write("aa00".decodeHex()) // Empty pong, flag 2 set. data.write("aa00".decodeHex()) // Empty pong, flag 2 set.
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message).isEqualTo("Unexpected rsv2 flag")
assertThat(e.message).isEqualTo("Unexpected rsv2 flag")
} }
data.clear() data.clear()
data.write("9a00".decodeHex()) // Empty pong, flag 3 set. data.write("9a00".decodeHex()) // Empty pong, flag 3 set.
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message).isEqualTo("Unexpected rsv3 flag")
assertThat(e.message).isEqualTo("Unexpected rsv3 flag")
} }
} }
@Test fun clientSentFramesMustBeMasked() { @Test fun clientSentFramesMustBeMasked() {
data.write("8100".decodeHex()) data.write("8100".decodeHex())
try { assertFailsWith<ProtocolException> {
serverReader.processNextFrame() serverReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Client-sent frames must be masked.") .isEqualTo("Client-sent frames must be masked.")
} }
} }
@Test fun serverSentFramesMustNotBeMasked() { @Test fun serverSentFramesMustNotBeMasked() {
data.write("8180".decodeHex()) data.write("8180".decodeHex())
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Server-sent frames must not be masked.") .isEqualTo("Server-sent frames must not be masked.")
} }
} }
@Test fun controlFramePayloadMax() { @Test fun controlFramePayloadMax() {
data.write("8a7e007e".decodeHex()) data.write("8a7e007e".decodeHex())
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Control frame must be less than 125B.") .isEqualTo("Control frame must be less than 125B.")
} }
} }
@ -215,11 +207,10 @@ class WebSocketReaderTest {
@Test fun clientFramePayloadTooLongThrows() { @Test fun clientFramePayloadTooLongThrows() {
data.write("817f8000000000000000".decodeHex()) data.write("817f8000000000000000".decodeHex())
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Frame length 0x8000000000000000 > 0x7FFFFFFFFFFFFFFF" "Frame length 0x8000000000000000 > 0x7FFFFFFFFFFFFFFF"
) )
} }
@ -299,46 +290,36 @@ class WebSocketReaderTest {
@Test fun clientIncompleteMessageBodyThrows() { @Test fun clientIncompleteMessageBodyThrows() {
data.write("810548656c".decodeHex()) // Length = 5, "Hel" data.write("810548656c".decodeHex()) // Length = 5, "Hel"
try { assertFailsWith<EOFException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("")
} catch (ignored: EOFException) {
} }
} }
@Test fun clientUncompressedMessageWithCompressedFlagThrows() { @Test fun clientUncompressedMessageWithCompressedFlagThrows() {
data.write("c10548656c6c6f".decodeHex()) // Uncompressed 'Hello', flag 1 set data.write("c10548656c6c6f".decodeHex()) // Uncompressed 'Hello', flag 1 set
try { assertFailsWith<IOException> {
clientReaderWithCompression.processNextFrame() clientReaderWithCompression.processNextFrame()
fail("")
} catch (ignored: IOException) {
} }
} }
@Test fun clientIncompleteControlFrameBodyThrows() { @Test fun clientIncompleteControlFrameBodyThrows() {
data.write("8a0548656c".decodeHex()) // Length = 5, "Hel" data.write("8a0548656c".decodeHex()) // Length = 5, "Hel"
try { assertFailsWith<EOFException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("")
} catch (ignored: EOFException) {
} }
} }
@Test fun serverIncompleteMessageBodyThrows() { @Test fun serverIncompleteMessageBodyThrows() {
data.write("818537fa213d7f9f4d".decodeHex()) // Length = 5, "Hel" data.write("818537fa213d7f9f4d".decodeHex()) // Length = 5, "Hel"
try { assertFailsWith<EOFException> {
serverReader.processNextFrame() serverReader.processNextFrame()
fail("")
} catch (ignored: EOFException) {
} }
} }
@Test fun serverIncompleteControlFrameBodyThrows() { @Test fun serverIncompleteControlFrameBodyThrows() {
data.write("8a8537fa213d7f9f4d".decodeHex()) // Length = 5, "Hel" data.write("8a8537fa213d7f9f4d".decodeHex()) // Length = 5, "Hel"
try { assertFailsWith<EOFException> {
serverReader.processNextFrame() serverReader.processNextFrame()
fail("")
} catch (ignored: EOFException) {
} }
} }
@ -361,11 +342,10 @@ class WebSocketReaderTest {
val bytes = binaryData(200) val bytes = binaryData(200)
data.write("0264".decodeHex()).write(bytes, 0, 100) data.write("0264".decodeHex()).write(bytes, 0, 100)
data.write("8264".decodeHex()).write(bytes, 100, 100) data.write("8264".decodeHex()).write(bytes, 100, 100)
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Expected continuation opcode. Got: 2") .isEqualTo("Expected continuation opcode. Got: 2")
} }
} }
@ -390,11 +370,10 @@ class WebSocketReaderTest {
@Test fun closeLengthOfOneThrows() { @Test fun closeLengthOfOneThrows() {
data.write("880100".decodeHex()) // Close with invalid 1-byte payload data.write("880100".decodeHex()) // Close with invalid 1-byte payload
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Malformed close payload length of 1.") .isEqualTo("Malformed close payload length of 1.")
} }
} }
@ -414,19 +393,17 @@ class WebSocketReaderTest {
@Test fun closeOutOfRangeThrows() { @Test fun closeOutOfRangeThrows() {
data.write("88020001".decodeHex()) // Close with code 1 data.write("88020001".decodeHex()) // Close with code 1
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Code must be in range [1000,5000): 1") .isEqualTo("Code must be in range [1000,5000): 1")
} }
data.write("88021388".decodeHex()) // Close with code 5000 data.write("88021388".decodeHex()) // Close with code 5000
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message)
assertThat(e.message)
.isEqualTo("Code must be in range [1000,5000): 5000") .isEqualTo("Code must be in range [1000,5000): 5000")
} }
} }
@ -440,11 +417,10 @@ class WebSocketReaderTest {
} }
var count = 0 var count = 0
while (!data.exhausted()) { while (!data.exhausted()) {
try { assertFailsWith<ProtocolException> {
clientReader.processNextFrame() clientReader.processNextFrame()
fail("") }.also { expected ->
} catch (e: ProtocolException) { assertThat(expected.message!!)
assertThat(e.message!!)
.matches(Regex("Code \\d+ is reserved and may not be used.")) .matches(Regex("Code \\d+ is reserved and may not be used."))
} }
count++ count++
@ -458,11 +434,10 @@ class WebSocketReaderTest {
callback.assertTextMessage("Hello") callback.assertTextMessage("Hello")
data.write("c107f248cdc9c90700".decodeHex()) // Hello data.write("c107f248cdc9c90700".decodeHex()) // Hello
clientReaderWithCompression.close() clientReaderWithCompression.close()
try { assertFailsWith<Exception> {
clientReaderWithCompression.processNextFrame() clientReaderWithCompression.processNextFrame()
fail("") }.also { expected ->
} catch (e: Exception) { assertThat(expected.message!!).contains("closed")
assertThat(e.message!!).contains("closed")
} }
} }

View File

@ -30,7 +30,8 @@ import okio.ByteString.Companion.EMPTY
import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.decodeHex
import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.encodeUtf8
import okio.ByteString.Companion.toByteString 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.Test
import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.ExtensionContext
@ -196,20 +197,18 @@ class WebSocketWriterTest {
} }
@Test fun closeCodeOutOfRangeThrows() { @Test fun closeCodeOutOfRangeThrows() {
try { assertFailsWith<IllegalArgumentException> {
clientWriter.writeClose(98724976, "Hello".encodeUtf8()) clientWriter.writeClose(98724976, "Hello".encodeUtf8())
fail() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message).isEqualTo("Code must be in range [1000,5000): 98724976")
assertThat(e.message).isEqualTo("Code must be in range [1000,5000): 98724976")
} }
} }
@Test fun closeReservedThrows() { @Test fun closeReservedThrows() {
try { assertFailsWith<IllegalArgumentException> {
clientWriter.writeClose(1005, "Hello".encodeUtf8()) clientWriter.writeClose(1005, "Hello".encodeUtf8())
fail() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message).isEqualTo("Code 1005 is reserved and may not be used.")
assertThat(e.message).isEqualTo("Code 1005 is reserved and may not be used.")
} }
} }
@ -254,34 +253,31 @@ class WebSocketWriterTest {
} }
@Test fun pingTooLongThrows() { @Test fun pingTooLongThrows() {
try { assertFailsWith<IllegalArgumentException> {
serverWriter.writePing(binaryData(1000)) serverWriter.writePing(binaryData(1000))
fail() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Payload size must be less than or equal to 125" "Payload size must be less than or equal to 125"
) )
} }
} }
@Test fun pongTooLongThrows() { @Test fun pongTooLongThrows() {
try { assertFailsWith<IllegalArgumentException> {
serverWriter.writePong((binaryData(1000))) serverWriter.writePong((binaryData(1000)))
fail() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Payload size must be less than or equal to 125" "Payload size must be less than or equal to 125"
) )
} }
} }
@Test fun closeTooLongThrows() { @Test fun closeTooLongThrows() {
try { assertFailsWith<IllegalArgumentException> {
val longReason: ByteString = repeat('X', 124).encodeUtf8() val longReason: ByteString = repeat('X', 124).encodeUtf8()
serverWriter.writeClose(1000, longReason) serverWriter.writeClose(1000, longReason)
fail() }.also { expected ->
} catch (e: IllegalArgumentException) { assertThat(expected.message).isEqualTo(
assertThat(e.message).isEqualTo(
"Payload size must be less than or equal to 125" "Payload size must be less than or equal to 125"
) )
} }