source: josm/trunk/test/functional/org/openstreetmap/josm/tools/HttpClientTest.java@ 12562

Last change on this file since 12562 was 12562, checked in by Don-vip, 7 years ago

speedup unit tests

  • Property svn:eol-style set to native
File size: 13.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.hamcrest.CoreMatchers.containsString;
5import static org.hamcrest.CoreMatchers.is;
6import static org.hamcrest.CoreMatchers.nullValue;
7import static org.junit.Assert.assertThat;
8
9import java.io.BufferedReader;
10import java.io.IOException;
11import java.io.InputStream;
12import java.net.URL;
13import java.nio.charset.StandardCharsets;
14import java.util.Collections;
15import java.util.logging.Handler;
16import java.util.logging.LogRecord;
17
18import javax.json.JsonObject;
19import javax.json.JsonReader;
20import javax.json.spi.JsonProvider;
21
22import org.junit.Assert;
23import org.junit.Before;
24import org.junit.Rule;
25import org.junit.Test;
26import org.openstreetmap.josm.TestUtils;
27import org.openstreetmap.josm.data.Version;
28import org.openstreetmap.josm.gui.progress.ProgressMonitor;
29import org.openstreetmap.josm.testutils.JOSMTestRules;
30
31import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
32
33/**
34 * Tests the {@link HttpClient} using the webservice <a href="https://httpbin.org/">https://httpbin.org/</a>.
35 */
36public class HttpClientTest {
37
38 @Rule
39 @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
40 public JOSMTestRules test = new JOSMTestRules().preferences().timeout(15000);
41
42 private ProgressMonitor progress;
43
44 private LogRecord captured;
45 private final Handler handler = new Handler() {
46
47 @Override
48 public void publish(LogRecord record) {
49 captured = record;
50 }
51
52 @Override
53 public void flush() {
54 }
55
56 @Override
57 public void close() throws SecurityException {
58 }
59 };
60
61 /**
62 * Setup test.
63 */
64 @Before
65 public void setUp() {
66 progress = TestUtils.newTestProgressMonitor();
67 captured = null;
68 Logging.getLogger().addHandler(handler);
69 Logging.getLogger().setLevel(Logging.LEVEL_DEBUG);
70 }
71
72 @Test
73 public void testConstructorGetterSetter() throws IOException {
74 final HttpClient client = HttpClient.create(new URL("https://httpbin.org/"));
75 assertThat(client.getURL(), is(new URL("https://httpbin.org/")));
76 assertThat(client.getRequestMethod(), is("GET"));
77 assertThat(client.getRequestHeader("Accept"), nullValue());
78 client.setAccept("text/html");
79 assertThat(client.getRequestHeader("Accept"), is("text/html"));
80 assertThat(client.getRequestHeader("ACCEPT"), is("text/html"));
81 client.setHeaders(Collections.singletonMap("foo", "bar"));
82 assertThat(client.getRequestHeader("foo"), is("bar"));
83 client.setHeaders(Collections.singletonMap("foo", "baz"));
84 assertThat(client.getRequestHeader("foo"), is("baz"));
85 client.setHeaders(Collections.singletonMap("foo", (String) null));
86 assertThat(client.getRequestHeader("foo"), nullValue());
87 }
88
89 @Test
90 public void testGet() throws IOException {
91 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/get?foo=bar")).connect(progress);
92 assertThat(response.getRequestMethod(), is("GET"));
93 assertThat(response.getResponseCode(), is(200));
94 assertThat(response.getResponseMessage(), is("OK"));
95 assertThat(response.getContentType(), is("application/json"));
96 assertThat(response.getHeaderField("Content-Type"), is("application/json"));
97 assertThat(response.getHeaderField("Content-TYPE"), is("application/json"));
98 assertThat(response.getHeaderFields().get("Content-Type"), is(Collections.singletonList("application/json")));
99 assertThat(response.getHeaderFields().get("Content-TYPE"), is(Collections.singletonList("application/json")));
100 try (InputStream in = response.getContent();
101 JsonReader json = JsonProvider.provider().createReader(in)) {
102 final JsonObject root = json.readObject();
103 assertThat(root.getJsonObject("args").getString("foo"), is("bar"));
104 assertThat(root.getString("url"), is("https://httpbin.org/get?foo=bar"));
105 }
106 }
107
108 @Test
109 public void testUserAgent() throws IOException {
110 try (InputStream in = HttpClient.create(new URL("https://httpbin.org/user-agent")).connect(progress).getContent();
111 JsonReader json = JsonProvider.provider().createReader(in)) {
112 assertThat(json.readObject().getString("user-agent"), is(Version.getInstance().getFullAgentString()));
113 }
114 }
115
116 @Test
117 public void testFetchUtf8Content() throws IOException {
118 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/encoding/utf8")).connect(progress);
119 assertThat(response.getResponseCode(), is(200));
120 final String content = response.fetchContent();
121 assertThat(content, containsString("UTF-8 encoded sample plain-text file"));
122 assertThat(content, containsString("\u2200x\u2208\u211d:"));
123 }
124
125 @Test
126 public void testPost() throws IOException {
127 final String text = "Hello World!\nGeetings from JOSM, the Java OpenStreetMap Editor";
128 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/post"), "POST")
129 .setHeader("Content-Type", "text/plain")
130 .setRequestBody(text.getBytes(StandardCharsets.UTF_8))
131 .setFinishOnCloseOutput(false) // to fix #12583, not sure if it's the best way to do it
132 .connect(progress);
133 assertThat(response.getResponseCode(), is(200));
134 try (InputStream in = response.getContent();
135 JsonReader json = JsonProvider.provider().createReader(in)) {
136 assertThat(json.readObject().getString("data"), is(text));
137 }
138 }
139
140 @Test
141 public void testPostZero() throws IOException {
142 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/post"), "POST")
143 .setHeader("Content-Type", "text/plain")
144 .setRequestBody("".getBytes(StandardCharsets.UTF_8))
145 .setFinishOnCloseOutput(false) // to fix #12583, not sure if it's the best way to do it
146 .connect(progress);
147 assertThat(response.getResponseCode(), is(200));
148 try (InputStream in = response.getContent();
149 JsonReader json = JsonProvider.provider().createReader(in)) {
150 assertThat(json.readObject().getString("data"), is(""));
151 }
152 }
153
154 @Test
155 public void testRelativeRedirects() throws IOException {
156 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/relative-redirect/3")).connect(progress);
157 assertThat(response.getResponseCode(), is(200));
158 assertThat(response.getContentLength() > 100, is(true));
159 }
160
161 @Test
162 public void testAbsoluteRedirects() throws IOException {
163 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/absolute-redirect/3")).connect(progress);
164 assertThat(response.getResponseCode(), is(200));
165 assertThat(response.getContentLength() > 100, is(true));
166 }
167
168 @Test(expected = IOException.class)
169 public void testTooMuchRedirects() throws IOException {
170 HttpClient.create(new URL("https://httpbin.org/redirect/3")).setMaxRedirects(2).connect(progress);
171 }
172
173 @Test
174 public void testHttp418() throws IOException {
175 // https://tools.ietf.org/html/rfc2324
176 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/status/418")).connect(progress);
177 assertThat(response.getResponseCode(), is(418));
178 assertThat(response.getResponseMessage(), is("I'M A TEAPOT"));
179 final String content = response.fetchContent();
180 assertThat(content, containsString("-=[ teapot ]=-"));
181 assertThat(captured.getMessage(), containsString("-=[ teapot ]=-"));
182 assertThat(captured.getLevel(), is(Logging.LEVEL_DEBUG));
183 }
184
185 @Test()
186 public void testHttp401() throws IOException {
187 // https://tools.ietf.org/html/rfc2324
188 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/status/401")).connect(progress);
189 assertThat(response.getResponseCode(), is(401));
190 assertThat(response.getResponseMessage(), is("UNAUTHORIZED"));
191 final String content = response.fetchContent();
192 assertThat(content, is(""));
193 assertThat(captured.getMessage(), containsString("Server did not return any body"));
194 assertThat(captured.getLevel(), is(Logging.LEVEL_DEBUG));
195 }
196
197 @Test
198 public void testHttp402() throws IOException {
199 // https://tools.ietf.org/html/rfc2324
200 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/status/402")).connect(progress);
201 assertThat(response.getResponseCode(), is(402));
202 assertThat(response.getResponseMessage(), is("PAYMENT REQUIRED"));
203 final String content = response.fetchContent();
204 assertThat(content, containsString("Fuck you, pay me!"));
205 assertThat(captured.getMessage(), containsString("Fuck you, pay me!"));
206 assertThat(captured.getLevel(), is(Logging.LEVEL_DEBUG));
207 }
208
209 @Test
210 public void testHttp403() throws IOException {
211 // https://tools.ietf.org/html/rfc2324
212 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/status/403")).connect(progress);
213 assertThat(response.getResponseCode(), is(403));
214 assertThat(response.getResponseMessage(), is("FORBIDDEN"));
215 final String content = response.fetchContent();
216 assertThat(content, is(""));
217 assertThat(captured.getMessage(), containsString("Server did not return any body"));
218 assertThat(captured.getLevel(), is(Logging.LEVEL_DEBUG));
219 }
220
221 @Test
222 public void testHttp404() throws IOException {
223 // https://tools.ietf.org/html/rfc2324
224 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/status/404")).connect(progress);
225 assertThat(response.getResponseCode(), is(404));
226 assertThat(response.getResponseMessage(), is("NOT FOUND"));
227 final String content = response.fetchContent();
228 assertThat(content, is(""));
229 assertThat(captured.getMessage(), containsString("Server did not return any body"));
230 assertThat(captured.getLevel(), is(Logging.LEVEL_DEBUG));
231 }
232
233 @Test
234 public void testHttp500() throws IOException {
235 // https://tools.ietf.org/html/rfc2324
236 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/status/500")).connect(progress);
237 assertThat(response.getResponseCode(), is(500));
238 assertThat(response.getResponseMessage(), is("INTERNAL SERVER ERROR"));
239 final String content = response.fetchContent();
240 assertThat(content, containsString(""));
241 assertThat(captured.getMessage(), containsString("Server did not return any body"));
242 assertThat(captured.getLevel(), is(Logging.LEVEL_DEBUG));
243 }
244
245 /**
246 * Checks that a slow request is well handled if it completes before the timeout.
247 * @throws IOException if any I/O error occurs
248 */
249 @Test
250 public void testRequestInTime() throws IOException {
251 final HttpClient.Response response = HttpClient.create(new URL("https://httpbin.org/delay/1")).setReadTimeout(1500).connect(progress);
252 assertThat(response.getResponseCode(), is(200));
253 }
254
255 /**
256 * Checks that a slow request results in the expected exception if it exceeds the timeout.
257 * @throws IOException always
258 */
259 @Test(expected = IOException.class)
260 public void testTakesTooLong() throws IOException {
261 HttpClient.create(new URL("https://httpbin.org/delay/1")).setReadTimeout(500).connect(progress);
262 }
263
264 /**
265 * Test of {@link HttpClient.Response#uncompress} method with Gzip compression.
266 * @throws IOException if any I/O error occurs
267 */
268 @Test
269 public void testOpenUrlGzip() throws IOException {
270 final URL url = new URL("https://www.openstreetmap.org/trace/1613906/data");
271 try (BufferedReader x = HttpClient.create(url).connect().uncompress(true).getContentReader()) {
272 Assert.assertTrue(x.readLine().startsWith("<?xml version="));
273 }
274 }
275
276 /**
277 * Test of {@link HttpClient.Response#uncompress} method with Bzip compression.
278 * @throws IOException if any I/O error occurs
279 */
280 @Test
281 public void testOpenUrlBzip() throws IOException {
282 final URL url = new URL("https://www.openstreetmap.org/trace/785544/data");
283 try (BufferedReader x = HttpClient.create(url).connect().uncompress(true).getContentReader()) {
284 Assert.assertTrue(x.readLine().startsWith("<?xml version="));
285 }
286 }
287
288 /**
289 * Test of {@link HttpClient.Response#uncompress} method with Bzip compression.
290 * @throws IOException if any I/O error occurs
291 */
292 @Test
293 public void testTicket9660() throws IOException {
294 final URL url = new URL("http://www.openstreetmap.org/trace/1350010/data");
295 try (BufferedReader x = HttpClient.create(url).connect()
296 .uncompress(true).uncompressAccordingToContentDisposition(true).getContentReader()) {
297 Assert.assertTrue(x.readLine().startsWith("<?xml version="));
298 }
299 }
300}
Note: See TracBrowser for help on using the repository browser.