/
CallTest.kt
4691 lines (4361 loc) · 142 KB
/
CallTest.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.containsExactly
import assertk.assertions.doesNotContain
import assertk.assertions.hasMessage
import assertk.assertions.isCloseTo
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import assertk.assertions.isFalse
import assertk.assertions.isLessThan
import assertk.assertions.isNotEmpty
import assertk.assertions.isNotNull
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
import java.net.CookieManager
import java.net.CookiePolicy
import java.net.HttpCookie
import java.net.HttpURLConnection
import java.net.InetAddress
import java.net.ProtocolException
import java.net.Proxy
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.net.UnknownServiceException
import java.time.Duration
import java.util.Arrays
import java.util.concurrent.BlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import javax.net.ssl.SSLException
import javax.net.ssl.SSLHandshakeException
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
import mockwebserver3.RecordedRequest
import mockwebserver3.SocketPolicy.DisconnectAfterRequest
import mockwebserver3.SocketPolicy.DisconnectAtEnd
import mockwebserver3.SocketPolicy.DisconnectAtStart
import mockwebserver3.SocketPolicy.FailHandshake
import mockwebserver3.SocketPolicy.HalfCloseAfterRequest
import mockwebserver3.SocketPolicy.NoResponse
import mockwebserver3.SocketPolicy.StallSocketAtStart
import mockwebserver3.junit5.internal.MockWebServerInstance
import okhttp3.CallEvent.CallEnd
import okhttp3.CallEvent.ConnectStart
import okhttp3.CallEvent.ConnectionAcquired
import okhttp3.CallEvent.ConnectionReleased
import okhttp3.CallEvent.ResponseFailed
import okhttp3.CertificatePinner.Companion.pin
import okhttp3.Credentials.basic
import okhttp3.Headers.Companion.headersOf
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody.Companion.asResponseBody
import okhttp3.TestUtil.assumeNotWindows
import okhttp3.TestUtil.awaitGarbageCollection
import okhttp3.internal.DoubleInetAddressDns
import okhttp3.internal.RecordingOkAuthenticator
import okhttp3.internal.USER_AGENT
import okhttp3.internal.addHeaderLenient
import okhttp3.internal.closeQuietly
import okhttp3.internal.http.HTTP_EARLY_HINTS
import okhttp3.internal.http.HTTP_PROCESSING
import okhttp3.internal.http.RecordingProxySelector
import okhttp3.java.net.cookiejar.JavaNetCookieJar
import okhttp3.okio.LoggingFilesystem
import okhttp3.testing.Flaky
import okhttp3.testing.PlatformRule
import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.HeldCertificate
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSource
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.Assumptions.assumeFalse
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.extension.RegisterExtension
import org.junitpioneer.jupiter.RetryingTest
@Timeout(30)
open class CallTest {
private val fileSystem = FakeFileSystem()
@RegisterExtension
val platform = PlatformRule()
@RegisterExtension
val clientTestRule = OkHttpClientTestRule()
@RegisterExtension
val testLogHandler = TestLogHandler(OkHttpClient::class.java)
private lateinit var server: MockWebServer
private lateinit var server2: MockWebServer
private var listener = RecordingEventListener()
private val handshakeCertificates = platform.localhostHandshakeCertificates()
private var client =
clientTestRule.newClientBuilder()
.eventListenerFactory(clientTestRule.wrap(listener))
.build()
private val callback = RecordingCallback()
private val cache =
Cache(
fileSystem = LoggingFilesystem(fileSystem),
directory = "/cache".toPath(),
maxSize = Int.MAX_VALUE.toLong(),
)
@BeforeEach
fun setUp(
server: MockWebServer,
@MockWebServerInstance("server2") server2: MockWebServer,
) {
this.server = server
this.server2 = server2
platform.assumeNotOpenJSSE()
}
@AfterEach
fun tearDown() {
cache.close()
fileSystem.checkNoOpenFiles()
}
@Test
fun get() {
server.enqueue(
MockResponse.Builder()
.body("abc")
.clearHeaders()
.addHeader("content-type: text/plain")
.addHeader("content-length", "3")
.build(),
)
val sentAt = System.currentTimeMillis()
val recordedResponse = executeSynchronously("/", "User-Agent", "SyncApiTest")
val receivedAt = System.currentTimeMillis()
recordedResponse.assertCode(200)
.assertSuccessful()
.assertHeaders(
Headers.Builder()
.add("content-type", "text/plain")
.add("content-length", "3")
.build(),
)
.assertBody("abc")
.assertSentRequestAtMillis(sentAt, receivedAt)
.assertReceivedResponseAtMillis(sentAt, receivedAt)
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("GET")
assertThat(recordedRequest.headers["User-Agent"]).isEqualTo("SyncApiTest")
assertThat(recordedRequest.body.size).isEqualTo(0)
assertThat(recordedRequest.headers["Content-Length"]).isNull()
}
@Test
fun buildRequestUsingHttpUrl() {
server.enqueue(MockResponse())
executeSynchronously("/").assertSuccessful()
}
@Test
fun invalidScheme() {
val requestBuilder = Request.Builder()
assertFailsWith<IllegalArgumentException> {
requestBuilder.url("ftp://hostname/path")
}.also { expected ->
assertThat(expected.message).isEqualTo("Expected URL scheme 'http' or 'https' but was 'ftp'")
}
}
@Test
fun invalidPort() {
val requestBuilder = Request.Builder()
assertFailsWith<IllegalArgumentException> {
requestBuilder.url("http://localhost:65536/")
}.also { expected ->
assertThat(expected.message).isEqualTo("Invalid URL port: \"65536\"")
}
}
@Test
fun getReturns500() {
server.enqueue(MockResponse(code = 500))
executeSynchronously("/")
.assertCode(500)
.assertNotSuccessful()
}
@Test
fun get_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
get()
}
@Test
fun get_HTTPS() {
enableTls()
get()
}
@Test
fun repeatedHeaderNames() {
server.enqueue(
MockResponse(
headers =
headersOf(
"B",
"123",
"B",
"234",
),
),
)
executeSynchronously("/", "A", "345", "A", "456")
.assertCode(200)
.assertHeader("B", "123", "234")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.headers.values("A")).containsExactly("345", "456")
}
@Test
fun repeatedHeaderNames_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
repeatedHeaderNames()
}
@Test
fun getWithRequestBody() {
server.enqueue(MockResponse())
assertFailsWith<IllegalArgumentException> {
Request.Builder().method("GET", "abc".toRequestBody("text/plain".toMediaType()))
}
}
@Test
fun head() {
server.enqueue(
MockResponse(
headers = headersOf("Content-Type", "text/plain"),
),
)
val request =
Request.Builder()
.url(server.url("/"))
.head()
.header("User-Agent", "SyncApiTest")
.build()
executeSynchronously(request)
.assertCode(200)
.assertHeader("Content-Type", "text/plain")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("HEAD")
assertThat(recordedRequest.headers["User-Agent"]).isEqualTo("SyncApiTest")
assertThat(recordedRequest.body.size).isEqualTo(0)
assertThat(recordedRequest.headers["Content-Length"]).isNull()
}
@Test
fun headResponseContentLengthIsIgnored() {
server.enqueue(
MockResponse.Builder()
.clearHeaders()
.addHeader("Content-Length", "100")
.build(),
)
server.enqueue(
MockResponse(body = "abc"),
)
val headRequest =
Request.Builder()
.url(server.url("/"))
.head()
.build()
val response = client.newCall(headRequest).execute()
assertThat(response.code).isEqualTo(200)
assertArrayEquals(ByteArray(0), response.body.bytes())
val getRequest = Request(server.url("/"))
executeSynchronously(getRequest)
.assertCode(200)
.assertBody("abc")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@Test
fun headResponseContentEncodingIsIgnored() {
server.enqueue(
MockResponse.Builder()
.clearHeaders()
.addHeader("Content-Encoding", "chunked")
.build(),
)
server.enqueue(MockResponse(body = "abc"))
val headRequest =
Request.Builder()
.url(server.url("/"))
.head()
.build()
executeSynchronously(headRequest)
.assertCode(200)
.assertHeader("Content-Encoding", "chunked")
.assertBody("")
val getRequest = Request(server.url("/"))
executeSynchronously(getRequest)
.assertCode(200)
.assertBody("abc")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@Test
fun head_HTTPS() {
enableTls()
head()
}
@Test
fun head_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
head()
}
@Test
fun post() {
server.enqueue(MockResponse(body = "abc"))
val request =
Request(
url = server.url("/"),
body = "def".toRequestBody("text/plain".toMediaType()),
)
executeSynchronously(request)
.assertCode(200)
.assertBody("abc")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("POST")
assertThat(recordedRequest.body.readUtf8()).isEqualTo("def")
assertThat(recordedRequest.headers["Content-Length"]).isEqualTo("3")
assertThat(recordedRequest.headers["Content-Type"]).isEqualTo("text/plain; charset=utf-8")
}
@Test
fun post_HTTPS() {
enableTls()
post()
}
@Test
fun post_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
post()
}
@Test
fun postZeroLength() {
server.enqueue(MockResponse(body = "abc"))
val request =
Request.Builder()
.url(server.url("/"))
.method("POST", ByteArray(0).toRequestBody(null))
.build()
executeSynchronously(request)
.assertCode(200)
.assertBody("abc")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("POST")
assertThat(recordedRequest.body.size).isEqualTo(0)
assertThat(recordedRequest.headers["Content-Length"]).isEqualTo("0")
assertThat(recordedRequest.headers["Content-Type"]).isNull()
}
@Test
fun postZerolength_HTTPS() {
enableTls()
postZeroLength()
}
@Test
fun postZerolength_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
postZeroLength()
}
@Test
fun postBodyRetransmittedAfterAuthorizationFail() {
postBodyRetransmittedAfterAuthorizationFail("abc")
}
@Test
fun postBodyRetransmittedAfterAuthorizationFail_HTTPS() {
enableTls()
postBodyRetransmittedAfterAuthorizationFail("abc")
}
@Test
fun postBodyRetransmittedAfterAuthorizationFail_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
postBodyRetransmittedAfterAuthorizationFail("abc")
}
/** Don't explode when resending an empty post. https://github.com/square/okhttp/issues/1131 */
@Test
fun postEmptyBodyRetransmittedAfterAuthorizationFail() {
postBodyRetransmittedAfterAuthorizationFail("")
}
@Test
fun postEmptyBodyRetransmittedAfterAuthorizationFail_HTTPS() {
enableTls()
postBodyRetransmittedAfterAuthorizationFail("")
}
@Test
fun postEmptyBodyRetransmittedAfterAuthorizationFail_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
postBodyRetransmittedAfterAuthorizationFail("")
}
private fun postBodyRetransmittedAfterAuthorizationFail(body: String) {
server.enqueue(MockResponse(code = 401))
server.enqueue(MockResponse())
val request =
Request.Builder()
.url(server.url("/"))
.method("POST", body.toRequestBody(null))
.build()
val credential = basic("jesse", "secret")
client =
client.newBuilder()
.authenticator(RecordingOkAuthenticator(credential, null))
.build()
val response = client.newCall(request).execute()
assertThat(response.code).isEqualTo(200)
response.body.close()
val recordedRequest1 = server.takeRequest()
assertThat(recordedRequest1.method).isEqualTo("POST")
assertThat(recordedRequest1.body.readUtf8()).isEqualTo(body)
assertThat(recordedRequest1.headers["Authorization"]).isNull()
val recordedRequest2 = server.takeRequest()
assertThat(recordedRequest2.method).isEqualTo("POST")
assertThat(recordedRequest2.body.readUtf8()).isEqualTo(body)
assertThat(recordedRequest2.headers["Authorization"]).isEqualTo(credential)
}
@Test
fun attemptAuthorization20Times() {
for (i in 0..19) {
server.enqueue(MockResponse(code = 401))
}
server.enqueue(MockResponse(body = "Success!"))
val credential = basic("jesse", "secret")
client =
client.newBuilder()
.authenticator(RecordingOkAuthenticator(credential, null))
.build()
executeSynchronously("/")
.assertCode(200)
.assertBody("Success!")
}
@Test
fun doesNotAttemptAuthorization21Times() {
for (i in 0..20) {
server.enqueue(MockResponse(code = 401))
}
val credential = basic("jesse", "secret")
client =
client.newBuilder()
.authenticator(RecordingOkAuthenticator(credential, null))
.build()
assertFailsWith<IOException> {
client.newCall(Request.Builder().url(server.url("/0")).build()).execute()
}.also { expected ->
assertThat(expected.message).isEqualTo("Too many follow-up requests: 21")
}
}
/**
* We had a bug where we were passing a null route to the authenticator.
* https://github.com/square/okhttp/issues/3809
*/
@Test
fun authenticateWithNoConnection() {
server.enqueue(
MockResponse(
code = 401,
headers = headersOf("Connection", "close"),
socketPolicy = DisconnectAtEnd,
),
)
val authenticator = RecordingOkAuthenticator(null, null)
client =
client.newBuilder()
.authenticator(authenticator)
.build()
executeSynchronously("/")
.assertCode(401)
assertThat(authenticator.onlyRoute()).isNotNull()
}
@Test
fun delete() {
server.enqueue(MockResponse(body = "abc"))
val request =
Request.Builder()
.url(server.url("/"))
.delete()
.build()
executeSynchronously(request)
.assertCode(200)
.assertBody("abc")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("DELETE")
assertThat(recordedRequest.body.size).isEqualTo(0)
assertThat(recordedRequest.headers["Content-Length"]).isEqualTo("0")
assertThat(recordedRequest.headers["Content-Type"]).isNull()
}
@Test
fun delete_HTTPS() {
enableTls()
delete()
}
@Test
fun delete_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
delete()
}
@Test
fun deleteWithRequestBody() {
server.enqueue(MockResponse(body = "abc"))
val request =
Request.Builder()
.url(server.url("/"))
.method("DELETE", "def".toRequestBody("text/plain".toMediaType()))
.build()
executeSynchronously(request)
.assertCode(200)
.assertBody("abc")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("DELETE")
assertThat(recordedRequest.body.readUtf8()).isEqualTo("def")
}
@Test
fun put() {
server.enqueue(MockResponse(body = "abc"))
val request =
Request.Builder()
.url(server.url("/"))
.put("def".toRequestBody("text/plain".toMediaType()))
.build()
executeSynchronously(request)
.assertCode(200)
.assertBody("abc")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("PUT")
assertThat(recordedRequest.body.readUtf8()).isEqualTo("def")
assertThat(recordedRequest.headers["Content-Length"]).isEqualTo("3")
assertThat(recordedRequest.headers["Content-Type"]).isEqualTo(
"text/plain; charset=utf-8",
)
}
@Test
fun put_HTTPS() {
enableTls()
put()
}
@Test
fun put_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
put()
}
@Test
fun patch() {
server.enqueue(MockResponse(body = "abc"))
val request =
Request.Builder()
.url(server.url("/"))
.patch("def".toRequestBody("text/plain".toMediaType()))
.build()
executeSynchronously(request)
.assertCode(200)
.assertBody("abc")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("PATCH")
assertThat(recordedRequest.body.readUtf8()).isEqualTo("def")
assertThat(recordedRequest.headers["Content-Length"]).isEqualTo("3")
assertThat(recordedRequest.headers["Content-Type"]).isEqualTo("text/plain; charset=utf-8")
}
@Test
fun patch_HTTP_2() {
enableProtocol(Protocol.HTTP_2)
patch()
}
@Test
fun patch_HTTPS() {
enableTls()
patch()
}
@Test
fun customMethodWithBody() {
server.enqueue(MockResponse(body = "abc"))
val request =
Request.Builder()
.url(server.url("/"))
.method("CUSTOM", "def".toRequestBody("text/plain".toMediaType()))
.build()
executeSynchronously(request)
.assertCode(200)
.assertBody("abc")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.method).isEqualTo("CUSTOM")
assertThat(recordedRequest.body.readUtf8()).isEqualTo("def")
assertThat(recordedRequest.headers["Content-Length"]).isEqualTo("3")
assertThat(recordedRequest.headers["Content-Type"])
.isEqualTo("text/plain; charset=utf-8")
}
@Test
fun unspecifiedRequestBodyContentTypeDoesNotGetDefault() {
server.enqueue(MockResponse())
val request =
Request.Builder()
.url(server.url("/"))
.method("POST", "abc".toRequestBody(null))
.build()
executeSynchronously(request).assertCode(200)
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.headers["Content-Type"]).isNull()
assertThat(recordedRequest.headers["Content-Length"]).isEqualTo("3")
assertThat(recordedRequest.body.readUtf8()).isEqualTo("abc")
}
@Test
fun illegalToExecuteTwice() {
server.enqueue(
MockResponse(
headers = headersOf("Content-Type", "text/plain"),
body = "abc",
),
)
val request =
Request.Builder()
.url(server.url("/"))
.header("User-Agent", "SyncApiTest")
.build()
val call = client.newCall(request)
val response = call.execute()
response.body.close()
assertFailsWith<IllegalStateException> {
call.execute()
}.also { expected ->
assertThat(expected.message).isEqualTo("Already Executed")
}
assertFailsWith<IllegalStateException> {
call.enqueue(callback)
}.also { expected ->
assertThat(expected.message).isEqualTo("Already Executed")
}
assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest")
}
@Test
fun illegalToExecuteTwice_Async() {
server.enqueue(
MockResponse(
headers = headersOf("Content-Type", "text/plain"),
body = "abc",
),
)
val request =
Request.Builder()
.url(server.url("/"))
.header("User-Agent", "SyncApiTest")
.build()
val call = client.newCall(request)
call.enqueue(callback)
assertFailsWith<IllegalStateException> {
call.execute()
}.also { expected ->
assertThat(expected.message).isEqualTo("Already Executed")
}
assertFailsWith<IllegalStateException> {
call.enqueue(callback)
}.also { expected ->
assertThat(expected.message).isEqualTo("Already Executed")
}
assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("SyncApiTest")
callback.await(request.url).assertSuccessful()
}
@Test
fun legalToExecuteTwiceCloning() {
server.enqueue(MockResponse(body = "abc"))
server.enqueue(MockResponse(body = "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
fun legalToExecuteTwiceCloning_Async() {
server.enqueue(MockResponse(body = "abc"))
server.enqueue(MockResponse(body = "def"))
val request = Request(server.url("/"))
val call = client.newCall(request)
call.enqueue(callback)
val cloned = call.clone()
cloned.enqueue(callback)
val firstResponse = callback.await(request.url).assertSuccessful()
val secondResponse = callback.await(request.url).assertSuccessful()
val bodies: MutableSet<String?> = LinkedHashSet()
bodies.add(firstResponse.body)
bodies.add(secondResponse.body)
assertThat(bodies).contains("abc")
assertThat(bodies).contains("def")
}
@Test
fun get_Async() {
server.enqueue(
MockResponse(
headers = headersOf("Content-Type", "text/plain"),
body = "abc",
),
)
val request =
Request.Builder()
.url(server.url("/"))
.header("User-Agent", "AsyncApiTest")
.build()
client.newCall(request).enqueue(callback)
callback.await(request.url)
.assertCode(200)
.assertHeader("Content-Type", "text/plain")
.assertBody("abc")
assertThat(server.takeRequest().headers["User-Agent"]).isEqualTo("AsyncApiTest")
}
@Test
fun exceptionThrownByOnResponseIsRedactedAndLogged() {
server.enqueue(MockResponse())
val request = Request(server.url("/secret"))
client.newCall(request).enqueue(
object : Callback {
override fun onFailure(
call: Call,
e: IOException,
) {
fail("")
}
override fun onResponse(
call: Call,
response: Response,
) {
throw IOException("a")
}
},
)
assertThat(testLogHandler.take())
.isEqualTo("INFO: Callback failure for call to " + server.url("/") + "...")
}
@Test
fun connectionPooling() {
server.enqueue(MockResponse(body = "abc"))
server.enqueue(MockResponse(body = "def"))
server.enqueue(MockResponse(body = "ghi"))
executeSynchronously("/a").assertBody("abc")
executeSynchronously("/b").assertBody("def")
executeSynchronously("/c").assertBody("ghi")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
}
/**
* Each OkHttpClient used to get its own instance of NullProxySelector, and because these weren't
* equal their connections weren't pooled. That's a nasty performance bug!
*
* https://github.com/square/okhttp/issues/5519
*/
@Test
fun connectionPoolingWithFreshClientSamePool() {
server.enqueue(MockResponse(body = "abc"))
server.enqueue(MockResponse(body = "def"))
server.enqueue(MockResponse(body = "ghi"))
client =
OkHttpClient.Builder()
.connectionPool(client.connectionPool)
.proxy(server.toProxyAddress())
.build()
executeSynchronously("/a").assertBody("abc")
client =
OkHttpClient.Builder()
.connectionPool(client.connectionPool)
.proxy(server.toProxyAddress())
.build()
executeSynchronously("/b").assertBody("def")
client =
OkHttpClient.Builder()
.connectionPool(client.connectionPool)
.proxy(server.toProxyAddress())
.build()
executeSynchronously("/c").assertBody("ghi")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
}
@Test
fun connectionPoolingWithClientBuiltOffProxy() {
client =
OkHttpClient.Builder()
.proxy(server.toProxyAddress())
.build()
server.enqueue(MockResponse(body = "abc"))
server.enqueue(MockResponse(body = "def"))
server.enqueue(MockResponse(body = "ghi"))
client = client.newBuilder().build()
executeSynchronously("/a").assertBody("abc")
client = client.newBuilder().build()
executeSynchronously("/b").assertBody("def")
client = client.newBuilder().build()
executeSynchronously("/c").assertBody("ghi")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
}
@Test
fun connectionPooling_Async() {
server.enqueue(MockResponse(body = "abc"))
server.enqueue(MockResponse(body = "def"))
server.enqueue(MockResponse(body = "ghi"))
client.newCall(Request.Builder().url(server.url("/a")).build()).enqueue(callback)
callback.await(server.url("/a")).assertBody("abc")
client.newCall(Request.Builder().url(server.url("/b")).build()).enqueue(callback)
callback.await(server.url("/b")).assertBody("def")
client.newCall(Request.Builder().url(server.url("/c")).build()).enqueue(callback)
callback.await(server.url("/c")).assertBody("ghi")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
}
@Test
fun connectionReuseWhenResponseBodyConsumed_Async() {
server.enqueue(MockResponse(body = "abc"))
server.enqueue(MockResponse(body = "def"))
val request = Request.Builder().url(server.url("/a")).build()
client.newCall(request).enqueue(
object : Callback {
override fun onFailure(
call: Call,
e: IOException,
) {
throw AssertionError()
}
override fun onResponse(
call: Call,
response: Response,
) {
val bytes = response.body.byteStream()
assertThat(bytes.read()).isEqualTo('a'.code)
assertThat(bytes.read()).isEqualTo('b'.code)
assertThat(bytes.read()).isEqualTo('c'.code)
// This request will share a connection with 'A' cause it's all done.
client.newCall(Request.Builder().url(server.url("/b")).build()).enqueue(callback)
}
},
)
callback.await(server.url("/b")).assertCode(200).assertBody("def")
// New connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Connection reuse!
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@Test
fun timeoutsUpdatedOnReusedConnections() {
server.enqueue(MockResponse(body = "abc"))
server.enqueue(
MockResponse.Builder()
.body("def")
.throttleBody(1, 750, TimeUnit.MILLISECONDS)
.build(),
)
// First request: time out after 1s.
client =
client.newBuilder()
.readTimeout(Duration.ofSeconds(1))
.build()
executeSynchronously("/a").assertBody("abc")
// Second request: time out after 250ms.
client =
client.newBuilder()
.readTimeout(Duration.ofMillis(250))
.build()
val request = Request.Builder().url(server.url("/b")).build()
val response = client.newCall(request).execute()
val bodySource = response.body.source()
assertThat(bodySource.readByte()).isEqualTo('d'.code.toByte())
// The second byte of this request will be delayed by 750ms so we should time out after 250ms.
val startNanos = System.nanoTime()
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)
}
}
}
/** https://github.com/square/okhttp/issues/442 */
@Test
fun tlsTimeoutsNotRetried() {
enableTls()
server.enqueue(MockResponse(socketPolicy = NoResponse))
server.enqueue(MockResponse(body = "unreachable!"))
client =
client.newBuilder()
.readTimeout(Duration.ofMillis(100))
.build()
val request = Request.Builder().url(server.url("/")).build()
assertFailsWith<InterruptedIOException> {
// If this succeeds, too many requests were made.
client.newCall(request).execute()
}
}
/**