forked from square/okhttp
-
Notifications
You must be signed in to change notification settings - Fork 3
/
CallKotlinTest.kt
282 lines (241 loc) · 8.36 KB
/
CallKotlinTest.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.IOException
import java.net.Proxy
import java.security.cert.X509Certificate
import java.time.Duration
import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy
import okhttp3.Headers.Companion.headersOf
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.TestUtil.assertSuppressed
import okhttp3.internal.DoubleInetAddressDns
import okhttp3.internal.connection.RealConnection
import okhttp3.internal.connection.RealConnection.Companion.IDLE_CONNECTION_HEALTHY_NS
import okhttp3.internal.http.RecordingProxySelector
import okhttp3.testing.Flaky
import okhttp3.testing.PlatformRule
import okhttp3.tls.internal.TlsUtil.localhost
import okio.BufferedSink
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertEquals
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 org.junitpioneer.jupiter.RetryingTest
@Timeout(30)
class CallKotlinTest {
@JvmField @RegisterExtension val platform = PlatformRule()
@JvmField @RegisterExtension val clientTestRule = OkHttpClientTestRule().apply {
recordFrames = true
recordSslDebug = true
}
private var client = clientTestRule.newClient()
private val handshakeCertificates = localhost()
private lateinit var server: MockWebServer
@BeforeEach
fun setUp(server: MockWebServer) {
this.server = server
platform.assumeNotBouncyCastle()
}
@Test
fun legalToExecuteTwiceCloning() {
server.enqueue(MockResponse().setBody("abc"))
server.enqueue(MockResponse().setBody("def"))
val request = Request(server.url("/"))
val call = client.newCall(request)
val response1 = call.execute()
val cloned = call.clone()
val response2 = cloned.execute()
assertThat("abc").isEqualTo(response1.body.string())
assertThat("def").isEqualTo(response2.body.string())
}
@Test
@Flaky
fun testMockWebserverRequest() {
enableTls()
server.enqueue(MockResponse().setBody("abc"))
val request = Request.Builder().url(server.url("/")).build()
val response = client.newCall(request).execute()
response.use {
assertEquals(200, response.code)
assertEquals("CN=localhost",
(response.handshake!!.peerCertificates.single() as X509Certificate).subjectDN.name)
}
}
private fun enableTls() {
client = client.newBuilder()
.sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager)
.build()
server.useHttps(handshakeCertificates.sslSocketFactory())
}
@RetryingTest(5)
@Flaky
fun testHeadAfterPut() {
class ErringRequestBody : RequestBody() {
override fun contentType(): MediaType {
return "application/xml".toMediaType()
}
override fun writeTo(sink: BufferedSink) {
sink.writeUtf8("<el")
sink.flush()
throw IOException("failed to stream the XML")
}
}
class ValidRequestBody : RequestBody() {
override fun contentType(): MediaType {
return "application/xml".toMediaType()
}
override fun writeTo(sink: BufferedSink) {
sink.writeUtf8("<element/>")
sink.flush()
}
}
server.enqueue(MockResponse().apply {
setResponseCode(201)
})
server.enqueue(MockResponse().apply {
setResponseCode(204)
})
server.enqueue(MockResponse().apply {
setResponseCode(204)
})
val endpointUrl = server.url("/endpoint")
var request = Request.Builder()
.url(endpointUrl)
.header("Content-Type", "application/xml")
.put(ValidRequestBody())
.build()
client.newCall(request).execute().use {
assertEquals(201, it.code)
}
request = Request.Builder()
.url(endpointUrl)
.head()
.build()
client.newCall(request).execute().use {
assertEquals(204, it.code)
}
request = Request.Builder()
.url(endpointUrl)
.header("Content-Type", "application/xml")
.put(ErringRequestBody())
.build()
try {
client.newCall(request).execute()
fail("test should always throw exception")
} catch (_: IOException) {
// NOTE: expected
}
request = Request.Builder()
.url(endpointUrl)
.head()
.build()
client.newCall(request).execute().use {
assertEquals(204, it.code)
}
}
@Test
fun staleConnectionNotReusedForNonIdempotentRequest() {
// Capture the connection so that we can later make it stale.
var connection: RealConnection? = null
client = client.newBuilder()
.addNetworkInterceptor(Interceptor { chain ->
connection = chain.connection() as RealConnection
chain.proceed(chain.request())
})
.build()
server.enqueue(MockResponse().setBody("a")
.setSocketPolicy(SocketPolicy.SHUTDOWN_OUTPUT_AT_END))
server.enqueue(MockResponse().setBody("b"))
val requestA = Request(server.url("/"))
val responseA = client.newCall(requestA).execute()
assertThat(responseA.body.string()).isEqualTo("a")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Give the socket a chance to become stale.
connection!!.idleAtNs -= IDLE_CONNECTION_HEALTHY_NS
Thread.sleep(250)
val requestB = Request(
url = server.url("/"),
body = "b".toRequestBody("text/plain".toMediaType()),
)
val responseB = client.newCall(requestB).execute()
assertThat(responseB.body.string()).isEqualTo("b")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
}
/** Confirm suppressed exceptions that occur while connecting are returned. */
@Test fun connectExceptionsAreReturnedAsSuppressed() {
val proxySelector = RecordingProxySelector()
proxySelector.proxies.add(Proxy(Proxy.Type.HTTP, TestUtil.UNREACHABLE_ADDRESS_IPV4))
proxySelector.proxies.add(Proxy.NO_PROXY)
server.shutdown()
client = client.newBuilder()
.proxySelector(proxySelector)
.readTimeout(Duration.ofMillis(100))
.connectTimeout(Duration.ofMillis(100))
.build()
val request = Request(server.url("/"))
try {
client.newCall(request).execute()
fail("")
} catch (expected: IOException) {
expected.assertSuppressed {
val suppressed = it.single()
assertThat(suppressed).isInstanceOf(IOException::class.java)
assertThat(suppressed).isNotSameAs(expected)
}
}
}
/** Confirm suppressed exceptions that occur after connecting are returned. */
@Test fun httpExceptionsAreReturnedAsSuppressed() {
server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START))
server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START))
client = client.newBuilder()
.dns(DoubleInetAddressDns()) // Two routes so we get two failures.
.build()
val request = Request(server.url("/"))
try {
client.newCall(request).execute()
fail("")
} catch (expected: IOException) {
expected.assertSuppressed {
val suppressed = it.single()
assertThat(suppressed).isInstanceOf(IOException::class.java)
assertThat(suppressed).isNotSameAs(expected)
}
}
}
@Test
fun responseRequestIsLastRedirect() {
server.enqueue(
MockResponse()
.setResponseCode(302)
.addHeader("Location: /b")
)
server.enqueue(MockResponse())
val request = Request(server.url("/"))
val call = client.newCall(request)
val response = call.execute()
assertThat(response.request.url.encodedPath).isEqualTo("/b")
assertThat(response.request.headers).isEqualTo(headersOf())
}
}