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.okhttpTls)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
}
mavenPublishing {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -24,6 +24,7 @@ import assertk.assertions.isEqualTo
import assertk.assertions.isTrue
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlin.test.assertFailsWith
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
@ -141,15 +142,12 @@ class SuspendCallTest {
val call = client.newCall(request)
try {
assertFailsWith<IOException> {
call.executeAsync().use {
withContext(Dispatchers.IO) {
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.conscrypt.openjdk)
testImplementation(libs.junit)
testImplementation(libs.kotlin.test.common)
testImplementation(libs.kotlin.test.junit)
}
mavenPublishing {

View File

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

View File

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

View File

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

View File

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

View File

@ -27,6 +27,7 @@ import java.net.ProtocolException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone
import kotlin.test.assertFailsWith
import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName
import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress
import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints
@ -69,10 +70,9 @@ internal class DerTest {
val derReader = DerReader(buffer)
try {
assertFailsWith<ProtocolException> {
derReader.read("test") {}
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("invalid encoding for length")
}
}
@ -85,10 +85,9 @@ internal class DerTest {
val derReader = DerReader(buffer)
try {
assertFailsWith<ProtocolException> {
derReader.read("test") {}
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("invalid encoding for length")
}
}
@ -127,10 +126,9 @@ internal class DerTest {
val derReader = DerReader(buffer)
try {
assertFailsWith<ProtocolException> {
derReader.read("test") {}
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("length > Long.MAX_VALUE")
}
}
@ -152,10 +150,9 @@ internal class DerTest {
val derReader = DerReader(buffer)
try {
assertFailsWith<ProtocolException> {
derReader.read("test") {}
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("length encoded with more than 8 bytes is not supported")
}
@ -634,10 +631,9 @@ internal class DerTest {
}
@Test fun `cannot decode utc time with offset`() {
try {
assertFailsWith<ProtocolException> {
Adapters.UTC_TIME.fromDer("17113139313231353139303231302d30383030".decodeHex())
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("Failed to parse UTCTime 191215190210-0800")
}
}
@ -651,19 +647,17 @@ internal class DerTest {
@Test fun `cannot decode malformed utc time`() {
val bytes = "170d3139313231362333303231305a".decodeHex()
try {
assertFailsWith<ProtocolException> {
Adapters.UTC_TIME.fromDer(bytes)
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("Failed to parse UTCTime 191216#30210Z")
}
}
@Test fun `cannot decode generalized time with offset`() {
try {
assertFailsWith<ProtocolException> {
Adapters.GENERALIZED_TIME.fromDer("181332303139313231353139303231302d30383030".decodeHex())
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191215190210-0800")
}
}
@ -677,10 +671,9 @@ internal class DerTest {
@Test fun `cannot decode malformed generalized time`() {
val bytes = "180f32303139313231362333303231305a".decodeHex()
try {
assertFailsWith<ProtocolException> {
Adapters.GENERALIZED_TIME.fromDer(bytes)
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("Failed to parse GeneralizedTime 20191216#30210Z")
}
}
@ -779,10 +772,9 @@ internal class DerTest {
@Test fun `cannot decode empty bit string`() {
val bytes = "0300".decodeHex()
try {
assertFailsWith<ProtocolException> {
Adapters.BIT_STRING.fromDer(bytes)
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("malformed bit string")
}
}
@ -795,41 +787,39 @@ internal class DerTest {
}
@Test fun `cannot decode constructed octet string`() {
try {
assertFailsWith<ProtocolException> {
Adapters.OCTET_STRING.fromDer(
"2410040668656c6c6f200406776f726c6421".decodeHex())
fail("")
} catch (expected: ProtocolException) {
"2410040668656c6c6f200406776f726c6421".decodeHex()
)
}.also { expected ->
assertThat(expected).hasMessage("constructed octet strings not supported for DER")
}
}
@Test fun `cannot decode constructed bit string`() {
try {
assertFailsWith<ProtocolException> {
Adapters.BIT_STRING.fromDer(
"231203070068656c6c6f20030700776f726c6421".decodeHex())
fail("")
} catch (expected: ProtocolException) {
"231203070068656c6c6f20030700776f726c6421".decodeHex()
)
}.also { expected ->
assertThat(expected).hasMessage("constructed bit strings not supported for DER")
}
}
@Test fun `cannot decode constructed string`() {
try {
assertFailsWith<ProtocolException> {
Adapters.UTF8_STRING.fromDer(
"2c100c0668656c6c6f200c06776f726c6421".decodeHex())
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("constructed strings not supported for DER")
}
}
@Test fun `cannot decode indefinite length bit string`() {
try {
assertFailsWith<ProtocolException> {
Adapters.BIT_STRING.fromDer(
"23800303000A3B0305045F291CD00000".decodeHex())
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("indefinite length not permitted for DER")
}
}
@ -838,12 +828,11 @@ internal class DerTest {
val buffer = Buffer()
.write("3A0904034A6F6E04026573".decodeHex())
val derReader = DerReader(buffer)
try {
assertFailsWith<Exception> {
derReader.read("test") {
derReader.readOctetString()
}
fail("")
} catch (expected: Exception) {
}.also { expected ->
assertThat(expected).hasMessage("constructed octet strings not supported for DER")
}
}
@ -922,10 +911,9 @@ internal class DerTest {
/** Make the claimed length of a nested object larger than the enclosing object. */
@Test fun `large object inside small object`() {
val bytes = "301b300d06092a864886f70d010101050003847fffffff000504030201".decodeHex()
try {
assertFailsWith<ProtocolException> {
CertificateAdapters.subjectPublicKeyInfo.fromDer(bytes)
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("enclosed object too large")
}
}
@ -933,10 +921,9 @@ internal class DerTest {
/** Object identifiers are nominally self-delimiting. Outrun the limit with one. */
@Test fun `variable length long outruns limit`() {
val bytes = "060229ffffff7f".decodeHex()
try {
assertFailsWith<ProtocolException> {
Adapters.OBJECT_IDENTIFIER.fromDer(bytes)
fail("")
} catch (expected: ProtocolException) {
}.also { expected ->
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.isTrue
import java.util.concurrent.TimeUnit
import kotlin.test.assertFailsWith
import okhttp3.CacheControl.Companion.parse
import okhttp3.Headers.Companion.headersOf
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
class CacheControlJvmTest {
@ -192,10 +192,8 @@ class CacheControlJvmTest {
@Throws(Exception::class)
fun secondsMustBeNonNegative() {
val builder = CacheControl.Builder()
try {
assertFailsWith<IllegalArgumentException> {
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.isNull
import assertk.assertions.isTrue
import assertk.fail
import java.io.IOException
import java.net.CookieManager
import java.net.HttpURLConnection
@ -36,6 +37,7 @@ import java.util.TimeZone
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import javax.net.ssl.HostnameVerifier
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer
import mockwebserver3.RecordedRequest
@ -58,8 +60,8 @@ import okio.Path
import okio.Path.Companion.toPath
import okio.buffer
import okio.fakefilesystem.FakeFileSystem
import okio.use
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
@ -692,12 +694,10 @@ class CacheTest {
)
val bodySource = get(server.url("/")).body.source()
assertThat(bodySource.readUtf8Line()).isEqualTo("ABCDE")
try {
bodySource.readUtf8(21)
fail<Any>("This implementation silently ignored a truncated HTTP body.")
} catch (expected: IOException) {
} finally {
bodySource.close()
bodySource.use {
assertFailsWith<IOException> {
bodySource.readUtf8(21)
}
}
assertThat(cache.writeAbortCount()).isEqualTo(1)
assertThat(cache.writeSuccessCount()).isEqualTo(0)
@ -737,10 +737,8 @@ class CacheTest {
val `in` = response1.body.source()
assertThat(`in`.readUtf8(5)).isEqualTo("ABCDE")
`in`.close()
try {
assertFailsWith<IllegalStateException> {
`in`.readByte()
fail<Any>("Expected an IllegalStateException because the source is closed.")
} catch (expected: IllegalStateException) {
}
assertThat(cache.writeAbortCount()).isEqualTo(1)
assertThat(cache.writeSuccessCount()).isEqualTo(0)
@ -2916,10 +2914,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length}
// ... and nothing else.
assertThat(i.hasNext()).isFalse()
try {
assertFailsWith<NoSuchElementException> {
i.next()
fail<Any>()
} catch (expected: NoSuchElementException) {
}
}
@ -2961,10 +2957,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length}
assertThat(get(url).body.string()).isEqualTo("a")
val i = cache.urls()
assertThat(i.hasNext()).isTrue()
try {
assertFailsWith<IllegalStateException> {
i.remove()
fail<Any>()
} catch (expected: IllegalStateException) {
}
}
@ -2983,10 +2977,8 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length}
i.remove()
// Too many calls to remove().
try {
assertFailsWith<IllegalStateException> {
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.
assertThat(i.hasNext()).isFalse()
try {
assertFailsWith<NoSuchElementException> {
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.Timeout
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junitpioneer.jupiter.RetryingTest
@Timeout(30)
@ -160,11 +161,8 @@ class CallKotlinTest {
.header("Content-Type", "application/xml")
.put(ErringRequestBody())
.build()
try {
assertFailsWith<IOException> {
client.newCall(request).execute()
fail("test should always throw exception")
} catch (_: IOException) {
// NOTE: expected
}
request = Request.Builder()
@ -229,10 +227,9 @@ class CallKotlinTest {
.build()
val request = Request(server.url("/"))
try {
assertFailsWith<IOException> {
client.newCall(request).execute()
fail("")
} catch (expected: IOException) {
}.also { expected ->
expected.assertSuppressed {
val suppressed = it.single()
assertThat(suppressed).isInstanceOf(IOException::class.java)
@ -251,10 +248,9 @@ class CallKotlinTest {
.build()
val request = Request(server.url("/"))
try {
assertFailsWith<IOException> {
client.newCall(request).execute()
fail("")
} catch (expected: IOException) {
}.also { expected ->
expected.assertSuppressed {
val suppressed = it.single()
assertThat(suppressed).isInstanceOf(IOException::class.java)

View File

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

View File

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

View File

@ -18,35 +18,32 @@ package okhttp3
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo
import assertk.fail
import java.util.Arrays
import javax.net.ssl.SSLPeerUnverifiedException
import kotlin.test.assertFailsWith
import okhttp3.CertificatePinner.Companion.pin
import okhttp3.CertificatePinner.Companion.sha1Hash
import okhttp3.tls.HeldCertificate
import okio.ByteString.Companion.decodeBase64
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
class CertificatePinnerTest {
@Test
fun malformedPin() {
val builder = CertificatePinner.Builder()
try {
assertFailsWith<IllegalArgumentException> {
builder.add("example.com", "md5/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
fail<Any>()
} catch (expected: IllegalArgumentException) {
}
}
@Test
fun malformedBase64() {
val builder = CertificatePinner.Builder()
try {
assertFailsWith<IllegalArgumentException> {
builder.add("example.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw*")
fail<Any>()
} catch (expected: IllegalArgumentException) {
}
}
@ -100,10 +97,8 @@ class CertificatePinnerTest {
val certificatePinner = CertificatePinner.Builder()
.add("example.com", certA1Sha256Pin)
.build()
try {
assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("example.com", certB1.certificate)
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
}
}
@ -156,10 +151,8 @@ class CertificatePinnerTest {
val certificatePinner = CertificatePinner.Builder()
.add("*.example.com", certA1Sha256Pin)
.build()
try {
assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("a.example.com", listOf(certB1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
}
}
@ -188,10 +181,8 @@ class CertificatePinnerTest {
.add("*.example.com", certA1Sha256Pin)
.add("a.example.com", certB1Sha256Pin)
.build()
try {
assertFailsWith<SSLPeerUnverifiedException> {
certificatePinner.check("a.example.com", listOf(certC1.certificate))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
}
}
@ -202,25 +193,17 @@ class CertificatePinnerTest {
.build()
// Should be pinned:
try {
assertFailsWith<SSLPeerUnverifiedException> {
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))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
}
try {
assertFailsWith<SSLPeerUnverifiedException> {
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))
fail<Any>()
} catch (expected: SSLPeerUnverifiedException) {
}
// Should not be pinned:
@ -232,40 +215,31 @@ class CertificatePinnerTest {
@Test
fun testBadPin() {
try {
assertFailsWith<IllegalArgumentException> {
CertificatePinner.Pin(
"example.co.uk",
"sha256/a"
)
fail<Any>()
} catch (iae: IllegalArgumentException) {
// expected
}
}
@Test
fun testBadAlgorithm() {
try {
assertFailsWith<IllegalArgumentException> {
CertificatePinner.Pin(
"example.co.uk",
"sha512/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
)
fail<Any>()
} catch (iae: IllegalArgumentException) {
// expected
}
}
@Test
fun testBadHost() {
try {
assertFailsWith<IllegalArgumentException> {
CertificatePinner.Pin(
"example.*",
"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.tls.HandshakeCertificates
import okhttp3.tls.HeldCertificate
import org.junit.jupiter.api.Assertions.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
@ -238,7 +239,7 @@ class ConnectionCoalescingTest {
}
override fun onFailure(call: Call, e: IOException) {
fail<Any?>()
fail("")
}
})
val client2 = client.newBuilder()
@ -255,10 +256,8 @@ class ConnectionCoalescingTest {
server.enqueue(MockResponse())
assert200Http2Response(execute(url), server.hostName)
val differentDnsUrl = url.newBuilder().host("differentdns.com").build()
try {
assertFailsWith<IOException> {
execute(differentDnsUrl)
fail<Any?>("expected a failed attempt to connect")
} catch (expected: IOException) {
}
}
@ -275,11 +274,9 @@ class ConnectionCoalescingTest {
.body("unexpected call")
.build()
)
try {
assertFailsWith<IOException> {
val response = execute(url)
response.close()
fail<Any?>("expected a failed attempt to connect")
} catch (expected: IOException) {
}
}
@ -290,10 +287,8 @@ class ConnectionCoalescingTest {
server.enqueue(MockResponse())
assert200Http2Response(execute(url), server.hostName)
val nonsanUrl = url.newBuilder().host("nonsan.com").build()
try {
assertFailsWith<SSLPeerUnverifiedException> {
execute(nonsanUrl)
fail<Any?>("expected a failed attempt to connect")
} catch (expected: SSLPeerUnverifiedException) {
}
}
@ -306,11 +301,9 @@ class ConnectionCoalescingTest {
.build()
)
server.enqueue(MockResponse())
try {
assertFailsWith<SSLPeerUnverifiedException> {
val response = execute(url)
response.close()
fail<Any?>("expected a failed attempt to connect")
} catch (expected: SSLPeerUnverifiedException) {
}
}
@ -339,10 +332,8 @@ class ConnectionCoalescingTest {
server.enqueue(MockResponse())
assert200Http2Response(execute(url), server.hostName)
val sanUrl = url.newBuilder().host("san.com").build()
try {
assertFailsWith<IOException> {
execute(sanUrl)
fail<Any?>("expected a failed attempt to connect")
} catch (expected: IOException) {
}
}
@ -359,10 +350,8 @@ class ConnectionCoalescingTest {
.build()
)
server.enqueue(MockResponse())
try {
assertFailsWith<SSLPeerUnverifiedException> {
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.isEqualTo
import assertk.assertions.isIn
import assertk.fail
import java.io.IOException
import java.net.InetSocketAddress
import java.net.UnknownHostException
import java.time.Duration
import java.util.Arrays
import java.util.concurrent.TimeUnit
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy.FailHandshake
@ -103,10 +105,9 @@ open class ConnectionListenerTest {
val call = client.newCall(Request.Builder()
.url(server!!.url("/"))
.build())
try {
assertFailsWith<IOException> {
call.execute()
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isIn("timeout", "Read timed out")
}
assertThat(listener.recordedEventTypes()).containsExactly(
@ -219,10 +220,8 @@ open class ConnectionListenerTest {
val call = client.newCall(Request.Builder()
.url(server!!.url("/"))
.build())
try {
assertFailsWith<IOException> {
call.execute()
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (expected: IOException) {
}
val address = client.dns.lookup(server!!.hostName)[0]
val expectedAddress = InetSocketAddress(address, server!!.port)

View File

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

View File

@ -26,11 +26,11 @@ import assertk.assertions.isTrue
import java.util.concurrent.CopyOnWriteArraySet
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import kotlin.test.assertFailsWith
import okhttp3.internal.applyConnectionSpec
import okhttp3.internal.platform.Platform.Companion.isAndroid
import okhttp3.testing.PlatformRule
import okhttp3.testing.PlatformVersion.majorVersion
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
@ -40,12 +40,11 @@ class ConnectionSpecTest {
@Test
fun noTlsVersions() {
try {
assertFailsWith<IllegalArgumentException> {
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(*arrayOf<String>())
.build()
fail<Any>()
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("At least one TLS version is required")
}
@ -53,12 +52,11 @@ class ConnectionSpecTest {
@Test
fun noCipherSuites() {
try {
assertFailsWith<IllegalArgumentException> {
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.cipherSuites(*arrayOf<CipherSuite>())
.build()
fail<Any>()
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.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.http.MAX_DATE
import okhttp3.internal.parseCookie
import org.junit.jupiter.api.Assertions.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
@ -446,18 +447,14 @@ class CookieTest {
}
@Test fun builderNameValidation() {
try {
assertFailsWith<IllegalArgumentException> {
Cookie.Builder().name(" a ")
fail<Any>()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun builderValueValidation() {
try {
assertFailsWith<IllegalArgumentException> {
Cookie.Builder().value(" b ")
fail<Any>()
} catch (expected: IllegalArgumentException) {
}
}
@ -492,10 +489,8 @@ class CookieTest {
}
@Test fun builderDomainValidation() {
try {
assertFailsWith<IllegalArgumentException> {
Cookie.Builder().hostOnlyDomain("a/b")
fail<Any>()
} catch (expected: IllegalArgumentException) {
}
}
@ -520,10 +515,8 @@ class CookieTest {
}
@Test fun builderPathValidation() {
try {
assertFailsWith<IllegalArgumentException> {
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.isNull
import assertk.assertions.isTrue
import assertk.fail
import java.net.CookieHandler
import java.net.CookieManager
import java.net.CookiePolicy
@ -35,7 +36,6 @@ import mockwebserver3.MockWebServer
import okhttp3.Cookie.Companion.parse
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.java.net.cookiejar.JavaNetCookieJar
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout
@ -252,7 +252,7 @@ class CookiesTest {
assertThat(request.headers["Cookie"]).isEqualTo("c=cookie")
for (header in redirectTarget.takeRequest().headers.names()) {
if (header.startsWith("Cookie")) {
fail<Any>(header)
fail(header)
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,6 +20,7 @@ import assertk.assertions.containsExactly
import assertk.assertions.isEqualTo
import java.time.Instant
import java.util.Date
import kotlin.test.assertFailsWith
import kotlin.test.fail
import okhttp3.Headers.Companion.toHeaders
import okhttp3.internal.EMPTY_HEADERS
@ -98,41 +99,32 @@ class HeadersJvmTest {
}
@Test fun addThrowsOnEmptyName() {
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add(": bar")
fail()
} catch (expected: IllegalArgumentException) {
}
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add(" : bar")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun addThrowsOnNoColon() {
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("foo bar")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun addThrowsOnMultiColon() {
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add(":status: 200 OK")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun addUnsafeNonAsciiRejectsUnicodeName() {
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder()
.addUnsafeNonAscii("héader1", "value1")
.build()
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
}
}
@ -146,10 +138,8 @@ class HeadersJvmTest {
// Fails on JS, ClassCastException: Illegal cast
@Test fun ofMapThrowsOnNull() {
try {
assertFailsWith<NullPointerException> {
(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.isNotEqualTo
import kotlin.test.Test
import kotlin.test.assertFailsWith
import kotlin.test.fail
import okhttp3.Headers.Companion.headersOf
import okhttp3.Headers.Companion.toHeaders
@ -31,18 +32,14 @@ class HeadersTest {
}
@Test fun ofThrowsOddNumberOfHeaders() {
try {
assertFailsWith<IllegalArgumentException> {
headersOf("User-Agent", "OkHttp", "Content-Length")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofThrowsOnEmptyName() {
try {
assertFailsWith<IllegalArgumentException> {
headersOf("", "OkHttp")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@ -62,26 +59,20 @@ class HeadersTest {
}
@Test fun ofRejectsNullChar() {
try {
assertFailsWith<IllegalArgumentException> {
headersOf("User-Agent", "Square\u0000OkHttp")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofMapThrowsOnEmptyName() {
try {
assertFailsWith<IllegalArgumentException> {
mapOf("" to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofMapThrowsOnBlankName() {
try {
assertFailsWith<IllegalArgumentException> {
mapOf(" " to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@ -109,107 +100,93 @@ class HeadersTest {
}
@Test fun ofMapRejectsNullCharInName() {
try {
assertFailsWith<IllegalArgumentException> {
mapOf("User-\u0000Agent" to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofMapRejectsNullCharInValue() {
try {
assertFailsWith<IllegalArgumentException> {
mapOf("User-Agent" to "Square\u0000OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun builderRejectsUnicodeInHeaderName() {
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("héader1", "value1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
}
}
@Test fun builderRejectsUnicodeInHeaderValue() {
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("header1", "valué1")
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
}
}
@Test fun varargFactoryRejectsUnicodeInHeaderName() {
try {
assertFailsWith<IllegalArgumentException> {
headersOf("héader1", "value1")
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
}
}
@Test fun varargFactoryRejectsUnicodeInHeaderValue() {
try {
assertFailsWith<IllegalArgumentException> {
headersOf("header1", "valué1")
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
}
}
@Test fun mapFactoryRejectsUnicodeInHeaderName() {
try {
assertFailsWith<IllegalArgumentException> {
mapOf("héader1" to "value1").toHeaders()
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
}
}
@Test fun mapFactoryRejectsUnicodeInHeaderValue() {
try {
assertFailsWith<IllegalArgumentException> {
mapOf("header1" to "valué1").toHeaders()
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
}
}
@Test fun sensitiveHeadersNotIncludedInExceptions() {
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Authorization", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Authorization value")
}
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Cookie", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Cookie value")
}
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Proxy-Authorization", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Proxy-Authorization value")
}
try {
assertFailsWith<IllegalArgumentException> {
Headers.Builder().add("Set-Cookie", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Set-Cookie value")
}
@ -286,33 +263,25 @@ class HeadersTest {
@Test fun nameIndexesAreStrict() {
val headers = headersOf("a", "b", "c", "d")
try {
assertFailsWith<IndexOutOfBoundsException> {
headers.name(-1)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
assertThat(headers.name(0)).isEqualTo("a")
assertThat(headers.name(1)).isEqualTo("c")
try {
assertFailsWith<IndexOutOfBoundsException> {
headers.name(2)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
}
@Test fun valueIndexesAreStrict() {
val headers = headersOf("a", "b", "c", "d")
try {
assertFailsWith<IndexOutOfBoundsException> {
headers.value(-1)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
assertThat(headers.value(0)).isEqualTo("b")
assertThat(headers.value(1)).isEqualTo("d")
try {
assertFailsWith<IndexOutOfBoundsException> {
headers.value(2)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
}
}

View File

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

View File

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

View File

@ -19,6 +19,7 @@ import assertk.assertThat
import assertk.assertions.isEqualTo
import java.io.IOException
import java.nio.charset.StandardCharsets
import kotlin.test.assertFailsWith
import okhttp3.Headers.Companion.headersOf
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
@ -26,17 +27,15 @@ import okhttp3.RequestBody.Companion.toRequestBody
import okio.Buffer
import okio.BufferedSink
import okio.utf8Size
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
class MultipartBodyTest {
@Test
fun onePartRequired() {
try {
assertFailsWith<IllegalStateException> {
MultipartBody.Builder().build()
fail<Any>()
} catch (e: IllegalStateException) {
assertThat(e.message)
}.also { expected ->
assertThat(expected.message)
.isEqualTo("Multipart body must have at least one part.")
}
}
@ -241,26 +240,22 @@ class MultipartBodyTest {
@Test
fun contentTypeHeaderIsForbidden() {
val multipart = MultipartBody.Builder()
try {
assertFailsWith<IllegalArgumentException> {
multipart.addPart(
headersOf("Content-Type", "text/plain"),
"Hello, World!".toRequestBody(null)
)
fail<Any>()
} catch (expected: IllegalArgumentException) {
}
}
@Test
fun contentLengthHeaderIsForbidden() {
val multipart = MultipartBody.Builder()
try {
assertFailsWith<IllegalArgumentException> {
multipart.addPart(
headersOf("Content-Length", "13"),
"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.ResponseBody.Companion.toResponseBody
import okio.Buffer
import org.junit.jupiter.api.Assertions.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
@ -116,16 +117,12 @@ class MultipartReaderTest {
)
val part = parts.nextPart()!!
try {
assertFailsWith<EOFException> {
assertThat(part.body.readUtf8()).isEqualTo("abcd\r\nefgh\r\n")
fail()
} catch (expected: EOFException) {
}
try {
assertFailsWith<EOFException> {
assertThat(parts.nextPart()).isNull()
fail()
} catch (expected: EOFException) {
}
}
@ -141,10 +138,8 @@ class MultipartReaderTest {
source = Buffer().writeUtf8(multipart)
)
try {
assertFailsWith<EOFException> {
parts.nextPart()
fail()
} catch (expected: EOFException) {
}
}
@ -243,11 +238,10 @@ class MultipartReaderTest {
val partAbc = parts.nextPart()!!
val partMno = parts.nextPart()!!
try {
assertFailsWith<IllegalStateException> {
partAbc.body.request(20)
fail()
} catch (e: IllegalStateException) {
assertThat(e).hasMessage("closed")
}.also { expected ->
assertThat(expected).hasMessage("closed")
}
assertThat(partMno.body.readUtf8()).isEqualTo("mnop")
@ -271,11 +265,10 @@ class MultipartReaderTest {
val part = parts.nextPart()!!
parts.close()
try {
assertFailsWith<IllegalStateException> {
part.body.request(10)
fail()
} catch (e: IllegalStateException) {
assertThat(e).hasMessage("closed")
}.also { expected ->
assertThat(expected).hasMessage("closed")
}
}
@ -287,11 +280,10 @@ class MultipartReaderTest {
parts.close()
try {
assertFailsWith<IllegalStateException> {
parts.nextPart()
fail()
} catch (e: IllegalStateException) {
assertThat(e).hasMessage("closed")
}.also { expected ->
assertThat(expected).hasMessage("closed")
}
}
@ -306,10 +298,9 @@ class MultipartReaderTest {
source = Buffer().writeUtf8(multipart)
)
try {
assertFailsWith<ProtocolException> {
parts.nextPart()
fail()
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("expected at least 1 part")
}
}
@ -415,10 +406,9 @@ class MultipartReaderTest {
source = Buffer().writeUtf8(multipart)
)
try {
assertFailsWith<ProtocolException> {
parts.nextPart()
fail()
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("unexpected characters after boundary")
}
}
@ -438,10 +428,9 @@ class MultipartReaderTest {
)
parts.nextPart()
try {
assertFailsWith<ProtocolException> {
parts.nextPart()
fail()
} catch (expected: ProtocolException) {
}.also { expected ->
assertThat(expected).hasMessage("unexpected characters after boundary")
}
}
@ -505,10 +494,8 @@ class MultipartReaderTest {
source = Buffer()
)
try {
assertFailsWith<EOFException> {
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.assertNotSame
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Assertions.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
@ -154,10 +155,8 @@ class OkHttpClientTest {
@Test fun setProtocolsRejectsHttp10() {
val builder = OkHttpClient.Builder()
try {
assertFailsWith<IllegalArgumentException> {
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() {
val builder = OkHttpClient.Builder()
builder.interceptors().addAll(listOf(null) as List<Interceptor>)
try {
assertFailsWith<IllegalStateException> {
builder.build()
fail<Any>()
} catch (expected: IllegalStateException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("Null interceptor: [null]")
}
}
@ -181,20 +179,18 @@ class OkHttpClientTest {
@Test fun nullNetworkInterceptorInList() {
val builder = OkHttpClient.Builder()
builder.networkInterceptors().addAll(listOf(null) as List<Interceptor>)
try {
assertFailsWith<IllegalStateException> {
builder.build()
fail<Any>()
} catch (expected: IllegalStateException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("Null network interceptor: [null]")
}
}
@Test fun testH2PriorKnowledgeOkHttpClientConstructionFallback() {
try {
assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder()
.protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1))
fail<Any>()
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message).isEqualTo(
"protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, http/1.1]"
@ -203,11 +199,10 @@ class OkHttpClientTest {
}
@Test fun testH2PriorKnowledgeOkHttpClientConstructionDuplicates() {
try {
assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder()
.protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE))
fail<Any>()
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message).isEqualTo(
"protocols containing h2_prior_knowledge cannot use other protocols: "
+ "[h2_prior_knowledge, h2_prior_knowledge]"
@ -234,10 +229,8 @@ class OkHttpClientTest {
@Test fun sslSocketFactorySetAsSocketFactory() {
val builder = OkHttpClient.Builder()
try {
assertFailsWith<IllegalArgumentException> {
builder.socketFactory(SSLSocketFactory.getDefault())
fail<Any>()
} catch (expected: IllegalArgumentException) {
}
}
@ -245,10 +238,8 @@ class OkHttpClientTest {
val client = OkHttpClient.Builder()
.connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))
.build()
try {
assertFailsWith<IllegalStateException> {
client.sslSocketFactory
fail<Any>()
} catch (expected: IllegalStateException) {
}
}
@ -281,11 +272,10 @@ class OkHttpClientTest {
Protocol.HTTP_1_1,
null
)
try {
assertFailsWith<IllegalArgumentException> {
OkHttpClient.Builder()
.protocols(protocols as List<Protocol>)
fail<Any>()
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("protocols must not contain null")
}
}
@ -420,10 +410,9 @@ class OkHttpClientTest {
@Test fun minWebSocketMessageToCompressNegative() {
val builder = OkHttpClient.Builder()
try {
assertFailsWith<IllegalArgumentException> {
builder.minWebSocketMessageToCompress(-1024)
fail<Any>()
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat(expected.message)
.isEqualTo("minWebSocketMessageToCompress must be positive: -1024")
}

View File

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

View File

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

View File

@ -18,11 +18,13 @@ package okhttp3
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isTrue
import assertk.fail
import java.io.IOException
import java.io.InputStreamReader
import java.io.Reader
import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertFailsWith
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.internal.and
@ -300,11 +302,10 @@ class ResponseBodyJvmTest {
return Buffer().writeUtf8("hello")
}
}
try {
assertFailsWith<IOException> {
body.bytes()
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo(
}.also { expected ->
assertThat(expected.message).isEqualTo(
"Content-Length (10) and stream length (5) disagree"
)
}
@ -325,11 +326,10 @@ class ResponseBodyJvmTest {
throw AssertionError()
}
}
try {
assertFailsWith<IOException> {
body.bytes()
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo(
}.also { expected ->
assertThat(expected.message).isEqualTo(
"Cannot buffer entire body for content length: 2147483648"
)
}
@ -391,11 +391,10 @@ class ResponseBodyJvmTest {
return Buffer().writeUtf8("hello")
}
}
try {
assertFailsWith<IOException> {
body.byteString()
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo(
}.also { expected ->
assertThat(expected.message).isEqualTo(
"Content-Length (10) and stream length (5) disagree"
)
}
@ -416,11 +415,10 @@ class ResponseBodyJvmTest {
throw AssertionError()
}
}
try {
assertFailsWith<IOException> {
body.byteString()
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo(
}.also { expected ->
assertThat(expected.message).isEqualTo(
"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.assertThrows
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail
import assertk.fail
import kotlin.test.assertFailsWith
@Timeout(30)
@Tag("Slowish")
@ -152,15 +153,11 @@ class ServerTruncatesRequestTest {
call.execute().use { response ->
assertThat(response.body.string()).isEqualTo("abc")
val requestBodyOut = requestBody.takeSink()
try {
assertFailsWith<IOException> {
SlowRequestBody.writeTo(requestBodyOut)
fail("")
} catch (expected: IOException) {
}
try {
assertFailsWith<IOException> {
requestBodyOut.close()
fail("")
} catch (expected: IOException) {
}
}
@ -266,10 +263,9 @@ class ServerTruncatesRequestTest {
)
)
try {
assertFailsWith<IOException> {
callA.execute()
fail("")
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected).hasMessage("boom")
}

View File

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

View File

@ -17,6 +17,7 @@ package okhttp3
import assertk.assertThat
import assertk.assertions.startsWith
import kotlin.test.assertFailsWith
import kotlin.test.fail
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.internal.idn.Punycode
@ -142,10 +143,8 @@ class UrlComponentEncodingTester private constructor() {
private fun testForbidden(codePoint: Int, codePointString: String, component: Component) {
val builder = "http://host/".toHttpUrl().newBuilder()
try {
assertFailsWith<IllegalArgumentException> {
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.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.test.assertFailsWith
import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.TestUtil.repeat
import okhttp3.testing.Flaky
import okio.BufferedSink
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
@ -85,11 +85,10 @@ class WholeOperationTimeoutTest {
.build()
val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try {
assertFailsWith<IOException> {
call.execute()
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("timeout")
}.also { expected ->
assertThat(expected.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue()
}
}
@ -134,11 +133,10 @@ class WholeOperationTimeoutTest {
.build()
val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try {
assertFailsWith<IOException> {
call.execute()
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("timeout")
}.also { expected ->
assertThat(expected.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue()
}
}
@ -188,11 +186,10 @@ class WholeOperationTimeoutTest {
call.timeout().timeout(250, TimeUnit.MILLISECONDS)
val response = call.execute()
Thread.sleep(500)
try {
assertFailsWith<IOException> {
response.body.source().readUtf8()
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("timeout")
}.also { expected ->
assertThat(expected.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue()
}
}
@ -223,12 +220,10 @@ class WholeOperationTimeoutTest {
} catch (e: InterruptedException) {
throw AssertionError()
}
try {
assertFailsWith<IOException> {
response.body.source().readUtf8()
fail<Any>()
} catch (e: IOException) {
exceptionRef.set(e)
} finally {
}.also { expected ->
exceptionRef.set(expected)
latch.countDown()
}
}
@ -281,11 +276,10 @@ class WholeOperationTimeoutTest {
.build()
val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try {
assertFailsWith<IOException> {
call.execute()
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("timeout")
}.also { expected ->
assertThat(expected.message).isEqualTo("timeout")
assertThat(call.isCanceled()).isTrue()
}
}
@ -307,11 +301,10 @@ class WholeOperationTimeoutTest {
val request = Request.Builder().url(server.url("/")).build()
val call = client.newCall(request)
call.timeout().timeout(250, TimeUnit.MILLISECONDS)
try {
assertFailsWith<IOException> {
call.execute()
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("timeout")
}.also { expected ->
assertThat(expected.message).isEqualTo("timeout")
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.Tag
import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
@ -129,10 +130,8 @@ class DiskLruCacheTest {
cache = DiskLruCache(filesystem, cacheDir, appVersion, 2, Int.MAX_VALUE.toLong(), taskRunner).also {
toClose.add(it)
}
try {
assertFailsWith<IOException> {
cache["k1"]
fail("")
} catch (_: IOException) {
}
// Now let it operate normally.
@ -146,49 +145,43 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class)
fun validateKey(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second)
var key: String? = null
try {
var key = ""
assertFailsWith<IllegalArgumentException> {
key = "has_space "
cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.")
} catch (iae: IllegalArgumentException) {
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}.also { expected ->
assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}
try {
assertFailsWith<IllegalArgumentException> {
key = "has_CR\r"
cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.")
} catch (iae: IllegalArgumentException) {
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}.also { expected ->
assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}
try {
assertFailsWith<IllegalArgumentException> {
key = "has_LF\n"
cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.")
} catch (iae: IllegalArgumentException) {
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}.also { expected ->
assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}
try {
assertFailsWith<IllegalArgumentException> {
key = "has_invalid/"
cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.")
} catch (iae: IllegalArgumentException) {
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}.also { expected ->
assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}
try {
assertFailsWith<IllegalArgumentException> {
key = "has_invalid\u2603"
cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was invalid.")
} catch (iae: IllegalArgumentException) {
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}.also { expected ->
assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}
try {
assertFailsWith<IllegalArgumentException> {
key = ("this_is_way_too_long_this_is_way_too_long_this_is_way_too_long_" +
"this_is_way_too_long_this_is_way_too_long_this_is_way_too_long")
cache.edit(key)
fail("Expecting an IllegalArgumentException as the key was too long.")
} catch (iae: IllegalArgumentException) {
assertThat(iae.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}.also { expected ->
assertThat(expected.message).isEqualTo("keys must match regex [a-z0-9_-]{1,120}: \"$key\"")
}
// Test valid cases.
@ -544,10 +537,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class)
fun keyWithSpaceNotPermitted(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second)
try {
assertFailsWith<IllegalArgumentException> {
cache.edit("my key")
fail("")
} catch (_: IllegalArgumentException) {
}
}
@ -555,10 +546,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class)
fun keyWithNewlineNotPermitted(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second)
try {
assertFailsWith<IllegalArgumentException> {
cache.edit("my\nkey")
fail("")
} catch (_: IllegalArgumentException) {
}
}
@ -566,10 +555,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class)
fun keyWithCarriageReturnNotPermitted(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second)
try {
assertFailsWith<IllegalArgumentException> {
cache.edit("my\rkey")
fail("")
} catch (_: IllegalArgumentException) {
}
}
@ -579,10 +566,8 @@ class DiskLruCacheTest {
setUp(parameters.first, parameters.second)
val creator = cache.edit("k1")!!
creator.setString(1, "A")
try {
assertFailsWith<IllegalStateException> {
creator.commit()
fail("")
} catch (_: IllegalStateException) {
}
assertThat(filesystem.exists(getCleanFile("k1", 0))).isFalse()
assertThat(filesystem.exists(getCleanFile("k1", 1))).isFalse()
@ -789,10 +774,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class)
fun constructorDoesNotAllowZeroCacheSize(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second)
try {
assertFailsWith<IllegalArgumentException> {
DiskLruCache(filesystem, cacheDir, appVersion, 2, 0, taskRunner)
fail("")
} catch (_: IllegalArgumentException) {
}
}
@ -800,10 +783,8 @@ class DiskLruCacheTest {
@ArgumentsSource(FileSystemParamProvider::class)
fun constructorDoesNotAllowZeroValuesPerEntry(parameters: Pair<FileSystem, Boolean>) {
setUp(parameters.first, parameters.second)
try {
assertFailsWith<IllegalArgumentException> {
DiskLruCache(filesystem, cacheDir, appVersion, 0, 10, taskRunner)
fail("")
} catch (_: IllegalArgumentException) {
}
}
@ -1426,10 +1407,8 @@ class DiskLruCacheTest {
it.assertValue(1, "c2")
}
assertThat(iterator.hasNext()).isFalse()
try {
assertFailsWith<NoSuchElementException> {
iterator.next()
fail("")
} catch (_: NoSuchElementException) {
}
}
@ -1500,10 +1479,8 @@ class DiskLruCacheTest {
setUp(parameters.first, parameters.second)
set("a", "a1", "a2")
val iterator = cache.snapshots()
try {
assertFailsWith<IllegalStateException> {
iterator.remove()
fail("")
} catch (_: IllegalStateException) {
}
}
@ -1516,10 +1493,8 @@ class DiskLruCacheTest {
iterator.next().use {
iterator.remove()
}
try {
assertFailsWith<IllegalStateException> {
iterator.remove()
fail("")
} catch (_: IllegalStateException) {
}
}
@ -2322,30 +2297,20 @@ class DiskLruCacheTest {
private fun sourceAsString(source: Source) = source.buffer().readUtf8()
private fun Editor.assertInoperable() {
try {
assertFailsWith<IllegalStateException> {
setString(0, "A")
fail("")
} catch (_: IllegalStateException) {
}
try {
assertFailsWith<IllegalStateException> {
newSource(0)
fail("")
} catch (_: IllegalStateException) {
}
try {
assertFailsWith<IllegalStateException> {
newSink(0)
fail("")
} catch (_: IllegalStateException) {
}
try {
assertFailsWith<IllegalStateException> {
commit()
fail("")
} catch (_: IllegalStateException) {
}
try {
assertFailsWith<IllegalStateException> {
abort()
fail("")
} catch (_: IllegalStateException) {
}
}

View File

@ -27,7 +27,8 @@ import okio.buffer
import okio.sink
import okio.source
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
@ -165,10 +166,8 @@ class FileOperatorTest {
randomAccessFile!!.getChannel()
)
val buffer = Buffer()
try {
assertFailsWith<IndexOutOfBoundsException> {
operator.read(0, buffer, -1L)
fail<Any>()
} catch (expected: IndexOutOfBoundsException) {
}
}
@ -178,15 +177,11 @@ class FileOperatorTest {
randomAccessFile!!.getChannel()
)
val buffer = Buffer().writeUtf8("abc")
try {
assertFailsWith<IndexOutOfBoundsException> {
operator.write(0, buffer, -1L)
fail<Any>()
} catch (expected: IndexOutOfBoundsException) {
}
try {
assertFailsWith<IndexOutOfBoundsException> {
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.util.concurrent.Callable
import java.util.concurrent.Executors
import kotlin.test.assertFailsWith
import okhttp3.internal.cache2.Relay.Companion.edit
import okhttp3.internal.cache2.Relay.Companion.read
import okio.Buffer
@ -163,10 +164,9 @@ class RelayTest {
assertThat(source1.readUtf8(10)).isEqualTo("abcdefghij")
source1.close() // Not exhausted!
assertThat(relay1.isClosed).isTrue()
try {
assertFailsWith<IOException> {
read(file)
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("unreadable cache file")
}
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.Test
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail
import assertk.fail
import kotlin.test.assertFailsWith
class TaskRunnerTest {
private val taskFaker = TaskFaker()
@ -618,14 +619,12 @@ class TaskRunnerTest {
@Test fun scheduleThrowsWhenShutdown() {
redQueue.shutdown()
try {
assertFailsWith<RejectedExecutionException> {
redQueue.schedule(object : Task("task", cancelable = false) {
override fun runOnce(): Long {
return -1L
}
}, 100.µs)
fail("")
} catch (_: RejectedExecutionException) {
}
taskFaker.assertNoMoreTasks()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -46,7 +46,8 @@ import okio.Source
import okio.buffer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout
@ -237,19 +238,16 @@ class Http2ConnectionTest {
val sink1 = stream1.getSink().buffer()
val sink2 = stream2.getSink().buffer()
sink1.writeUtf8("abc")
try {
assertFailsWith<IOException> {
sink2.writeUtf8("abc")
sink2.flush()
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM")
}
sink1.writeUtf8("def")
sink1.close()
try {
assertFailsWith<ConnectionShutdownException> {
connection.newStream(headerEntries("c", "cola"), true)
fail<Any?>()
} catch (expected: ConnectionShutdownException) {
}
assertThat(stream1.isOpen).isTrue()
assertThat(stream2.isOpen).isFalse()
@ -494,15 +492,11 @@ class Http2ConnectionTest {
.build()
connection.start( /* sendConnectionPreface = */false)
socket.shutdownOutput()
try {
assertFailsWith<IOException> {
connection.newStream(headerEntries("a", longString), false)
fail<Any?>()
} catch (expected: IOException) {
}
try {
assertFailsWith<IOException> {
connection.newStream(headerEntries("b", longString), false)
fail<Any?>()
} catch (expected: IOException) {
}
}
@ -676,10 +670,9 @@ class Http2ConnectionTest {
connection.writePingAndAwaitPong()
val sink = stream.getSink().buffer()
sink.writeUtf8("abc")
try {
assertFailsWith<StreamResetException> {
sink.close()
fail<Any?>()
} catch (expected: StreamResetException) {
}.also { expected ->
assertThat(expected.errorCode).isEqualTo(ErrorCode.NO_ERROR)
}
assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android"))
@ -746,10 +739,8 @@ class Http2ConnectionTest {
val connection = connect(peer)
val stream = connection.newStream(headerEntries("a", "artichaut"), true)
connection.writePingAndAwaitPong()
try {
assertFailsWith<IllegalStateException> {
stream.trailers()
fail<Any?>()
} catch (expected: IllegalStateException) {
}
}
@ -767,10 +758,8 @@ class Http2ConnectionTest {
val connection = connect(peer)
val stream = connection.newStream(headerEntries("a", "artichaut"), true)
connection.writePingAndAwaitPong()
try {
assertFailsWith<StreamResetException> {
stream.trailers()
fail<Any?>()
} catch (expected: StreamResetException) {
}
}
@ -788,10 +777,8 @@ class Http2ConnectionTest {
val stream = connection.newStream(headerEntries("a", "android"), true)
// finish the stream
stream.writeHeaders(headerEntries("b", "berserk"), true, false)
try {
assertFailsWith<IllegalStateException> {
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 out = stream.getSink().buffer()
connection.writePingAndAwaitPong() // Ensure that the RST_CANCEL has been received.
try {
assertFailsWith<IOException> {
out.writeUtf8("square")
out.flush()
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream was reset: CANCEL")
}
try {
// Close throws because buffered data wasn't flushed.
assertFailsWith<IOException> {
out.close()
fail<Any?>()
} catch (expected: IOException) {
// Close throws because buffered data wasn't flushed.
}
assertThat(connection.openStreamCount()).isEqualTo(0)
@ -1133,17 +1117,15 @@ class Http2ConnectionTest {
val source = stream.getSource()
val out = stream.getSink().buffer()
source.close()
try {
assertFailsWith<IOException> {
source.read(Buffer(), 1)
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream closed")
}
try {
assertFailsWith<IOException> {
out.writeUtf8("a")
out.flush()
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream finished")
}
assertThat(connection.openStreamCount()).isEqualTo(0)
@ -1177,10 +1159,9 @@ class Http2ConnectionTest {
val source = stream.getSource()
val out = stream.getSink().buffer()
source.close()
try {
assertFailsWith<IOException> {
source.read(Buffer(), 1)
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream closed")
}
out.writeUtf8("square")
@ -1327,10 +1308,9 @@ class Http2ConnectionTest {
// Play it back.
val connection = connect(peer)
val stream = connection.newStream(headerEntries("a", "android"), false)
try {
assertFailsWith<IOException> {
stream.takeHeaders()
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM")
}
assertThat(connection.openStreamCount()).isEqualTo(0)
@ -1363,19 +1343,16 @@ class Http2ConnectionTest {
val sink1 = stream1.getSink().buffer()
val sink2 = stream2.getSink().buffer()
sink1.writeUtf8("abc")
try {
assertFailsWith<IOException> {
sink2.writeUtf8("abc")
sink2.flush()
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream was reset: REFUSED_STREAM")
}
sink1.writeUtf8("def")
sink1.close()
try {
assertFailsWith<ConnectionShutdownException> {
connection.newStream(headerEntries("c", "cola"), false)
fail<Any?>()
} catch (expected: ConnectionShutdownException) {
}
assertThat(stream1.isOpen).isTrue()
assertThat(stream2.isOpen).isFalse()
@ -1444,23 +1421,19 @@ class Http2ConnectionTest {
assertThat(connection.openStreamCount()).isEqualTo(1)
connection.close()
assertThat(connection.openStreamCount()).isEqualTo(0)
try {
assertFailsWith<ConnectionShutdownException> {
connection.newStream(headerEntries("b", "banana"), false)
fail<Any?>()
} catch (expected: ConnectionShutdownException) {
}
val sink = stream.getSink().buffer()
try {
assertFailsWith<IOException> {
sink.writeByte(0)
sink.flush()
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream finished")
}
try {
assertFailsWith<IOException> {
stream.getSource().read(Buffer(), 1)
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
assertThat(expected.message).isEqualTo("stream was reset: CANCEL")
}
@ -1487,10 +1460,8 @@ class Http2ConnectionTest {
val stream = connection.newStream(headerEntries("b", "banana"), false)
stream.readTimeout().timeout(500, TimeUnit.MILLISECONDS)
val startNanos = System.nanoTime()
try {
assertFailsWith<InterruptedIOException> {
stream.takeHeaders()
fail<Any?>()
} catch (expected: InterruptedIOException) {
}
val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle()
@ -1530,10 +1501,8 @@ class Http2ConnectionTest {
val source = stream.getSource().buffer()
source.require(3)
val startNanos = System.nanoTime()
try {
assertFailsWith<InterruptedIOException> {
source.require(4)
fail<Any?>()
} catch (expected: InterruptedIOException) {
}
val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle()
@ -1583,10 +1552,8 @@ class Http2ConnectionTest {
stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS)
val startNanos = System.nanoTime()
sink.write(Buffer().writeUtf8("f"), 1)
try {
assertFailsWith<InterruptedIOException> {
sink.flush() // This will time out waiting on the write window.
fail<Any?>()
} catch (expected: InterruptedIOException) {
}
val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle()
@ -1628,10 +1595,8 @@ class Http2ConnectionTest {
stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS)
sink.write(Buffer().writeUtf8("abcdef"), 6)
val startNanos = System.nanoTime()
try {
assertFailsWith<InterruptedIOException> {
sink.flush() // This will time out waiting on the write window.
fail<Any?>()
} catch (expected: InterruptedIOException) {
}
val elapsedNanos = System.nanoTime() - startNanos
awaitWatchdogIdle()
@ -1835,10 +1800,8 @@ class Http2ConnectionTest {
val stream = connection.newStream(headerEntries("b", "banana"), false)
assertThat(stream.takeHeaders()).isEqualTo(headersOf("a", "android"))
val source = stream.getSource()
try {
assertFailsWith<EOFException> {
source.buffer().readByteString(101)
fail<Any?>()
} catch (expected: EOFException) {
}
}
@ -1914,10 +1877,9 @@ class Http2ConnectionTest {
.build()
connection.start( /* sendConnectionPreface = */false)
val stream = connection.newStream(headerEntries("b", "banana"), false)
try {
assertFailsWith<IOException> {
stream.takeHeaders()
fail<Any?>()
} catch (expected: IOException) {
}.also { expected ->
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.GzipSink
import okio.buffer
import org.junit.jupiter.api.Assertions.fail
import assertk.fail
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.Test
class Http2Test {
@ -265,11 +266,10 @@ class Http2Test {
frame.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(2)
frame.writeInt(2)
try {
assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>("")
} catch (e: IOException) {
assertThat(e.message).isEqualTo("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1")
}.also { expected ->
assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1")
}
}
@ -310,11 +310,10 @@ class Http2Test {
frame.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(4) // SETTINGS_INITIAL_WINDOW_SIZE
frame.writeInt(Int.MIN_VALUE)
try {
assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo(
}.also { expected ->
assertThat(expected.message).isEqualTo(
"PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1"
)
}
@ -327,11 +326,10 @@ class Http2Test {
frame.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE
frame.writeInt(Int.MIN_VALUE)
try {
assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo(
}.also { expected ->
assertThat(expected.message).isEqualTo(
"PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: -2147483648"
)
}
@ -344,11 +342,10 @@ class Http2Test {
frame.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE
frame.writeInt(2.0.pow(14.0).toInt() - 1)
try {
assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383")
}.also { expected ->
assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383")
}
}
@ -359,11 +356,10 @@ class Http2Test {
frame.writeInt(0) // Settings are always on the connection stream 0.
frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE
frame.writeInt(2.0.pow(24.0).toInt())
try {
assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216")
}.also { expected ->
assertThat(expected.message).isEqualTo("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216")
}
}
@ -419,11 +415,10 @@ class Http2Test {
frame.writeByte(FLAG_NONE)
frame.writeInt(0)
frame.write(payload)
try {
assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>()
} catch (e: IOException) {
assertThat(e.message).isEqualTo("PROTOCOL_ERROR: TYPE_DATA streamId == 0")
}.also { expected ->
assertThat(expected.message).isEqualTo("PROTOCOL_ERROR: TYPE_DATA streamId == 0")
}
}
@ -438,11 +433,10 @@ class Http2Test {
frame.writeByte(FLAG_COMPRESSED)
frame.writeInt(expectedStreamId and 0x7fffffff)
zipped.readAll(frame)
try {
assertFailsWith<IOException> {
reader.nextFrame(requireSettings = false, BaseTestHandler())
fail<Any>()
} catch (e: IOException) {
assertThat(e.message)
}.also { expected ->
assertThat(expected.message)
.isEqualTo("PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA")
}
}
@ -536,11 +530,10 @@ class Http2Test {
}
@Test fun tooLargeDataFrame() {
try {
assertFailsWith<IllegalArgumentException> {
sendDataFrame(Buffer().write(ByteArray(0x1000000)))
fail<Any>()
} catch (e: IllegalArgumentException) {
assertThat(e.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216")
}.also { expected ->
assertThat(expected.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216")
}
}
@ -563,18 +556,16 @@ class Http2Test {
}
@Test fun badWindowSizeIncrement() {
try {
assertFailsWith<IllegalArgumentException> {
windowUpdate(0)
fail<Any>()
} catch (e: IllegalArgumentException) {
assertThat(e.message)
}.also { expected ->
assertThat(expected.message)
.isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0")
}
try {
assertFailsWith<IllegalArgumentException> {
windowUpdate(0x80000000L)
fail<Any>()
} catch (e: IllegalArgumentException) {
assertThat(e.message)
}.also { expected ->
assertThat(expected.message)
.isEqualTo("windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648")
}
}
@ -630,12 +621,11 @@ class Http2Test {
@Test fun frameSizeError() {
val writer = Http2Writer(Buffer(), true)
try {
assertFailsWith<IllegalArgumentException> {
writer.frameHeader(0, 16777216, Http2.TYPE_DATA, FLAG_NONE)
fail<Any>()
} catch (e: IllegalArgumentException) {
}.also { expected ->
// TODO: real max is based on settings between 16384 and 16777215
assertThat(e.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216")
assertThat(expected.message).isEqualTo("FRAME_SIZE_ERROR length > 16384: 16777216")
}
}
@ -649,13 +639,12 @@ class Http2Test {
@Test fun streamIdHasReservedBit() {
val writer = Http2Writer(Buffer(), true)
try {
assertFailsWith<IllegalArgumentException> {
var streamId = 3
streamId = streamId or (1L shl 31).toInt() // set reserved bit
writer.frameHeader(streamId, Http2.INITIAL_MAX_FRAME_SIZE, Http2.TYPE_DATA, FLAG_NONE)
fail<Any>()
} catch (e: IllegalArgumentException) {
assertThat(e.message).isEqualTo("reserved bit set: -2147483645")
}.also { expected ->
assertThat(expected.message).isEqualTo("reserved bit set: -2147483645")
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -19,12 +19,12 @@ import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isLessThan
import java.io.EOFException
import kotlin.test.assertFailsWith
import okhttp3.TestUtil.fragmentBuffer
import okio.Buffer
import okio.ByteString
import okio.ByteString.Companion.decodeHex
import okio.ByteString.Companion.encodeUtf8
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
internal class MessageDeflaterInflaterTest {
@ -110,10 +110,8 @@ internal class MessageDeflaterInflaterTest {
val deflater = MessageDeflater(true)
deflater.close()
try {
assertFailsWith<Exception> {
deflater.deflate("Hello deflate!".encodeUtf8())
fail()
} catch (expected: Exception) {
}
}
@ -122,10 +120,8 @@ internal class MessageDeflaterInflaterTest {
inflater.close()
try {
assertFailsWith<Exception> {
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.SocketTimeoutException
import java.util.Random
import kotlin.test.assertFailsWith
import okhttp3.Headers
import okhttp3.Headers.Companion.headersOf
import okhttp3.Protocol
@ -98,10 +99,9 @@ class RealWebSocketTest {
@Test
fun clientCloseWith0Fails() {
try {
assertFailsWith<IllegalArgumentException> {
client.webSocket!!.close(0, null)
org.junit.jupiter.api.Assertions.fail<Any>()
} catch (expected: IllegalArgumentException) {
}.also { expected ->
assertThat("Code must be in range [1000,5000): 0")
.isEqualTo(expected.message)
}

View File

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

View File

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

View File

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