diff --git a/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt b/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt index ae02c7435449..0ae1e9807988 100644 --- a/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt +++ b/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt @@ -40,7 +40,7 @@ internal fun Dispatcher.wrap(): mockwebserver3.Dispatcher { override fun peek(): mockwebserver3.MockResponse = delegate.peek().wrap() - override fun shutdown() { + override fun close() { delegate.shutdown() } } diff --git a/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt b/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt index 8e992f9b4e65..d82f78a99057 100644 --- a/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt +++ b/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt @@ -217,7 +217,7 @@ class MockWebServer : @Synchronized @Throws(IOException::class) fun shutdown() { - delegate.shutdown() + delegate.close() } @Synchronized override fun after() { diff --git a/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt b/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt index 205d765f085d..26e86f39de36 100644 --- a/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt +++ b/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt @@ -26,11 +26,11 @@ class QueueDispatcher : Dispatcher() { override fun peek(): MockResponse = throw UnsupportedOperationException("unexpected call") fun enqueueResponse(response: MockResponse) { - delegate.enqueueResponse(response.wrap()) + delegate.enqueue(response.wrap()) } override fun shutdown() { - delegate.shutdown() + delegate.close() } fun setFailFast(failFast: Boolean) { diff --git a/mockwebserver-junit4/src/main/kotlin/mockwebserver3/junit4/MockWebServerRule.kt b/mockwebserver-junit4/src/main/kotlin/mockwebserver3/junit4/MockWebServerRule.kt index bda82c9f4013..be364a1fe87a 100644 --- a/mockwebserver-junit4/src/main/kotlin/mockwebserver3/junit4/MockWebServerRule.kt +++ b/mockwebserver-junit4/src/main/kotlin/mockwebserver3/junit4/MockWebServerRule.kt @@ -52,7 +52,7 @@ class MockWebServerRule : ExternalResource() { override fun after() { try { - server.shutdown() + server.close() } catch (e: IOException) { logger.log(Level.WARNING, "MockWebServer shutdown failed", e) } diff --git a/mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/MockWebServerExtension.kt b/mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/MockWebServerExtension.kt index 22425d9cf68b..887cebb07f4e 100644 --- a/mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/MockWebServerExtension.kt +++ b/mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/MockWebServerExtension.kt @@ -77,7 +77,7 @@ class MockWebServerExtension : val toClear = servers.values.toList() servers.clear() for (server in toClear) { - server.shutdown() + server.close() } } catch (e: IOException) { logger.log(Level.WARNING, "MockWebServer shutdown failed", e) diff --git a/mockwebserver/api/mockwebserver3.api b/mockwebserver/api/mockwebserver3.api index ede7b45e55d0..a5729cc86b6c 100644 --- a/mockwebserver/api/mockwebserver3.api +++ b/mockwebserver/api/mockwebserver3.api @@ -1,8 +1,8 @@ -public abstract class mockwebserver3/Dispatcher { +public abstract class mockwebserver3/Dispatcher : java/io/Closeable { public fun ()V + public fun close ()V public abstract fun dispatch (Lmockwebserver3/RecordedRequest;)Lmockwebserver3/MockResponse; public fun peek ()Lmockwebserver3/MockResponse; - public fun shutdown ()V } public final class mockwebserver3/MockResponse { @@ -90,7 +90,6 @@ public abstract interface class mockwebserver3/MockResponseBody { } public final class mockwebserver3/MockWebServer : java/io/Closeable { - public static final field Companion Lmockwebserver3/MockWebServer$Companion; public fun ()V public fun close ()V public final fun enqueue (Lmockwebserver3/MockResponse;)V @@ -113,7 +112,6 @@ public final class mockwebserver3/MockWebServer : java/io/Closeable { public final fun setProtocols (Ljava/util/List;)V public final fun setServerSocketFactory (Ljavax/net/ServerSocketFactory;)V public final fun setStarted (Z)V - public final fun shutdown ()V public final fun start ()V public final fun start (I)V public final fun start (Ljava/net/InetAddress;I)V @@ -126,9 +124,6 @@ public final class mockwebserver3/MockWebServer : java/io/Closeable { public final fun useHttps (Ljavax/net/ssl/SSLSocketFactory;)V } -public final class mockwebserver3/MockWebServer$Companion { -} - public final class mockwebserver3/PushPromise { public fun (Ljava/lang/String;Ljava/lang/String;Lokhttp3/Headers;Lmockwebserver3/MockResponse;)V public final fun getHeaders ()Lokhttp3/Headers; @@ -138,19 +133,15 @@ public final class mockwebserver3/PushPromise { } public class mockwebserver3/QueueDispatcher : mockwebserver3/Dispatcher { - public static final field Companion Lmockwebserver3/QueueDispatcher$Companion; public fun ()V public fun clear ()V + public fun close ()V public fun dispatch (Lmockwebserver3/RecordedRequest;)Lmockwebserver3/MockResponse; - public fun enqueueResponse (Lmockwebserver3/MockResponse;)V + public fun enqueue (Lmockwebserver3/MockResponse;)V protected final fun getResponseQueue ()Ljava/util/concurrent/BlockingQueue; public fun peek ()Lmockwebserver3/MockResponse; public fun setFailFast (Lmockwebserver3/MockResponse;)V public fun setFailFast (Z)V - public fun shutdown ()V -} - -public final class mockwebserver3/QueueDispatcher$Companion { } public final class mockwebserver3/RecordedRequest { diff --git a/mockwebserver/build.gradle.kts b/mockwebserver/build.gradle.kts index aea7d950abc4..d103a7d2ccb9 100644 --- a/mockwebserver/build.gradle.kts +++ b/mockwebserver/build.gradle.kts @@ -1,5 +1,6 @@ import com.vanniktech.maven.publish.JavadocJar import com.vanniktech.maven.publish.KotlinJvm +import org.jetbrains.kotlin.gradle.dsl.kotlinExtension plugins { kotlin("jvm") @@ -29,3 +30,7 @@ dependencies { mavenPublishing { configure(KotlinJvm(javadocJar = JavadocJar.Empty())) } + +kotlin { + explicitApi() +} diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt b/mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt index e1d1bcec0499..c92ccb1fd08f 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt @@ -15,16 +15,17 @@ */ package mockwebserver3 +import java.io.Closeable import mockwebserver3.SocketPolicy.KeepOpen /** Handler for mock server requests. */ -abstract class Dispatcher { +public abstract class Dispatcher : Closeable { /** * Returns a response to satisfy `request`. This method may block (for instance, to wait on * a CountdownLatch). */ @Throws(InterruptedException::class) - abstract fun dispatch(request: RecordedRequest): MockResponse + public abstract fun dispatch(request: RecordedRequest): MockResponse /** * Returns an early guess of the next response, used for policy on how an incoming request should @@ -32,12 +33,12 @@ abstract class Dispatcher { * can return other values to test HTTP edge cases, such as unhappy socket policies or throttled * request bodies. */ - open fun peek(): MockResponse = MockResponse(socketPolicy = KeepOpen) + public open fun peek(): MockResponse = MockResponse(socketPolicy = KeepOpen) /** * Release any resources held by this dispatcher. Any requests that are currently being dispatched * should return immediately. Responses returned after shutdown will not be transmitted: their * socket connections have already been closed. */ - open fun shutdown() {} + public open override fun close() {} } diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt b/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt index d1aa78a57567..f6e863d6e5c1 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt @@ -33,50 +33,50 @@ import okhttp3.internal.http2.Settings import okio.Buffer /** A scripted response to be replayed by the mock web server. */ -class MockResponse { +public class MockResponse { /** Returns the HTTP response line, such as "HTTP/1.1 200 OK". */ - val status: String + public val status: String - val code: Int + public val code: Int get() { val statusParts = status.split(' ', limit = 3) require(statusParts.size >= 2) { "Unexpected status: $status" } return statusParts[1].toInt() } - val message: String + public val message: String get() { val statusParts = status.split(' ', limit = 3) require(statusParts.size >= 2) { "Unexpected status: $status" } return statusParts[2] } - val headers: Headers - val trailers: Headers + public val headers: Headers + public val trailers: Headers // At most one of (body,webSocketListener,streamHandler) is non-null. - val body: MockResponseBody? - val webSocketListener: WebSocketListener? - val socketHandler: SocketHandler? + public val body: MockResponseBody? + public val webSocketListener: WebSocketListener? + public val socketHandler: SocketHandler? - val inTunnel: Boolean - val informationalResponses: List + public val inTunnel: Boolean + public val informationalResponses: List - val throttleBytesPerPeriod: Long - val throttlePeriodNanos: Long + public val throttleBytesPerPeriod: Long + public val throttlePeriodNanos: Long - val socketPolicy: SocketPolicy + public val socketPolicy: SocketPolicy - val headersDelayNanos: Long - val bodyDelayNanos: Long - val trailersDelayNanos: Long + public val headersDelayNanos: Long + public val bodyDelayNanos: Long + public val trailersDelayNanos: Long /** The streams the server will push with this response. */ - val pushPromises: List + public val pushPromises: List - val settings: Settings + public val settings: Settings - constructor( + public constructor( code: Int = 200, headers: Headers = headersOf(), body: String = "", @@ -108,22 +108,22 @@ class MockResponse { this.settings = builder.settings } - fun newBuilder(): Builder = Builder(this) + public fun newBuilder(): Builder = Builder(this) - override fun toString(): String = status + public override fun toString(): String = status - class Builder : Cloneable { - var inTunnel: Boolean + public class Builder : Cloneable { + public var inTunnel: Boolean private set private val informationalResponses_: MutableList - val informationalResponses: List + public val informationalResponses: List get() = informationalResponses_.toList() - var status: String + public var status: String private set - var code: Int + public var code: Int get() { val statusParts = status.split(' ', limit = 3) require(statusParts.size >= 2) { "Unexpected status: $status" } @@ -143,11 +143,11 @@ class MockResponse { } private var headers_: Headers.Builder - val headers: Headers + public val headers: Headers get() = headers_.build() private var trailers_: Headers.Builder - val trailers: Headers + public val trailers: Headers get() = trailers_.build() // At most one of (body,webSocketListener,socketHandler) is non-null. @@ -155,21 +155,21 @@ class MockResponse { private var socketHandlerVar: SocketHandler? = null private var webSocketListenerVar: WebSocketListener? = null - var body: MockResponseBody? + public var body: MockResponseBody? get() = bodyVar private set(value) { bodyVar = value socketHandlerVar = null webSocketListenerVar = null } - var socketHandler: SocketHandler? + public var socketHandler: SocketHandler? get() = socketHandlerVar private set(value) { socketHandlerVar = value bodyVar = null webSocketListenerVar = null } - var webSocketListener: WebSocketListener? + public var webSocketListener: WebSocketListener? get() = webSocketListenerVar private set(value) { webSocketListenerVar = value @@ -177,30 +177,30 @@ class MockResponse { socketHandlerVar = null } - var throttleBytesPerPeriod: Long + public var throttleBytesPerPeriod: Long private set - var throttlePeriodNanos: Long + public var throttlePeriodNanos: Long private set - var socketPolicy: SocketPolicy + public var socketPolicy: SocketPolicy private set - var headersDelayNanos: Long + public var headersDelayNanos: Long private set - var bodyDelayNanos: Long + public var bodyDelayNanos: Long private set - var trailersDelayNanos: Long + public var trailersDelayNanos: Long private set private val pushPromises_: MutableList - val pushPromises: List + public val pushPromises: List get() = pushPromises_.toList() private val settings_: Settings - val settings: Settings + public val settings: Settings get() = Settings().apply { merge(settings_) } - constructor() { + public constructor() { this.inTunnel = false this.informationalResponses_ = mutableListOf() this.status = "HTTP/1.1 200 OK" @@ -244,13 +244,13 @@ class MockResponse { } } - fun code(code: Int) = + public fun code(code: Int): Builder = apply { this.code = code } /** Sets the status and returns this. */ - fun status(status: String) = + public fun status(status: String): Builder = apply { this.status = status } @@ -259,7 +259,7 @@ class MockResponse { * Removes all HTTP headers including any "Content-Length" and "Transfer-encoding" headers that * were added by default. */ - fun clearHeaders() = + public fun clearHeaders(): Builder = apply { headers_ = Headers.Builder() } @@ -268,7 +268,7 @@ class MockResponse { * Adds [header] as an HTTP header. For well-formed HTTP [header] should contain a name followed * by a colon and a value. */ - fun addHeader(header: String) = + public fun addHeader(header: String): Builder = apply { headers_.add(header) } @@ -277,52 +277,55 @@ class MockResponse { * Adds a new header with the name and value. This may be used to add multiple headers with the * same name. */ - fun addHeader( + public fun addHeader( name: String, value: Any, - ) = apply { - headers_.add(name, value.toString()) - } + ): Builder = + apply { + headers_.add(name, value.toString()) + } /** * Adds a new header with the name and value. This may be used to add multiple headers with the * same name. Unlike [addHeader] this does not validate the name and * value. */ - fun addHeaderLenient( + public fun addHeaderLenient( name: String, value: Any, - ) = apply { - addHeaderLenient(headers_, name, value.toString()) - } + ): Builder = + apply { + addHeaderLenient(headers_, name, value.toString()) + } /** Removes all headers named [name], then adds a new header with the name and value. */ - fun setHeader( + public fun setHeader( name: String, value: Any, - ) = apply { - removeHeader(name) - addHeader(name, value) - } + ): Builder = + apply { + removeHeader(name) + addHeader(name, value) + } /** Removes all headers named [name]. */ - fun removeHeader(name: String) = + public fun removeHeader(name: String): Builder = apply { headers_.removeAll(name) } - fun body(body: Buffer) = body(body.toMockResponseBody()) + public fun body(body: Buffer): Builder = body(body.toMockResponseBody()) - fun body(body: MockResponseBody) = + public fun body(body: MockResponseBody): Builder = apply { setHeader("Content-Length", body.contentLength) this.body = body } /** Sets the response body to the UTF-8 encoded bytes of [body]. */ - fun body(body: String): Builder = body(Buffer().writeUtf8(body)) + public fun body(body: String): Builder = body(Buffer().writeUtf8(body)) - fun socketHandler(socketHandler: SocketHandler) = + public fun socketHandler(socketHandler: SocketHandler): Builder = apply { this.socketHandler = socketHandler } @@ -330,48 +333,49 @@ class MockResponse { /** * Sets the response body to [body], chunked every [maxChunkSize] bytes. */ - fun chunkedBody( + public fun chunkedBody( body: Buffer, maxChunkSize: Int = Int.MAX_VALUE, - ) = apply { - removeHeader("Content-Length") - headers_.add("Transfer-encoding: chunked") - - val bytesOut = Buffer() - while (!body.exhausted()) { - val chunkSize = minOf(body.size, maxChunkSize.toLong()) - bytesOut.writeHexadecimalUnsignedLong(chunkSize) - bytesOut.writeUtf8("\r\n") - bytesOut.write(body, chunkSize) - bytesOut.writeUtf8("\r\n") + ): Builder = + apply { + removeHeader("Content-Length") + headers_.add("Transfer-encoding: chunked") + + val bytesOut = Buffer() + while (!body.exhausted()) { + val chunkSize = minOf(body.size, maxChunkSize.toLong()) + bytesOut.writeHexadecimalUnsignedLong(chunkSize) + bytesOut.writeUtf8("\r\n") + bytesOut.write(body, chunkSize) + bytesOut.writeUtf8("\r\n") + } + bytesOut.writeUtf8("0\r\n") // Last chunk. Trailers follow! + this.body = bytesOut.toMockResponseBody() } - bytesOut.writeUtf8("0\r\n") // Last chunk. Trailers follow! - this.body = bytesOut.toMockResponseBody() - } /** * Sets the response body to the UTF-8 encoded bytes of [body], * chunked every [maxChunkSize] bytes. */ - fun chunkedBody( + public fun chunkedBody( body: String, maxChunkSize: Int = Int.MAX_VALUE, ): Builder = chunkedBody(Buffer().writeUtf8(body), maxChunkSize) /** Sets the headers and returns this. */ - fun headers(headers: Headers) = + public fun headers(headers: Headers): Builder = apply { this.headers_ = headers.newBuilder() } /** Sets the trailers and returns this. */ - fun trailers(trailers: Headers) = + public fun trailers(trailers: Headers): Builder = apply { this.trailers_ = trailers.newBuilder() } /** Sets the socket policy and returns this. */ - fun socketPolicy(socketPolicy: SocketPolicy) = + public fun socketPolicy(socketPolicy: SocketPolicy): Builder = apply { this.socketPolicy = socketPolicy } @@ -380,45 +384,49 @@ class MockResponse { * Throttles the request reader and response writer to sleep for the given period after each * series of [bytesPerPeriod] bytes are transferred. Use this to simulate network behavior. */ - fun throttleBody( + public fun throttleBody( bytesPerPeriod: Long, period: Long, unit: TimeUnit, - ) = apply { - throttleBytesPerPeriod = bytesPerPeriod - throttlePeriodNanos = unit.toNanos(period) - } + ): Builder = + apply { + throttleBytesPerPeriod = bytesPerPeriod + throttlePeriodNanos = unit.toNanos(period) + } - fun headersDelay( + public fun headersDelay( delay: Long, unit: TimeUnit, - ) = apply { - headersDelayNanos = unit.toNanos(delay) - } + ): Builder = + apply { + headersDelayNanos = unit.toNanos(delay) + } /** * Set the delayed time of the response body to [delay]. This applies to the response body * only; response headers are not affected. */ - fun bodyDelay( + public fun bodyDelay( delay: Long, unit: TimeUnit, - ) = apply { - bodyDelayNanos = unit.toNanos(delay) - } + ): Builder = + apply { + bodyDelayNanos = unit.toNanos(delay) + } - fun trailersDelay( + public fun trailersDelay( delay: Long, unit: TimeUnit, - ) = apply { - trailersDelayNanos = unit.toNanos(delay) - } + ): Builder = + apply { + trailersDelayNanos = unit.toNanos(delay) + } /** * When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this attaches a * pushed stream to this response. */ - fun addPush(promise: PushPromise) = + public fun addPush(promise: PushPromise): Builder = apply { this.pushPromises_ += promise } @@ -427,7 +435,7 @@ class MockResponse { * When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this pushes * [settings] before writing the response. */ - fun settings(settings: Settings) = + public fun settings(settings: Settings): Builder = apply { this.settings_.clear() this.settings_.merge(settings) @@ -437,7 +445,7 @@ class MockResponse { * Attempts to perform a web socket upgrade on the connection. * This will overwrite any previously set status, body, or streamHandler. */ - fun webSocketUpgrade(listener: WebSocketListener) = + public fun webSocketUpgrade(listener: WebSocketListener): Builder = apply { status = "HTTP/1.1 101 Switching Protocols" setHeader("Connection", "Upgrade") @@ -452,7 +460,7 @@ class MockResponse { * When a new connection is received, all in-tunnel responses are served before the connection is * upgraded to HTTPS or HTTP/2. */ - fun inTunnel() = + public fun inTunnel(): Builder = apply { removeHeader("Content-Length") inTunnel = true @@ -463,18 +471,18 @@ class MockResponse { * [headers delay][headersDelay] applies after this response is transmitted. Set a * headers delay on that response to delay its transmission. */ - fun addInformationalResponse(response: MockResponse) = + public fun addInformationalResponse(response: MockResponse): Builder = apply { informationalResponses_ += response } - fun add100Continue() = + public fun add100Continue(): Builder = apply { addInformationalResponse(MockResponse(code = 100)) } public override fun clone(): Builder = build().newBuilder() - fun build(): MockResponse = MockResponse(this) + public fun build(): MockResponse = MockResponse(this) } } diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/MockResponseBody.kt b/mockwebserver/src/main/kotlin/mockwebserver3/MockResponseBody.kt index ed3fa20f314e..d5c9f4010e1a 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/MockResponseBody.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/MockResponseBody.kt @@ -17,7 +17,6 @@ package mockwebserver3 import java.io.IOException -import okhttp3.ExperimentalOkHttpApi import okio.BufferedSink /** @@ -26,11 +25,10 @@ import okio.BufferedSink * Unlike [okhttp3.ResponseBody], this interface is designed to be implemented by writers and not * called by readers. */ -@ExperimentalOkHttpApi -interface MockResponseBody { +public interface MockResponseBody { /** The length of this response in bytes, or -1 if unknown. */ - val contentLength: Long + public val contentLength: Long @Throws(IOException::class) - fun writeTo(sink: BufferedSink) + public fun writeTo(sink: BufferedSink) } diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt b/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt index a4ce2a0fded3..cdce3d6eb1b0 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt @@ -66,7 +66,6 @@ import mockwebserver3.SocketPolicy.StallSocketAtStart import mockwebserver3.internal.ThrottledSink import mockwebserver3.internal.TriggerSink import mockwebserver3.internal.sleepNanos -import okhttp3.ExperimentalOkHttpApi import okhttp3.Headers import okhttp3.Headers.Companion.headersOf import okhttp3.HttpUrl @@ -101,8 +100,7 @@ import okio.source * A scriptable web server. Callers supply canned responses and the server replays them upon request * in sequence. */ -@ExperimentalOkHttpApi -class MockWebServer : Closeable { +public class MockWebServer : Closeable { private val taskRunnerBackend = TaskRunner.RealBackend( threadFactory("MockWebServer TaskRunner", daemon = false), @@ -120,13 +118,13 @@ class MockWebServer : Closeable { * The number of HTTP requests received thus far by this server. This may exceed the number of * HTTP connections when connection reuse is in practice. */ - val requestCount: Int + public val requestCount: Int get() = atomicRequestCount.get() /** The number of bytes of the POST body to keep in memory to the given limit. */ - var bodyLimit: Long = Long.MAX_VALUE + public var bodyLimit: Long = Long.MAX_VALUE - var serverSocketFactory: ServerSocketFactory? = null + public var serverSocketFactory: ServerSocketFactory? = null @Synchronized get() { if (field == null && started) { field = ServerSocketFactory.getDefault() // Build the default value lazily. @@ -150,16 +148,16 @@ class MockWebServer : Closeable { * Other dispatchers can be configured. They can vary the response based on timing or the content * of the request. */ - var dispatcher: Dispatcher = QueueDispatcher() + public var dispatcher: Dispatcher = QueueDispatcher() private var portField: Int = -1 - val port: Int + public val port: Int get() { before() return portField } - val hostName: String + public val hostName: String get() { before() return _inetSocketAddress!!.address.hostName @@ -167,7 +165,7 @@ class MockWebServer : Closeable { private var _inetSocketAddress: InetSocketAddress? = null - val inetSocketAddress: InetSocketAddress + public val inetSocketAddress: InetSocketAddress get() { before() return InetSocketAddress(hostName, portField) @@ -178,7 +176,7 @@ class MockWebServer : Closeable { * HTTP/2. This is true by default; set to false to disable negotiation and restrict connections * to HTTP/1.1. */ - var protocolNegotiationEnabled: Boolean = true + public var protocolNegotiationEnabled: Boolean = true /** * The protocols supported by ALPN on incoming HTTPS connections in order of preference. The list @@ -186,7 +184,7 @@ class MockWebServer : Closeable { * * This list is ignored when [negotiation is disabled][protocolNegotiationEnabled]. */ - var protocols: List = immutableListOf(Protocol.HTTP_2, Protocol.HTTP_1_1) + public var protocols: List = immutableListOf(Protocol.HTTP_2, Protocol.HTTP_1_1) set(value) { val protocolList = value.toImmutableList() require(Protocol.H2_PRIOR_KNOWLEDGE !in protocolList || protocolList.size == 1) { @@ -199,8 +197,8 @@ class MockWebServer : Closeable { field = protocolList } - var started: Boolean = false - private var shutdown: Boolean = false + public var started: Boolean = false + private var closed: Boolean = false @Synchronized private fun before() { if (started) return // Don't call start() in case we're already shut down. @@ -211,7 +209,7 @@ class MockWebServer : Closeable { } } - fun toProxyAddress(): Proxy { + public fun toProxyAddress(): Proxy { before() val address = InetSocketAddress(_inetSocketAddress!!.address.hostName, port) return Proxy(Proxy.Type.HTTP, address) @@ -222,7 +220,7 @@ class MockWebServer : Closeable { * * @param path the request path, such as "/". */ - fun url(path: String): HttpUrl = + public fun url(path: String): HttpUrl = HttpUrl .Builder() .scheme(if (sslSocketFactory != null) "https" else "http") @@ -234,7 +232,7 @@ class MockWebServer : Closeable { /** * Serve requests with HTTPS rather than otherwise. */ - fun useHttps(sslSocketFactory: SSLSocketFactory) { + public fun useHttps(sslSocketFactory: SSLSocketFactory) { this.sslSocketFactory = sslSocketFactory } @@ -243,7 +241,7 @@ class MockWebServer : Closeable { * authentication to another layer such as in an HTTP cookie or header. This is the default and * most common configuration. */ - fun noClientAuth() { + public fun noClientAuth() { this.clientAuth = CLIENT_AUTH_NONE } @@ -254,7 +252,7 @@ class MockWebServer : Closeable { * certificate at all! But if the client presents an untrusted certificate the handshake * will fail and no connection will be established. */ - fun requestClientAuth() { + public fun requestClientAuth() { this.clientAuth = CLIENT_AUTH_REQUESTED } @@ -264,7 +262,7 @@ class MockWebServer : Closeable { * proceed normally. If the client presents an untrusted certificate or no certificate at all the * handshake will fail and no connection will be established. */ - fun requireClientAuth() { + public fun requireClientAuth() { this.clientAuth = CLIENT_AUTH_REQUIRED } @@ -276,7 +274,7 @@ class MockWebServer : Closeable { * @return the head of the request queue */ @Throws(InterruptedException::class) - fun takeRequest(): RecordedRequest = requestQueue.take() + public fun takeRequest(): RecordedRequest = requestQueue.take() /** * Awaits the next HTTP request (waiting up to the specified wait time if necessary), removes it, @@ -288,7 +286,7 @@ class MockWebServer : Closeable { * @return the head of the request queue */ @Throws(InterruptedException::class) - fun takeRequest( + public fun takeRequest( timeout: Long, unit: TimeUnit, ): RecordedRequest? = requestQueue.poll(timeout, unit) @@ -301,7 +299,9 @@ class MockWebServer : Closeable { * @throws ClassCastException if the default dispatcher has been * replaced with [setDispatcher][dispatcher]. */ - fun enqueue(response: MockResponse) = (dispatcher as QueueDispatcher).enqueueResponse(response) + public fun enqueue(response: MockResponse) { + (dispatcher as QueueDispatcher).enqueue(response) + } /** * Starts the server on the loopback interface for the given port. @@ -311,7 +311,9 @@ class MockWebServer : Closeable { */ @Throws(IOException::class) @JvmOverloads - fun start(port: Int = 0) = start(InetAddress.getByName("localhost"), port) + public fun start(port: Int = 0) { + start(InetAddress.getByName("localhost"), port) + } /** * Starts the server on the given address and port. @@ -321,10 +323,12 @@ class MockWebServer : Closeable { * use port 0 to avoid flakiness when a specific port is unavailable. */ @Throws(IOException::class) - fun start( + public fun start( inetAddress: InetAddress, port: Int, - ) = start(InetSocketAddress(inetAddress, port)) + ) { + start(InetSocketAddress(inetAddress, port)) + } /** * Starts the server and binds to the given socket address. @@ -334,7 +338,7 @@ class MockWebServer : Closeable { @Synchronized @Throws(IOException::class) private fun start(inetSocketAddress: InetSocketAddress) { - check(!shutdown) { "shutdown() already called" } + check(!closed) { "shutdown() already called" } if (started) return started = true @@ -370,7 +374,7 @@ class MockWebServer : Closeable { httpConnection.next().closeQuietly() httpConnection.remove() } - dispatcher.shutdown() + dispatcher.close() } } @@ -396,11 +400,10 @@ class MockWebServer : Closeable { } } - @Synchronized @Throws(IOException::class) - fun shutdown() { - if (shutdown) return - shutdown = true + public override fun close() { + if (closed) return + closed = true if (!started) return // Nothing to shut down. val serverSocket = this.serverSocket ?: return // If this is null, start() must have failed. @@ -617,7 +620,7 @@ class MockWebServer : Closeable { } ShutdownInputAtEnd -> socket.shutdownInput() ShutdownOutputAtEnd -> socket.shutdownOutput() - ShutdownServerAfterResponse -> shutdown() + ShutdownServerAfterResponse -> close() else -> { } } @@ -926,10 +929,7 @@ class MockWebServer : Closeable { check(line.isEmpty()) { "Expected empty but was: $line" } } - override fun toString(): String = "MockWebServer[$portField]" - - @Throws(IOException::class) - override fun close() = shutdown() + public override fun toString(): String = "MockWebServer[$portField]" /** A buffer wrapper that drops data after [bodyLimit] bytes. */ private class TruncatingBuffer( @@ -1189,8 +1189,7 @@ class MockWebServer : Closeable { } } - @ExperimentalOkHttpApi - companion object { + private companion object { private const val CLIENT_AUTH_NONE = 0 private const val CLIENT_AUTH_REQUESTED = 1 private const val CLIENT_AUTH_REQUIRED = 2 diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/PushPromise.kt b/mockwebserver/src/main/kotlin/mockwebserver3/PushPromise.kt index 296a4fddcf29..f6c70c589c57 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/PushPromise.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/PushPromise.kt @@ -15,14 +15,12 @@ */ package mockwebserver3 -import okhttp3.ExperimentalOkHttpApi import okhttp3.Headers /** An HTTP request initiated by the server. */ -@ExperimentalOkHttpApi -class PushPromise( - val method: String, - val path: String, - val headers: Headers, - val response: MockResponse, +public class PushPromise( + public val method: String, + public val path: String, + public val headers: Headers, + public val response: MockResponse, ) diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt b/mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt index 146493186937..47945105e7cc 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt @@ -20,13 +20,12 @@ import java.net.HttpURLConnection.HTTP_UNAVAILABLE import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue import java.util.logging.Logger -import okhttp3.ExperimentalOkHttpApi /** - * Default dispatcher that processes a script of responses. Populate the script by calling [enqueueResponse]. + * Default dispatcher that processes a script of responses. Populate the script by calling + * [enqueue]. */ -@ExperimentalOkHttpApi -open class QueueDispatcher : Dispatcher() { +public open class QueueDispatcher : Dispatcher() { protected val responseQueue: BlockingQueue = LinkedBlockingQueue() private var failFastResponse: MockResponse? = null @@ -53,36 +52,35 @@ open class QueueDispatcher : Dispatcher() { return result } - override fun peek(): MockResponse = responseQueue.peek() ?: failFastResponse ?: super.peek() + public override fun peek(): MockResponse = responseQueue.peek() ?: failFastResponse ?: super.peek() - open fun enqueueResponse(response: MockResponse) { + public open fun enqueue(response: MockResponse) { responseQueue.add(response) } - open fun clear() { + public open fun clear() { responseQueue.clear() } - override fun shutdown() { + public override fun close() { responseQueue.add(DEAD_LETTER) } - open fun setFailFast(failFast: Boolean) { - val failFastResponse = - if (failFast) { - MockResponse(code = HttpURLConnection.HTTP_NOT_FOUND) - } else { - null - } - setFailFast(failFastResponse) + public open fun setFailFast(failFast: Boolean) { + setFailFast( + failFastResponse = + when { + failFast -> MockResponse(code = HttpURLConnection.HTTP_NOT_FOUND) + else -> null + }, + ) } - open fun setFailFast(failFastResponse: MockResponse?) { + public open fun setFailFast(failFastResponse: MockResponse?) { this.failFastResponse = failFastResponse } - @ExperimentalOkHttpApi - companion object { + private companion object { /** * Enqueued on shutdown to release threads waiting on [dispatch]. Note that this response * isn't transmitted because the connection is closed before this response is returned. diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt b/mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt index 359342d42070..e853be936c60 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt @@ -31,47 +31,47 @@ import okio.Buffer /** An HTTP request that came into the mock web server. */ @ExperimentalOkHttpApi -class RecordedRequest( - val requestLine: String, +public class RecordedRequest( + public val requestLine: String, /** All headers. */ - val headers: Headers, + public val headers: Headers, /** * The sizes of the chunks of this request's body, or an empty list if the request's body * was empty or unchunked. */ - val chunkSizes: List, + public val chunkSizes: List, /** The total size of the body of this POST request (before truncation).*/ - val bodySize: Long, + public val bodySize: Long, /** The body of this POST request. This may be truncated. */ - val body: Buffer, + public val body: Buffer, /** * The index of this request on its HTTP connection. Since a single HTTP connection may serve * multiple requests, each request is assigned its own sequence number. */ - val sequenceNumber: Int, + public val sequenceNumber: Int, socket: Socket, /** * The failure MockWebServer recorded when attempting to decode this request. If, for example, * the inbound request was truncated, this exception will be non-null. */ - val failure: IOException? = null, + public val failure: IOException? = null, ) { - val method: String? - val path: String? + public val method: String? + public val path: String? /** * The TLS handshake of the connection that carried this request, or null if the request was * received without TLS. */ - val handshake: Handshake? - val requestUrl: HttpUrl? + public val handshake: Handshake? + public val requestUrl: HttpUrl? /** * Returns the name of the server the client requested via the SNI (Server Name Indication) * attribute in the TLS handshake. Unlike the rest of the HTTP exchange, this name is sent in * cleartext and may be monitored or blocked by a proxy or other middlebox. */ - val handshakeServerNames: List + public val handshakeServerNames: List init { if (socket is SSLSocket) { @@ -115,5 +115,5 @@ class RecordedRequest( } } - override fun toString(): String = requestLine + public override fun toString(): String = requestLine } diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/SocketHandler.kt b/mockwebserver/src/main/kotlin/mockwebserver3/SocketHandler.kt index 1d2980454789..c7f74c3ee3f9 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/SocketHandler.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/SocketHandler.kt @@ -15,7 +15,6 @@ */ package mockwebserver3 -import okhttp3.ExperimentalOkHttpApi import okio.Socket /** @@ -24,7 +23,6 @@ import okio.Socket * * See [okhttp3.RequestBody.isDuplex]. */ -@ExperimentalOkHttpApi -interface SocketHandler { - fun handle(socket: Socket) +public interface SocketHandler { + public fun handle(socket: Socket) } diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/SocketPolicy.kt b/mockwebserver/src/main/kotlin/mockwebserver3/SocketPolicy.kt index f74df36c906b..5449c7df3da9 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/SocketPolicy.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/SocketPolicy.kt @@ -32,16 +32,16 @@ import okhttp3.ExperimentalOkHttpApi * server has closed the socket before follow up requests are made. */ @ExperimentalOkHttpApi -sealed interface SocketPolicy { +public sealed interface SocketPolicy { /** * Shutdown [MockWebServer] after writing response. */ - object ShutdownServerAfterResponse : SocketPolicy + public object ShutdownServerAfterResponse : SocketPolicy /** * Keep the socket open after the response. This is the default HTTP/1.1 behavior. */ - object KeepOpen : SocketPolicy + public object KeepOpen : SocketPolicy /** * Close the socket after the response. This is the default HTTP/1.0 behavior. For HTTP/2 @@ -51,75 +51,75 @@ sealed interface SocketPolicy { * * See [SocketPolicy] for reasons why this can cause test flakiness and how to avoid it. */ - object DisconnectAtEnd : SocketPolicy + public object DisconnectAtEnd : SocketPolicy /** * Request immediate close of connection without even reading the request. Use to simulate buggy * SSL servers closing connections in response to unrecognized TLS extensions. */ - object DisconnectAtStart : SocketPolicy + public object DisconnectAtStart : SocketPolicy /** * Close connection after reading the request but before writing the response. Use this to * simulate late connection pool failures. */ - object DisconnectAfterRequest : SocketPolicy + public object DisconnectAfterRequest : SocketPolicy /** * Half close connection (InputStream for client) after reading the request but before * writing the response. Use this to simulate late connection pool failures. */ - object HalfCloseAfterRequest : SocketPolicy + public object HalfCloseAfterRequest : SocketPolicy /** Close connection after reading half of the request body (if present). */ - object DisconnectDuringRequestBody : SocketPolicy + public object DisconnectDuringRequestBody : SocketPolicy /** Close connection after writing half of the response body (if present). */ - object DisconnectDuringResponseBody : SocketPolicy + public object DisconnectDuringResponseBody : SocketPolicy /** * Process the response without even attempting to reading the request body. For HTTP/2 this will * send [http2ErrorCode] after the response body or trailers. For HTTP/1 this will close the * socket after the response body or trailers. */ - class DoNotReadRequestBody( - val http2ErrorCode: Int = 0, + public class DoNotReadRequestBody( + public val http2ErrorCode: Int = 0, ) : SocketPolicy /** Don't trust the client during the SSL handshake. */ - object FailHandshake : SocketPolicy + public object FailHandshake : SocketPolicy /** * Shutdown the socket input after sending the response. For testing bad behavior. * * See [SocketPolicy] for reasons why this can cause test flakiness and how to avoid it. */ - object ShutdownInputAtEnd : SocketPolicy + public object ShutdownInputAtEnd : SocketPolicy /** * Shutdown the socket output after sending the response. For testing bad behavior. * * See [SocketPolicy] for reasons why this can cause test flakiness and how to avoid it. */ - object ShutdownOutputAtEnd : SocketPolicy + public object ShutdownOutputAtEnd : SocketPolicy /** * After accepting the connection and doing TLS (if configured) don't do HTTP/1.1 or HTTP/2 * framing. Ignore the socket completely until the server is shut down. */ - object StallSocketAtStart : SocketPolicy + public object StallSocketAtStart : SocketPolicy /** * Read the request but don't respond to it. Just keep the socket open. For testing read response * header timeout issue. */ - object NoResponse : SocketPolicy + public object NoResponse : SocketPolicy /** * Fail HTTP/2 requests without processing them by sending [http2ErrorCode]. */ @ExperimentalOkHttpApi - class ResetStreamAtStart( - val http2ErrorCode: Int = 0, + public class ResetStreamAtStart( + public val http2ErrorCode: Int = 0, ) : SocketPolicy } diff --git a/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt b/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt index 1772c279f952..ac076208872f 100644 --- a/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt +++ b/mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt @@ -80,7 +80,7 @@ class MockWebServerTest { @AfterEach fun tearDown() { - server.shutdown() + server.close() } @Test @@ -469,9 +469,9 @@ class MockWebServerTest { } @Test - fun shutdownWithoutStart() { + fun closeWithoutStart() { val server = MockWebServer() - server.shutdown() + server.close() } @Test @@ -481,10 +481,10 @@ class MockWebServerTest { } @Test - fun shutdownWithoutEnqueue() { + fun closeWithoutEnqueue() { val server = MockWebServer() server.start() - server.shutdown() + server.close() } @Test @@ -506,11 +506,11 @@ class MockWebServerTest { fun differentInstancesGetDifferentPorts() { val other = MockWebServer() assertThat(other.port).isNotEqualTo(server.port) - other.shutdown() + other.close() } @Test - fun shutdownWhileBlockedDispatching() { + fun closeWhileBlockedDispatching() { // Enqueue a request that'll cause MockWebServer to hang on QueueDispatcher.dispatch(). val connection = server.url("/").toUrl().openConnection() as HttpURLConnection connection.readTimeout = 500 @@ -521,8 +521,8 @@ class MockWebServerTest { // Expected. } - // Shutting down the server should unblock the dispatcher. - server.shutdown() + // Closing the server should unblock the dispatcher. + server.close() } @Test @@ -764,20 +764,20 @@ class MockWebServerTest { val server2 = MockWebServer() server2.start() server2.start() - server2.shutdown() + server2.close() } @Test - fun shutdownTwice() { + fun closeTwice() { val server2 = MockWebServer() server2.start() - server2.shutdown() + server2.close() try { server2.start() fail() } catch (expected: IllegalStateException) { // Expected. } - server2.shutdown() + server2.close() } } diff --git a/okhttp-testing-support/build.gradle.kts b/okhttp-testing-support/build.gradle.kts index 4e8699e6d149..88858825132e 100644 --- a/okhttp-testing-support/build.gradle.kts +++ b/okhttp-testing-support/build.gradle.kts @@ -5,6 +5,7 @@ plugins { dependencies { api(libs.squareup.okio) + api(projects.mockwebserver3) "friendsApi"(projects.okhttp) api(projects.okhttpTls) api(libs.assertk) diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/internal/duplex/MockSocketHandler.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt similarity index 98% rename from mockwebserver/src/main/kotlin/mockwebserver3/internal/duplex/MockSocketHandler.kt rename to okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt index e040f6ed911b..956a0e824f59 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/internal/duplex/MockSocketHandler.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package mockwebserver3.internal.duplex +package okhttp3.internal.duplex import java.io.IOException import java.util.concurrent.CountDownLatch diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt index 5c96eb5b0889..76d7c0f079ad 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt @@ -229,7 +229,7 @@ class CacheTest { } else { assertThat(cached).isNull() } - server.shutdown() // tearDown() isn't sufficient; this test starts multiple servers + server.close() // tearDown() isn't sufficient; this test starts multiple servers } private fun assertSubsequentResponseCached( @@ -260,7 +260,7 @@ class CacheTest { val cached = cacheGet(cache, request) assertThat(cached).isNotNull() cached!!.body.close() - server.shutdown() // tearDown() isn't sufficient; this test starts multiple servers + server.close() // tearDown() isn't sufficient; this test starts multiple servers } @Test diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt index 2b89d0ef3879..e75991565c84 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt @@ -234,7 +234,7 @@ class CallKotlinTest { val proxySelector = RecordingProxySelector() proxySelector.proxies.add(Proxy(Proxy.Type.HTTP, TestUtil.UNREACHABLE_ADDRESS_IPV4)) proxySelector.proxies.add(Proxy.NO_PROXY) - server.shutdown() + server.close() client = client diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt index 7abe08c6e948..d5bc8678d279 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt @@ -1262,9 +1262,9 @@ open class CallTest { return super.dispatch(request) } } - dispatcher.enqueueResponse(MockResponse(body = "seed connection pool")) - dispatcher.enqueueResponse(MockResponse(socketPolicy = DisconnectAfterRequest)) - dispatcher.enqueueResponse(MockResponse(body = "retry success")) + dispatcher.enqueue(MockResponse(body = "seed connection pool")) + dispatcher.enqueue(MockResponse(socketPolicy = DisconnectAfterRequest)) + dispatcher.enqueue(MockResponse(body = "retry success")) server.dispatcher = dispatcher listener = object : RecordingEventListener() { @@ -4159,7 +4159,7 @@ open class CallTest { @Test fun connectFails() { - server.shutdown() + server.close() executeSynchronously("/") .assertFailure(IOException::class.java) } @@ -4177,7 +4177,7 @@ open class CallTest { .addProxy(server2.toProxyAddress()) .addProxy(Proxy.NO_PROXY), ).build() - server2.shutdown() + server2.close() val request = Request( url = server.url("/"), diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt index 0e0fa6e462bf..634b1fea71eb 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt @@ -35,7 +35,6 @@ import java.util.concurrent.TimeUnit import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer -import mockwebserver3.internal.duplex.MockSocketHandler import okhttp3.CallEvent.FollowUpDecision import okhttp3.Credentials.basic import okhttp3.Headers.Companion.headersOf @@ -43,6 +42,7 @@ import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.TestUtil.assumeNotWindows import okhttp3.internal.RecordingOkAuthenticator import okhttp3.internal.duplex.AsyncRequestBody +import okhttp3.internal.duplex.MockSocketHandler import okhttp3.testing.PlatformRule import okio.BufferedSink import org.junit.jupiter.api.AfterEach diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt index 09ac410a2446..e522e7984c7e 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt @@ -110,8 +110,8 @@ class FastFallbackTest { @AfterEach internal fun tearDown() { - serverIpv4.shutdown() - serverIpv6.shutdown() + serverIpv4.close() + serverIpv6.close() } @Test @@ -163,7 +163,7 @@ class FastFallbackTest { @Test fun reachesIpv4WhenIpv6IsDown() { - serverIpv6.shutdown() + serverIpv6.close() serverIpv4.enqueue( MockResponse(body = "hello from IPv4"), ) @@ -180,7 +180,7 @@ class FastFallbackTest { @Test fun reachesIpv6WhenIpv4IsDown() { - serverIpv4.shutdown() + serverIpv4.close() serverIpv6.enqueue( MockResponse(body = "hello from IPv6"), ) @@ -197,8 +197,8 @@ class FastFallbackTest { @Test fun failsWhenBothServersAreDown() { - serverIpv4.shutdown() - serverIpv6.shutdown() + serverIpv4.close() + serverIpv6.close() val call = client.newCall(Request(url)) assertFailsWith { @@ -218,7 +218,7 @@ class FastFallbackTest { TestUtil.UNREACHABLE_ADDRESS_IPV6.address, localhostIpv4, ) - serverIpv6.shutdown() + serverIpv6.close() serverIpv4.enqueue( MockResponse(body = "hello from IPv4"), ) @@ -239,7 +239,7 @@ class FastFallbackTest { TestUtil.UNREACHABLE_ADDRESS_IPV4.address, localhostIpv6, ) - serverIpv4.shutdown() + serverIpv4.close() serverIpv6.enqueue( MockResponse(body = "hello from IPv6"), ) diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt index 4f3cd7bb26ad..842a74f0df74 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt @@ -69,7 +69,7 @@ class InterceptorTest { @Test fun applicationInterceptorsCanShortCircuitResponses() { - server.shutdown() // Accept no connections. + server.close() // Accept no connections. val request = Request .Builder() diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt index 9d311bc3a9be..00ab9ee06410 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt @@ -314,7 +314,7 @@ class RouteFailureTest { @ParameterizedTest @ValueSource(booleans = [false, true]) - fun proxyMoveTest(cleanShutdown: Boolean) { + fun proxyMoveTest(cleanClose: Boolean) { // Define a single Proxy at myproxy:8008 that will artificially move during the test val proxySelector = RecordingProxySelector() val socketAddress = InetSocketAddress.createUnresolved("myproxy", 8008) @@ -348,9 +348,9 @@ class RouteFailureTest { println("server1.requestCount ${server1.requestCount}") assertThat(server1.requestCount).isEqualTo(1) - // Shutdown the proxy server - if (cleanShutdown) { - server1.shutdown() + // Close the proxy server + if (cleanClose) { + server1.close() } // Now redirect with DNS to proxyServer2 @@ -362,7 +362,7 @@ class RouteFailureTest { executeSynchronously(request) .apply { // We may have a single failed request if not clean shutdown - if (cleanShutdown) { + if (cleanClose) { assertSuccessful() assertCode(200) diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt index 30fc819a9730..fa4ea9c54064 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt @@ -273,7 +273,7 @@ class URLConnectionTest { @Test fun connectRetriesUntilConnectedOrFailed() { val request = newRequest("/foo") - server.shutdown() + server.close() assertFailsWith { getResponse(request) } @@ -301,7 +301,7 @@ class URLConnectionTest { .addProxy(server2.toProxyAddress()) .addProxy(Proxy.NO_PROXY), ).build() - server2.shutdown() + server2.close() val request = Request( url = server.url("/def"), @@ -3297,7 +3297,7 @@ class URLConnectionTest { val source1 = connection1.body.source() source1.timeout().timeout(100, TimeUnit.MILLISECONDS) assertThat(readAscii(source1.inputStream(), Int.MAX_VALUE)).isEqualTo("ABC") - server.shutdown() + server.close() assertFailsWith { getResponse(newRequest("/")) } diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt index ea3fa0ea8eeb..0ee2f1e56d35 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt @@ -1229,14 +1229,14 @@ class HttpOverHttp2Test { CountDownLatch(0), ) val dispatcher = RespondAfterCancelDispatcher(responseDequeuedLatches, requestCanceledLatches) - dispatcher.enqueueResponse( + dispatcher.enqueue( MockResponse .Builder() .bodyDelay(10, TimeUnit.SECONDS) .body("abc") .build(), ) - dispatcher.enqueueResponse( + dispatcher.enqueue( MockResponse(body = "def"), ) server.dispatcher = dispatcher @@ -1275,21 +1275,21 @@ class HttpOverHttp2Test { CountDownLatch(0), ) val dispatcher = RespondAfterCancelDispatcher(responseDequeuedLatches, requestCanceledLatches) - dispatcher.enqueueResponse( + dispatcher.enqueue( MockResponse .Builder() .bodyDelay(10, TimeUnit.SECONDS) .body("abc") .build(), ) - dispatcher.enqueueResponse( + dispatcher.enqueue( MockResponse .Builder() .bodyDelay(10, TimeUnit.SECONDS) .body("def") .build(), ) - dispatcher.enqueueResponse( + dispatcher.enqueue( MockResponse(body = "ghi"), ) server.dispatcher = dispatcher @@ -2094,20 +2094,20 @@ class HttpOverHttp2Test { assumeTrue(protocol === Protocol.HTTP_2) server.useHttps(handshakeCertificates.sslSocketFactory()) val queueDispatcher = QueueDispatcher() - queueDispatcher.enqueueResponse( + queueDispatcher.enqueue( MockResponse .Builder() .inTunnel() .build(), ) - queueDispatcher.enqueueResponse( + queueDispatcher.enqueue( MockResponse .Builder() .inTunnel() .build(), ) - queueDispatcher.enqueueResponse(MockResponse(body = "call2 response")) - queueDispatcher.enqueueResponse(MockResponse(body = "call1 response")) + queueDispatcher.enqueue(MockResponse(body = "call2 response")) + queueDispatcher.enqueue(MockResponse(body = "call1 response")) // We use a re-entrant dispatcher to initiate one HTTPS connection while the other is in flight. server.dispatcher = @@ -2138,8 +2138,8 @@ class HttpOverHttp2Test { override fun peek(): MockResponse = queueDispatcher.peek() - override fun shutdown() { - queueDispatcher.shutdown() + override fun close() { + queueDispatcher.close() } } client = @@ -2266,7 +2266,7 @@ class HttpOverHttp2Test { ) { try { if (callCount++ == 1) { - server.shutdown() + server.close() } } catch (e: IOException) { fail("")