-
Notifications
You must be signed in to change notification settings - Fork 443
/
HttpRequestTest.java
1270 lines (1107 loc) · 50.9 KB
/
HttpRequestTest.java
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) 2010 Google 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 com.google.api.client.http;
import com.google.api.client.testing.http.HttpTesting;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockHttpUnsuccessfulResponseHandler;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.testing.util.LogRecordingHandler;
import com.google.api.client.testing.util.MockBackOff;
import com.google.api.client.testing.util.MockSleeper;
import com.google.api.client.util.BackOff;
import com.google.api.client.util.Key;
import com.google.api.client.util.LoggingStreamingContent;
import com.google.api.client.util.StringUtils;
import com.google.api.client.util.Value;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import org.junit.Assert;
/**
* Tests {@link HttpRequest}.
*
* @author Yaniv Inbar
*/
public class HttpRequestTest extends TestCase {
private static final ImmutableSet<String> BASIC_METHODS =
ImmutableSet.of(HttpMethods.GET, HttpMethods.PUT, HttpMethods.POST, HttpMethods.DELETE);
private static final ImmutableSet<String> OTHER_METHODS =
ImmutableSet.of(HttpMethods.HEAD, HttpMethods.PATCH);
public HttpRequestTest(String name) {
super(name);
}
@Override
public void setUp() {
// suppress logging warnings to the console
HttpTransport.LOGGER.setLevel(java.util.logging.Level.SEVERE);
}
@Override
public void tearDown() {
// back to the standard logging level for console
HttpTransport.LOGGER.setLevel(java.util.logging.Level.WARNING);
}
public void testNotSupportedByDefault() throws Exception {
MockHttpTransport transport = new MockHttpTransport();
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
for (String method : BASIC_METHODS) {
request.setRequestMethod(method);
request.execute();
}
for (String method : OTHER_METHODS) {
transport =
new MockHttpTransport.Builder().setSupportedMethods(ImmutableSet.<String>of()).build();
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setRequestMethod(method);
try {
request.execute();
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
transport =
new MockHttpTransport.Builder().setSupportedMethods(ImmutableSet.of(method)).build();
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setRequestMethod(method);
request.execute();
}
}
static class MockExecutor implements Executor {
private Runnable runnable;
public void actuallyRun() {
runnable.run();
}
public void execute(Runnable command) {
this.runnable = command;
}
}
@Deprecated
private static class MockBackOffPolicy implements BackOffPolicy {
int backOffCalls;
int resetCalls;
boolean returnBackOffStop;
MockBackOffPolicy() {}
public boolean isBackOffRequired(int statusCode) {
switch (statusCode) {
case HttpStatusCodes.STATUS_CODE_SERVER_ERROR: // 500
case HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE: // 503
return true;
default:
return false;
}
}
public void reset() {
resetCalls++;
}
public long getNextBackOffMillis() {
backOffCalls++;
if (returnBackOffStop) {
return BackOffPolicy.STOP;
}
return 0;
}
}
/** Transport used for testing the redirection logic in HttpRequest. */
static class RedirectTransport extends MockHttpTransport {
int lowLevelExecCalls;
boolean removeLocation;
boolean infiniteRedirection;
int redirectStatusCode = HttpStatusCodes.STATUS_CODE_MOVED_PERMANENTLY;
String[] expectedContent;
LowLevelHttpRequest retryableGetRequest =
new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
if (expectedContent != null) {
assertEquals(
String.valueOf(lowLevelExecCalls),
expectedContent[lowLevelExecCalls],
getContentAsString());
}
lowLevelExecCalls++;
if (infiniteRedirection || lowLevelExecCalls == 1) {
// Return redirect on only the first call.
// If infiniteRedirection is true then always return the redirect status code.
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setStatusCode(redirectStatusCode);
if (!removeLocation) {
response.addHeader("Location", HttpTesting.SIMPLE_URL);
}
return response;
}
// Return success on the second if infiniteRedirection is False.
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setContent("{\"data\":{\"foo\":{\"v1\":{}}}}");
return response;
}
};
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return retryableGetRequest;
}
}
private void setBackOffUnsuccessfulResponseHandler(
HttpRequest request, BackOff backOff, final HttpUnsuccessfulResponseHandler handler) {
final HttpBackOffUnsuccessfulResponseHandler backOffHandler =
new HttpBackOffUnsuccessfulResponseHandler(backOff).setSleeper(new MockSleeper());
request.setUnsuccessfulResponseHandler(
new HttpUnsuccessfulResponseHandler() {
public boolean handleResponse(
HttpRequest request, HttpResponse response, boolean supportsRetry)
throws IOException {
return handler.handleResponse(request, response, supportsRetry)
|| backOffHandler.handleResponse(request, response, supportsRetry);
}
});
}
public void test301Redirect() throws Exception {
// Set up RedirectTransport to redirect on the first request and then return success.
RedirectTransport fakeTransport = new RedirectTransport();
HttpRequest request =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));
HttpResponse resp = request.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
}
@Deprecated
public void test301RedirectWithUnsuccessfulResponseHandled() throws Exception {
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(true);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
// Set up RedirectTransport to redirect on the first request and then return success.
RedirectTransport fakeTransport = new RedirectTransport();
HttpRequest request =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));
request.setUnsuccessfulResponseHandler(handler);
request.setBackOffPolicy(backOffPolicy);
HttpResponse resp = request.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
// Assert that the redirect logic was not invoked because the response handler could handle the
// request. The request url should be the original http://gmail.com
Assert.assertEquals("http://gmail.com", request.getUrl().toString());
// Assert that the backoff policy was not invoked because the response handler could handle the
// request.
Assert.assertEquals(1, backOffPolicy.resetCalls);
Assert.assertEquals(0, backOffPolicy.backOffCalls);
Assert.assertTrue(handler.isCalled());
}
public void test301RedirectWithBackOffUnsuccessfulResponseHandled() throws Exception {
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(true);
// Set up RedirectTransport to redirect on the first request and then return success.
RedirectTransport fakeTransport = new RedirectTransport();
HttpRequest request =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));
MockBackOff backOff = new MockBackOff();
setBackOffUnsuccessfulResponseHandler(request, backOff, handler);
HttpResponse resp = request.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
// Assert that the redirect logic was not invoked because the response handler could handle the
// request. The request url should be the original http://gmail.com
Assert.assertEquals("http://gmail.com", request.getUrl().toString());
// Assert that the backoff was not invoked since the response handler could handle the request
Assert.assertEquals(0, backOff.getNumberOfTries());
Assert.assertTrue(handler.isCalled());
}
@Deprecated
public void test301RedirectWithUnsuccessfulResponseNotHandled() throws Exception {
// Create an Unsuccessful response handler that always returns false.
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
// Set up RedirectTransport to redirect on the first request and then return success.
RedirectTransport fakeTransport = new RedirectTransport();
HttpRequest request =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));
request.setUnsuccessfulResponseHandler(handler);
request.setBackOffPolicy(backOffPolicy);
HttpResponse resp = request.execute();
Assert.assertEquals(200, resp.getStatusCode());
// Assert that the redirect logic was invoked because the response handler could not handle the
// request. The request url should have changed from http://gmail.com to http://google.com
Assert.assertEquals(HttpTesting.SIMPLE_URL, request.getUrl().toString());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
// Assert that the backoff policy is never invoked (except to reset) because the response
// handler returned false.
Assert.assertEquals(1, backOffPolicy.resetCalls);
Assert.assertEquals(0, backOffPolicy.backOffCalls);
}
public void test301RedirectWithBackOffUnsuccessfulResponseNotHandled() throws Exception {
// Create an Unsuccessful response handler that always returns false.
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
// Set up RedirectTransport to redirect on the first request and then return success.
RedirectTransport fakeTransport = new RedirectTransport();
HttpRequest request =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));
MockBackOff backOff = new MockBackOff();
setBackOffUnsuccessfulResponseHandler(request, backOff, handler);
HttpResponse resp = request.execute();
Assert.assertEquals(200, resp.getStatusCode());
// Assert that the redirect logic was invoked because the response handler could not handle the
// request. The request url should have changed from http://gmail.com to http://google.com
Assert.assertEquals(HttpTesting.SIMPLE_URL, request.getUrl().toString());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
// Assert that the backoff was not invoked since it's not required for 3xx errors
Assert.assertEquals(0, backOff.getNumberOfTries());
}
public void test303Redirect() throws Exception {
// Set up RedirectTransport to redirect on the first request and then return success.
RedirectTransport fakeTransport = new RedirectTransport();
fakeTransport.redirectStatusCode = HttpStatusCodes.STATUS_CODE_SEE_OTHER;
byte[] content = new byte[300];
Arrays.fill(content, (byte) ' ');
HttpRequest request =
fakeTransport
.createRequestFactory()
.buildPostRequest(
new GenericUrl("http://gmail.com"), new ByteArrayContent(null, content));
request.setRequestMethod(HttpMethods.POST);
HttpResponse resp = request.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
// Assert that the method in the request was changed to a GET due to the 303.
Assert.assertEquals(HttpMethods.GET, request.getRequestMethod());
// Assert that the content is null, since GET requests don't support non-zero content-length
Assert.assertNull(request.getContent());
}
public void testInfiniteRedirects() throws Exception {
// Set up RedirectTransport to cause infinite redirections.
RedirectTransport fakeTransport = new RedirectTransport();
fakeTransport.infiniteRedirection = true;
HttpRequest request =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));
try {
request.execute();
fail("expected HttpResponseException");
} catch (HttpResponseException e) {
}
// Should be called 1 more than the number of retries allowed (because the first request is not
// counted as a retry).
Assert.assertEquals(request.getNumberOfRetries() + 1, fakeTransport.lowLevelExecCalls);
}
public void testMissingLocationRedirect() throws Exception {
// Set up RedirectTransport to set responses with missing location headers.
RedirectTransport fakeTransport = new RedirectTransport();
fakeTransport.removeLocation = true;
HttpRequest request =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));
try {
request.execute();
fail("expected HttpResponseException");
} catch (HttpResponseException e) {
}
Assert.assertEquals(1, fakeTransport.lowLevelExecCalls);
}
private static class FailThenSuccessBackoffTransport extends MockHttpTransport {
public int lowLevelExecCalls;
int errorStatusCode;
int callsBeforeSuccess;
protected FailThenSuccessBackoffTransport(int errorStatusCode, int callsBeforeSuccess) {
this.errorStatusCode = errorStatusCode;
this.callsBeforeSuccess = callsBeforeSuccess;
}
public LowLevelHttpRequest retryableGetRequest =
new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() {
lowLevelExecCalls++;
if (lowLevelExecCalls <= callsBeforeSuccess) {
// Return failure on the first call
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setContent("INVALID TOKEN");
response.setStatusCode(errorStatusCode);
return response;
}
// Return success on the second
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setContent("{\"data\":{\"foo\":{\"v1\":{}}}}");
response.setStatusCode(200);
return response;
}
};
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return retryableGetRequest;
}
}
private static class FailThenSuccessConnectionErrorTransport extends MockHttpTransport {
public int lowLevelExecCalls;
int callsBeforeSuccess;
List<String> userAgentHeader = Lists.newArrayList();
protected FailThenSuccessConnectionErrorTransport(int callsBeforeSuccess) {
this.callsBeforeSuccess = callsBeforeSuccess;
}
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
lowLevelExecCalls++;
userAgentHeader = getHeaderValues("User-Agent");
if (lowLevelExecCalls <= callsBeforeSuccess) {
throw new IOException();
}
// Return success when count is more than callsBeforeSuccess
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setStatusCode(200);
return response;
}
};
}
}
private static class StatusCodesTransport extends MockHttpTransport {
int statusCode = 200;
public StatusCodesTransport() {}
public MockLowLevelHttpRequest retryableGetRequest =
new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setStatusCode(statusCode);
return response;
}
};
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return retryableGetRequest;
}
}
public void testHandleRedirect() throws Exception {
StatusCodesTransport transport = new StatusCodesTransport();
HttpRequest req =
transport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
HttpResponse response = req.execute();
// 200 should not be redirected
assertFalse(req.handleRedirect(response.getStatusCode(), response.getHeaders()));
subtestRedirect(301, true);
subtestRedirect(302, true);
subtestRedirect(303, true);
subtestRedirect(307, true);
subtestRedirect(307, false);
}
private void subtestRedirect(int statusCode, boolean setLocation) throws Exception {
StatusCodesTransport transport = new StatusCodesTransport();
transport.statusCode = statusCode;
HttpRequest req =
transport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setThrowExceptionOnExecuteError(false);
req.getHeaders()
.setAuthorization("auth")
.setIfMatch("etag")
.setIfNoneMatch("etag")
.setIfModifiedSince("date")
.setIfUnmodifiedSince("date")
.setIfRange("range");
HttpResponse response = req.execute();
if (setLocation) {
response.getHeaders().setLocation("http://redirect/location");
}
boolean handleRedirect = req.handleRedirect(response.getStatusCode(), response.getHeaders());
if (setLocation) {
assertTrue(handleRedirect);
assertNull(req.getHeaders().getAuthorization());
assertNull(req.getHeaders().getIfMatch());
assertNull(req.getHeaders().getIfNoneMatch());
assertNull(req.getHeaders().getIfModifiedSince());
assertNull(req.getHeaders().getIfUnmodifiedSince());
assertNull(req.getHeaders().getIfRange());
assertEquals("http://redirect/location", req.getUrl().toString());
} else {
assertFalse(handleRedirect);
assertEquals("auth", req.getHeaders().getAuthorization());
assertEquals("etag", req.getHeaders().getIfMatch());
assertEquals("etag", req.getHeaders().getIfNoneMatch());
assertEquals("date", req.getHeaders().getIfModifiedSince());
assertEquals("date", req.getHeaders().getIfUnmodifiedSince());
assertEquals("range", req.getHeaders().getIfRange());
assertEquals("http://not/used", req.getUrl().toString());
}
}
public void testHandleRedirect_relativeLocation() throws IOException {
subtestHandleRedirect_relativeLocation("http://some.org/a/b", "z", "http://some.org/a/z");
subtestHandleRedirect_relativeLocation("http://some.org/a/b", "z/", "http://some.org/a/z/");
subtestHandleRedirect_relativeLocation("http://some.org/a/b", "/z", "http://some.org/z");
subtestHandleRedirect_relativeLocation("http://some.org/a/b", "x/z", "http://some.org/a/x/z");
subtestHandleRedirect_relativeLocation(
"http://some.org/a/b", "http://other.org/c", "http://other.org/c");
}
public void subtestHandleRedirect_relativeLocation(
String curLocation, String relLocation, String newLocation) throws IOException {
HttpTransport transport = new MockHttpTransport();
HttpRequest req = transport.createRequestFactory().buildGetRequest(new GenericUrl(curLocation));
HttpHeaders responseHeaders = new HttpHeaders().setLocation(relLocation);
req.handleRedirect(HttpStatusCodes.STATUS_CODE_SEE_OTHER, responseHeaders);
assertEquals(newLocation, req.getUrl().toString());
}
@Deprecated
public void testExecuteErrorWithRetryEnabled() throws Exception {
int callsBeforeSuccess = 3;
FailThenSuccessConnectionErrorTransport fakeTransport =
new FailThenSuccessConnectionErrorTransport(callsBeforeSuccess);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setRetryOnExecuteIOException(true);
req.setNumberOfRetries(callsBeforeSuccess + 1);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(4, fakeTransport.lowLevelExecCalls);
}
public void testExecuteErrorWithIOExceptionHandler() throws Exception {
int callsBeforeSuccess = 3;
FailThenSuccessConnectionErrorTransport fakeTransport =
new FailThenSuccessConnectionErrorTransport(callsBeforeSuccess);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(BackOff.ZERO_BACKOFF));
req.setNumberOfRetries(callsBeforeSuccess + 1);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(4, fakeTransport.lowLevelExecCalls);
}
@Deprecated
public void testExecuteErrorWithRetryEnabledBeyondRetryLimit() throws Exception {
int callsBeforeSuccess = 11;
FailThenSuccessConnectionErrorTransport fakeTransport =
new FailThenSuccessConnectionErrorTransport(callsBeforeSuccess);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setRetryOnExecuteIOException(true);
req.setNumberOfRetries(callsBeforeSuccess - 1);
try {
req.execute();
fail("Expected: " + IOException.class);
} catch (IOException e) {
// Expected
}
Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls);
}
public void testExecuteErrorWithIOExceptionHandlerBeyondRetryLimit() throws Exception {
int callsBeforeSuccess = 11;
FailThenSuccessConnectionErrorTransport fakeTransport =
new FailThenSuccessConnectionErrorTransport(callsBeforeSuccess);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(BackOff.ZERO_BACKOFF));
req.setNumberOfRetries(callsBeforeSuccess - 1);
try {
req.execute();
fail("Expected: " + IOException.class);
} catch (IOException e) {
// Expected
}
Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls);
}
public void testExecuteErrorWithoutIOExceptionHandler() throws Exception {
int callsBeforeSuccess = 3;
FailThenSuccessConnectionErrorTransport fakeTransport =
new FailThenSuccessConnectionErrorTransport(callsBeforeSuccess);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
// I/O exception handler is null by default
req.setNumberOfRetries(callsBeforeSuccess + 1);
try {
req.execute();
fail("Expected: " + IOException.class);
} catch (IOException e) {
// Expected
}
Assert.assertEquals(1, fakeTransport.lowLevelExecCalls);
}
@Deprecated
public void testUserAgentWithExecuteErrorAndRetryEnabled() throws Exception {
int callsBeforeSuccess = 3;
FailThenSuccessConnectionErrorTransport fakeTransport =
new FailThenSuccessConnectionErrorTransport(callsBeforeSuccess);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setRetryOnExecuteIOException(true);
req.setNumberOfRetries(callsBeforeSuccess + 1);
HttpResponse resp = req.execute();
Assert.assertEquals(1, fakeTransport.userAgentHeader.size());
Assert.assertEquals(HttpRequest.USER_AGENT_SUFFIX, fakeTransport.userAgentHeader.get(0));
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(4, fakeTransport.lowLevelExecCalls);
}
public void testUserAgentWithExecuteErrorAndIOExceptionHandler() throws Exception {
int callsBeforeSuccess = 3;
FailThenSuccessConnectionErrorTransport fakeTransport =
new FailThenSuccessConnectionErrorTransport(callsBeforeSuccess);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(BackOff.ZERO_BACKOFF));
req.setNumberOfRetries(callsBeforeSuccess + 1);
HttpResponse resp = req.execute();
Assert.assertEquals(1, fakeTransport.userAgentHeader.size());
Assert.assertEquals(HttpRequest.USER_AGENT_SUFFIX, fakeTransport.userAgentHeader.get(0));
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(4, fakeTransport.lowLevelExecCalls);
}
public void testAbnormalResponseHandlerWithNoBackOff() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, 1);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(true);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setUnsuccessfulResponseHandler(handler);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
Assert.assertTrue(handler.isCalled());
}
@Deprecated
public void testAbnormalResponseHandlerWithBackOff() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(true);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setUnsuccessfulResponseHandler(handler);
req.setBackOffPolicy(backOffPolicy);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(1, backOffPolicy.resetCalls);
Assert.assertEquals(0, backOffPolicy.backOffCalls);
Assert.assertTrue(handler.isCalled());
}
public void testAbnormalResponseHandlerWithBackOffUnsuccessfulResponseHandler() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(true);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
MockBackOff backOff = new MockBackOff();
setBackOffUnsuccessfulResponseHandler(req, backOff, handler);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(0, backOff.getNumberOfTries());
Assert.assertTrue(handler.isCalled());
}
@Deprecated
public void testBackOffSingleCall() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setUnsuccessfulResponseHandler(handler);
req.setBackOffPolicy(backOffPolicy);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(1, backOffPolicy.resetCalls);
Assert.assertEquals(1, backOffPolicy.backOffCalls);
Assert.assertTrue(handler.isCalled());
}
public void testBackOffUnsuccessfulResponseSingleCall() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
MockBackOff backOff = new MockBackOff();
setBackOffUnsuccessfulResponseHandler(req, backOff, handler);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(1, backOff.getNumberOfTries());
Assert.assertTrue(handler.isCalled());
}
@Deprecated
public void testBackOffMultipleCalls() throws Exception {
int callsBeforeSuccess = 5;
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(
HttpStatusCodes.STATUS_CODE_SERVER_ERROR, callsBeforeSuccess);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setUnsuccessfulResponseHandler(handler);
req.setBackOffPolicy(backOffPolicy);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(callsBeforeSuccess + 1, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(1, backOffPolicy.resetCalls);
Assert.assertEquals(callsBeforeSuccess, backOffPolicy.backOffCalls);
Assert.assertTrue(handler.isCalled());
}
public void testBackOffUnsucessfulReponseMultipleCalls() throws Exception {
int callsBeforeSuccess = 5;
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(
HttpStatusCodes.STATUS_CODE_SERVER_ERROR, callsBeforeSuccess);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
MockBackOff backOff = new MockBackOff();
setBackOffUnsuccessfulResponseHandler(req, backOff, handler);
HttpResponse resp = req.execute();
Assert.assertEquals(200, resp.getStatusCode());
Assert.assertEquals(callsBeforeSuccess + 1, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(callsBeforeSuccess, backOff.getNumberOfTries());
Assert.assertTrue(handler.isCalled());
}
@Deprecated
public void testBackOffCallsBeyondRetryLimit() throws Exception {
int callsBeforeSuccess = 11;
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(
HttpStatusCodes.STATUS_CODE_SERVER_ERROR, callsBeforeSuccess);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setNumberOfRetries(callsBeforeSuccess - 1);
req.setUnsuccessfulResponseHandler(handler);
req.setBackOffPolicy(backOffPolicy);
try {
req.execute();
fail("expected HttpResponseException");
} catch (HttpResponseException e) {
}
Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(1, backOffPolicy.resetCalls);
Assert.assertEquals(callsBeforeSuccess - 1, backOffPolicy.backOffCalls);
Assert.assertTrue(handler.isCalled());
}
public void testBackOffUnsuccessfulReponseCallsBeyondRetryLimit() throws Exception {
int callsBeforeSuccess = 11;
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(
HttpStatusCodes.STATUS_CODE_SERVER_ERROR, callsBeforeSuccess);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setNumberOfRetries(callsBeforeSuccess - 1);
MockBackOff backOff = new MockBackOff();
setBackOffUnsuccessfulResponseHandler(req, backOff, handler);
try {
req.execute();
fail("expected HttpResponseException");
} catch (HttpResponseException e) {
}
Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(callsBeforeSuccess - 1, backOff.getMaxTries());
Assert.assertTrue(handler.isCalled());
}
@Deprecated
public void testBackOffUnRecognizedStatusCode() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, 1);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setUnsuccessfulResponseHandler(handler);
req.setBackOffPolicy(backOffPolicy);
try {
req.execute();
} catch (HttpResponseException e) {
}
Assert.assertEquals(1, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(1, backOffPolicy.resetCalls);
// The BackOffPolicy should not be called since it does not support 401 status codes.
Assert.assertEquals(0, backOffPolicy.backOffCalls);
Assert.assertTrue(handler.isCalled());
}
public void testBackOffUnsuccessfulReponseUnRecognizedStatusCode() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, 1);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
MockBackOff backOff = new MockBackOff();
setBackOffUnsuccessfulResponseHandler(req, backOff, handler);
try {
req.execute();
} catch (HttpResponseException e) {
}
Assert.assertEquals(1, fakeTransport.lowLevelExecCalls);
// The back-off should not be called since it does not support 401 status codes.
Assert.assertEquals(0, backOff.getNumberOfTries());
Assert.assertTrue(handler.isCalled());
}
@Deprecated
public void testBackOffStop() throws Exception {
int callsBeforeSuccess = 5;
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(
HttpStatusCodes.STATUS_CODE_SERVER_ERROR, callsBeforeSuccess);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
MockBackOffPolicy backOffPolicy = new MockBackOffPolicy();
backOffPolicy.returnBackOffStop = true;
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
req.setUnsuccessfulResponseHandler(handler);
req.setBackOffPolicy(backOffPolicy);
try {
req.execute();
} catch (HttpResponseException e) {
}
Assert.assertEquals(1, fakeTransport.lowLevelExecCalls);
Assert.assertEquals(1, backOffPolicy.resetCalls);
// The BackOffPolicy should be called only once and then it should return BackOffPolicy.STOP
// should stop all back off retries.
Assert.assertEquals(1, backOffPolicy.backOffCalls);
Assert.assertTrue(handler.isCalled());
}
public void testBackOffUnsucessfulResponseStop() throws Exception {
int callsBeforeSuccess = 5;
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(
HttpStatusCodes.STATUS_CODE_SERVER_ERROR, callsBeforeSuccess);
MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
HttpRequest req =
fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://not/used"));
MockBackOff backOff = new MockBackOff().setMaxTries(1);
setBackOffUnsuccessfulResponseHandler(req, backOff, handler);
try {
req.execute();
} catch (HttpResponseException e) {
}
Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
// The back-off should be called only once, since the its max tries is set to 1
Assert.assertEquals(1, backOff.getNumberOfTries());
Assert.assertTrue(handler.isCalled());
}
public enum E {
@Value
VALUE,
@Value("other")
OTHER_VALUE,
}
public static class MyHeaders extends HttpHeaders {
@Key public String foo;
@Key Object objNum;
@Key Object objList;
@Key List<String> list;
@Key String[] r;
@Key E value;
@Key E otherValue;
}
public void testExecute_headerSerialization() throws Exception {
// custom headers
MyHeaders myHeaders = new MyHeaders();
myHeaders.foo = "bar";
myHeaders.objNum = 5;
myHeaders.list = ImmutableList.of("a", "b", "c");
myHeaders.objList = ImmutableList.of("a2", "b2", "c2");
myHeaders.r = new String[] {"a1", "a2"};
myHeaders.setAcceptEncoding(null);
myHeaders.setUserAgent("foo");
myHeaders.set("a", "b");
myHeaders.value = E.VALUE;
myHeaders.otherValue = E.OTHER_VALUE;
// execute request
final MockLowLevelHttpRequest lowLevelRequest = new MockLowLevelHttpRequest();
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return lowLevelRequest;
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setHeaders(myHeaders);
request.execute();
// check headers
assertEquals(ImmutableList.of("bar"), lowLevelRequest.getHeaderValues("foo"));
assertEquals(ImmutableList.of("a", "b", "c"), lowLevelRequest.getHeaderValues("list"));
assertEquals(ImmutableList.of("a2", "b2", "c2"), lowLevelRequest.getHeaderValues("objlist"));
assertEquals(ImmutableList.of("a1", "a2"), lowLevelRequest.getHeaderValues("r"));
assertTrue(lowLevelRequest.getHeaderValues("accept-encoding").isEmpty());
assertEquals(
ImmutableList.of("foo Google-HTTP-Java-Client/" + HttpRequest.VERSION + " (gzip)"),
lowLevelRequest.getHeaderValues("user-agent"));
assertEquals(ImmutableList.of("b"), lowLevelRequest.getHeaderValues("a"));
assertEquals(ImmutableList.of("VALUE"), lowLevelRequest.getHeaderValues("value"));
assertEquals(ImmutableList.of("other"), lowLevelRequest.getHeaderValues("othervalue"));
}
public void testGZipEncoding() throws Exception {
class MyTransport extends MockHttpTransport {
boolean expectGZip;
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
if (expectGZip) {
assertEquals(HttpEncodingStreamingContent.class, getStreamingContent().getClass());
assertEquals("gzip", getContentEncoding());
assertEquals(25, getContentLength());
} else {
assertFalse(
getStreamingContent().getClass().equals(HttpEncodingStreamingContent.class));
assertNull(getContentEncoding());
assertEquals(300, getContentLength());
}
char[] content = new char[300];