forked from googleapis/google-http-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpResponseTest.java
545 lines (500 loc) · 20.7 KB
/
HttpResponseTest.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
/*
* 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.json.Json;
import com.google.api.client.testing.http.HttpTesting;
import com.google.api.client.testing.http.MockHttpTransport;
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.TestableByteArrayInputStream;
import com.google.api.client.util.Key;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Level;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import junit.framework.TestCase;
/**
* Tests {@link HttpResponse}.
*
* @author Yaniv Inbar
*/
public class HttpResponseTest extends TestCase {
public HttpResponseTest() {}
public HttpResponseTest(String name) {
super(name);
}
public void testParseAsString_none() throws Exception {
HttpTransport transport = new MockHttpTransport();
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
assertEquals("", response.parseAsString());
}
private static final String SAMPLE = "123\u05D9\u05e0\u05D9\u05D1";
private static final String SAMPLE2 = "123abc";
public void testParseAsString_utf8() throws Exception {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.setContentType(Json.MEDIA_TYPE);
result.setContent(SAMPLE);
return result;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
assertEquals(SAMPLE, response.parseAsString());
}
public void testParseAsString_noContentType() throws Exception {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.setContent(SAMPLE2);
return result;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
assertEquals(SAMPLE2, response.parseAsString());
}
public void testStatusCode_negative_dontThrowException() throws Exception {
subtestStatusCode_negative(false);
}
public void testStatusCode_negative_throwException() throws Exception {
subtestStatusCode_negative(true);
}
private void subtestStatusCode_negative(boolean throwExceptionOnExecuteError) throws Exception {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest()
.setResponse(new MockLowLevelHttpResponse().setStatusCode(-1));
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setThrowExceptionOnExecuteError(throwExceptionOnExecuteError);
try {
// HttpResponse converts a negative status code to zero
HttpResponse response = request.execute();
assertEquals(0, response.getStatusCode());
assertFalse(throwExceptionOnExecuteError);
} catch (HttpResponseException e) {
// exception should be thrown only if throwExceptionOnExecuteError is true
assertTrue(throwExceptionOnExecuteError);
assertEquals(0, e.getStatusCode());
}
}
public static class MyHeaders extends HttpHeaders {
@Key public String foo;
@Key public Object obj;
@Key String[] r;
}
static final String ETAG_VALUE = "\"abc\"";
public void testHeaderParsing() throws Exception {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.addHeader("accept", "value");
result.addHeader("foo", "bar");
result.addHeader("goo", "car");
result.addHeader("hoo", "dar");
result.addHeader("hoo", "far");
result.addHeader("obj", "o");
result.addHeader("r", "a1");
result.addHeader("r", "a2");
result.addHeader("ETAG", ETAG_VALUE);
return result;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setResponseHeaders(new MyHeaders());
HttpResponse response = request.execute();
assertEquals("value", response.getHeaders().getAccept());
assertEquals("bar", ((MyHeaders) response.getHeaders()).foo);
assertEquals(Arrays.asList("o"), ((MyHeaders) response.getHeaders()).obj);
assertEquals(Arrays.asList("a1", "a2"), Arrays.asList(((MyHeaders) response.getHeaders()).r));
assertEquals(Arrays.asList("car"), response.getHeaders().get("goo"));
assertEquals(Arrays.asList("dar", "far"), response.getHeaders().get("hoo"));
assertEquals(ETAG_VALUE, response.getHeaders().getETag());
}
public void testParseAs_noParser() throws Exception {
try {
new MockHttpTransport()
.createRequestFactory()
.buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
.execute()
.parseAs(Object.class);
fail("expected " + NullPointerException.class);
} catch (NullPointerException e) {
// expected
}
}
public void testParseAs_classNoContent() throws Exception {
final MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
for (final int status :
new int[] {
HttpStatusCodes.STATUS_CODE_NO_CONTENT, HttpStatusCodes.STATUS_CODE_NOT_MODIFIED, 102
}) {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url)
throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
result.setStatusCode(status);
result.setContentType(null);
result.setContent(new ByteArrayInputStream(new byte[0]));
return result;
}
};
}
};
// Confirm that 'null' is returned when getting the response object of a
// request with no message body.
Object parsed =
transport
.createRequestFactory()
.buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
.setThrowExceptionOnExecuteError(false)
.execute()
.parseAs(Object.class);
assertNull(parsed);
}
}
public void testParseAs_typeNoContent() throws Exception {
final MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
for (final int status :
new int[] {
HttpStatusCodes.STATUS_CODE_NO_CONTENT, HttpStatusCodes.STATUS_CODE_NOT_MODIFIED, 102
}) {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url)
throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
result.setStatusCode(status);
result.setContentType(null);
result.setContent(new ByteArrayInputStream(new byte[0]));
return result;
}
};
}
};
// Confirm that 'null' is returned when getting the response object of a
// request with no message body.
Object parsed =
transport
.createRequestFactory()
.buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
.setThrowExceptionOnExecuteError(false)
.execute()
.parseAs((Type) Object.class);
assertNull(parsed);
}
}
public void testDownload() throws Exception {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.setContentType(Json.MEDIA_TYPE);
result.setContent(SAMPLE);
return result;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
response.download(outputStream);
assertEquals(SAMPLE, outputStream.toString("UTF-8"));
}
public void testDisconnectWithContent() throws Exception {
final MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse();
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
lowLevelHttpResponse.setContentType(Json.MEDIA_TYPE);
lowLevelHttpResponse.setContent(SAMPLE);
return lowLevelHttpResponse;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
assertFalse(lowLevelHttpResponse.isDisconnected());
TestableByteArrayInputStream content =
(TestableByteArrayInputStream) lowLevelHttpResponse.getContent();
assertFalse(content.isClosed());
response.disconnect();
assertTrue(lowLevelHttpResponse.isDisconnected());
assertTrue(content.isClosed());
}
public void testDisconnectWithNoContent() throws Exception {
final MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse();
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
return lowLevelHttpResponse;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
assertFalse(lowLevelHttpResponse.isDisconnected());
response.disconnect();
assertTrue(lowLevelHttpResponse.isDisconnected());
}
public void testContentLoggingLimitWithLoggingEnabledAndDisabled() throws Exception {
subtestContentLoggingLimit("", 2, false);
subtestContentLoggingLimit("A", 2, false);
subtestContentLoggingLimit("ABC" + '\0' + "DEF", 20, true, "Total: 7 bytes", "ABC DEF");
subtestContentLoggingLimit("A", 2, true, "Total: 1 byte", "A");
try {
subtestContentLoggingLimit("ABC", -1, true);
fail("Expected: " + IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
// Expected.
}
subtestContentLoggingLimit("ABC", 0, true, "Total: 3 bytes");
subtestContentLoggingLimit("ABC", 2, true, "Total: 3 bytes (logging first 2 bytes)", "AB");
subtestContentLoggingLimit("ABC", 3, true, "Total: 3 bytes", "ABC");
subtestContentLoggingLimit("ABC", 4, true, "Total: 3 bytes", "ABC");
char[] a = new char[18000];
Arrays.fill(a, 'x');
String big = new String(a);
String formated18kInteger = NumberFormat.getInstance().format(18000);
subtestContentLoggingLimit(
big, Integer.MAX_VALUE, true, String.format("Total: %s bytes", formated18kInteger), big);
subtestContentLoggingLimit(
big,
4,
true,
String.format("Total: %s bytes (logging first 4 bytes)", formated18kInteger),
"xxxx");
}
public void subtestContentLoggingLimit(
final String content,
int contentLoggingLimit,
boolean loggingEnabled,
String... expectedMessages)
throws Exception {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url)
throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.setContent(content);
result.setContentType("text/plain");
return result;
}
};
}
};
HttpTransport.LOGGER.setLevel(Level.CONFIG);
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setLoggingEnabled(loggingEnabled);
HttpResponse response = request.execute();
assertEquals(loggingEnabled, response.isLoggingEnabled());
response.setContentLoggingLimit(contentLoggingLimit);
LogRecordingHandler recorder = new LogRecordingHandler();
HttpTransport.LOGGER.addHandler(recorder);
response.parseAsString();
assertEquals(Arrays.asList(expectedMessages), recorder.messages());
}
public void testGetContent_gzipNoContent() throws IOException {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url)
throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.setContent("");
result.setContentEncoding("gzip");
result.setContentType("text/plain");
return result;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.execute().getContent();
}
public void testGetContent_gzipEncoding_ReturnRawStream() throws IOException {
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url)
throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.setContent("");
result.setContentEncoding("gzip");
result.setContentType("text/plain");
return result;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setResponseReturnRawInputStream(true);
assertFalse(
"it should not decompress stream",
request.execute().getContent() instanceof GZIPInputStream);
}
public void testGetContent_gzipEncoding_finishReading() throws IOException {
do_testGetContent_gzipEncoding_finishReading("gzip");
}
public void testGetContent_gzipEncoding_finishReadingWithUppercaseContentEncoding() throws IOException {
do_testGetContent_gzipEncoding_finishReading("GZIP");
}
public void testGetContent_gzipEncoding_finishReadingWithDifferentDefaultLocaleAndUppercaseContentEncoding() throws IOException {
Locale originalDefaultLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.forLanguageTag("tr-TR"));
do_testGetContent_gzipEncoding_finishReading("GZIP");
} finally {
Locale.setDefault(originalDefaultLocale);
}
}
private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding) throws IOException {
byte[] dataToCompress = "abcd".getBytes(StandardCharsets.UTF_8);
byte[] mockBytes;
try (
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length);
GZIPOutputStream zipStream = new GZIPOutputStream((byteStream))
) {
zipStream.write(dataToCompress);
zipStream.close();
mockBytes = byteStream.toByteArray();
}
final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse();
mockResponse.setContent(mockBytes);
mockResponse.setContentEncoding(contentEncoding);
mockResponse.setContentType("text/plain");
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url)
throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
return mockResponse;
}
};
}
};
HttpRequest request =
transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
try (TestableByteArrayInputStream output = (TestableByteArrayInputStream) mockResponse.getContent()) {
assertFalse(output.isClosed());
assertEquals("abcd", response.parseAsString());
assertTrue(output.isClosed());
}
}
public void testGetContent_otherEncodingWithgzipInItsName_GzipIsNotUsed() throws IOException {
final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse();
mockResponse.setContent("abcd");
mockResponse.setContentEncoding("otherEncodingWithgzipInItsName");
mockResponse.setContentType("text/plain");
HttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url)
throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
return mockResponse;
}
};
}
};
HttpRequest request = transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
// If gzip was used on this response, an exception would be thrown
HttpResponse response = request.execute();
assertEquals("abcd", response.parseAsString());
}
}