Debian Codegraph @

tests/test_http.py

raw
1 import email.utils
2 import errno
3 from http.client import BadStatusLine
4 import os
5 import pytest
6 import socket
7 from unittest import mock
8 import urllib
9
10 import httplib2
11 import tests
12
13
14 def _raise_connection_refused_exception(*args, **kwargs):
15 raise socket.error(errno.ECONNREFUSED, "Connection refused.")
16
17
18 def test_connection_type():
19 http = httplib2.Http()
20 http.force_exception_to_status_code = False
21 response, content = http.request(tests.DUMMY_URL, connection_type=tests.MockHTTPConnection)
22 assert response["content-location"] == tests.DUMMY_URL
23 assert content == b"the body"
24
25
26 def test_bad_status_line_retry():
27 http = httplib2.Http()
28 old_retries = httplib2.RETRIES
29 httplib2.RETRIES = 1
30 http.force_exception_to_status_code = False
31 try:
32 response, content = http.request(tests.DUMMY_URL, connection_type=tests.MockHTTPBadStatusConnection)
33 except BadStatusLine:
34 assert tests.MockHTTPBadStatusConnection.num_calls == 2
35 httplib2.RETRIES = old_retries
36
37
38 def test_unknown_server():
39 http = httplib2.Http()
40 http.force_exception_to_status_code = False
41 with tests.assert_raises(httplib2.ServerNotFoundError):
42 with mock.patch("socket.socket.connect", side_effect=socket.gaierror):
43 http.request("http://no-such-hostname./")
44
45 # Now test with exceptions turned off
46 http.force_exception_to_status_code = True
47 response, content = http.request("http://no-such-hostname./")
48 assert response["content-type"] == "text/plain"
49 assert content.startswith(b"Unable to find")
50 assert response.status == 400
51
52
53 @mock.patch("socket.socket.connect", spec=True)
54 def test_connection_refused_raises_exception(mock_socket_connect):
55 mock_socket_connect.side_effect = _raise_connection_refused_exception
56 http = httplib2.Http()
57 http.force_exception_to_status_code = False
58 with tests.assert_raises(socket.error):
59 http.request(tests.DUMMY_URL)
60
61
62 @mock.patch("socket.socket.connect", spec=True)
63 def test_connection_refused_returns_response(mock_socket_connect):
64 mock_socket_connect.side_effect = _raise_connection_refused_exception
65 http = httplib2.Http()
66 http.force_exception_to_status_code = True
67 response, content = http.request(tests.DUMMY_URL)
68 content = content.lower()
69 assert response["content-type"] == "text/plain"
70 assert b"connection refused" in content or b"actively refused" in content or b"socket is not connected" in content
71 assert response.status == 400
72
73
74 def test_get_iri():
75 http = httplib2.Http()
76 query = u"?a=\N{CYRILLIC CAPITAL LETTER DJE}"
77 with tests.server_reflect() as uri:
78 response, content = http.request(uri + query, "GET")
79 assert response.status == 200
80 reflected = tests.HttpRequest.from_bytes(content)
81 assert reflected.uri == "/?a=%D0%82"
82
83
84 def test_get_is_default_method():
85 # Test that GET is the default method
86 http = httplib2.Http()
87 with tests.server_reflect() as uri:
88 response, content = http.request(uri)
89 assert response.status == 200
90 reflected = tests.HttpRequest.from_bytes(content)
91 assert reflected.method == "GET"
92
93
94 def test_different_methods():
95 # Test that all methods can be used
96 http = httplib2.Http()
97 methods = ["GET", "PUT", "DELETE", "POST", "unknown"]
98 with tests.server_reflect(request_count=len(methods)) as uri:
99 for method in methods:
100 response, content = http.request(uri, method, body=b" ")
101 assert response.status == 200
102 reflected = tests.HttpRequest.from_bytes(content)
103 assert reflected.method == method
104
105
106 def test_head_read():
107 # Test that we don't try to read the response of a HEAD request
108 # since httplib blocks response.read() for HEAD requests.
109 http = httplib2.Http()
110 respond_with = b"HTTP/1.0 200 OK\r\ncontent-length: " b"14\r\n\r\nnon-empty-body"
111 with tests.server_const_bytes(respond_with) as uri:
112 response, content = http.request(uri, "HEAD")
113 assert response.status == 200
114 assert content == b""
115
116
117 def test_get_no_cache():
118 # Test that can do a GET w/o the cache turned on.
119 http = httplib2.Http()
120 with tests.server_const_http() as uri:
121 response, content = http.request(uri, "GET")
122 assert response.status == 200
123 assert response.previous is None
124
125
126 def test_user_agent():
127 # Test that we provide a default user-agent
128 http = httplib2.Http()
129 with tests.server_reflect() as uri:
130 response, content = http.request(uri, "GET")
131 assert response.status == 200
132 reflected = tests.HttpRequest.from_bytes(content)
133 assert reflected.headers.get("user-agent", "").startswith("Python-httplib2/")
134
135
136 def test_user_agent_non_default():
137 # Test that the default user-agent can be over-ridden
138 http = httplib2.Http()
139 with tests.server_reflect() as uri:
140 response, content = http.request(uri, "GET", headers={"User-Agent": "fred/1.0"})
141 assert response.status == 200
142 reflected = tests.HttpRequest.from_bytes(content)
143 assert reflected.headers.get("user-agent") == "fred/1.0"
144
145
146 def test_get_300_with_location():
147 # Test the we automatically follow 300 redirects if a Location: header is provided
148 http = httplib2.Http()
149 final_content = b"This is the final destination.\n"
150 routes = {
151 "/final": tests.http_response_bytes(body=final_content),
152 "": tests.http_response_bytes(status="300 Multiple Choices", headers={"location": "/final"}),
153 }
154 with tests.server_route(routes, request_count=2) as uri:
155 response, content = http.request(uri, "GET")
156 assert response.status == 200
157 assert content == final_content
158 assert response.previous.status == 300
159 assert not response.previous.fromcache
160
161 # Confirm that the intermediate 300 is not cached
162 with tests.server_route(routes, request_count=2) as uri:
163 response, content = http.request(uri, "GET")
164 assert response.status == 200
165 assert content == final_content
166 assert response.previous.status == 300
167 assert not response.previous.fromcache
168
169
170 def test_get_300_with_location_noredirect():
171 # Test the we automatically follow 300 redirects if a Location: header is provided
172 http = httplib2.Http()
173 http.follow_redirects = False
174 response = tests.http_response_bytes(
175 status="300 Multiple Choices",
176 headers={"location": "/final"},
177 body=b"redirect body",
178 )
179 with tests.server_const_bytes(response) as uri:
180 response, content = http.request(uri, "GET")
181 assert response.status == 300
182
183
184 def test_get_300_without_location():
185 # Not giving a Location: header in a 300 response is acceptable
186 # In which case we just return the 300 response
187 http = httplib2.Http()
188 with tests.server_const_http(status="300 Multiple Choices", body=b"redirect body") as uri:
189 response, content = http.request(uri, "GET")
190 assert response.status == 300
191 assert response.previous is None
192 assert content == b"redirect body"
193
194
195 def test_get_301():
196 # Test that we automatically follow 301 redirects
197 # and that we cache the 301 response
198 http = httplib2.Http(cache=tests.get_cache_path())
199 destination = ""
200 routes = {
201 "/final": tests.http_response_bytes(body=b"This is the final destination.\n"),
202 "": tests.http_response_bytes(
203 status="301 Now where did I leave that URL",
204 headers={"location": "/final"},
205 body=b"redirect body",
206 ),
207 }
208 with tests.server_route(routes, request_count=3) as uri:
209 destination = urllib.parse.urljoin(uri, "/final")
210 response1, content1 = http.request(uri, "GET")
211 response2, content2 = http.request(uri, "GET")
212 assert response1.status == 200
213 assert "content-location" in response2
214 assert response1["content-location"] == destination
215 assert content1 == b"This is the final destination.\n"
216 assert response1.previous.status == 301
217 assert not response1.previous.fromcache
218
219 assert response2.status == 200
220 assert response2["content-location"] == destination
221 assert content2 == b"This is the final destination.\n"
222 assert response2.previous.status == 301
223 assert response2.previous.fromcache
224
225
226 def test_head_301():
227 # Test that we automatically follow 301 redirects
228 http = httplib2.Http()
229 destination = ""
230 routes = {
231 "/final": tests.http_response_bytes(body=b"This is the final destination.\n"),
232 "": tests.http_response_bytes(
233 status="301 Now where did I leave that URL",
234 headers={"location": "/final"},
235 body=b"redirect body",
236 ),
237 }
238 with tests.server_route(routes, request_count=2) as uri:
239 destination = urllib.parse.urljoin(uri, "/final")
240 response, content = http.request(uri, "HEAD")
241 assert response.status == 200
242 assert response["content-location"] == destination
243 assert response.previous.status == 301
244 assert not response.previous.fromcache
245
246
247 @pytest.mark.xfail(reason=("FIXME: 301 cache works only with follow_redirects, should work regardless"))
248 def test_get_301_no_redirect():
249 # Test that we cache the 301 response
250 http = httplib2.Http(cache=tests.get_cache_path(), timeout=0.5)
251 http.follow_redirects = False
252 response = tests.http_response_bytes(
253 status="301 Now where did I leave that URL",
254 headers={"location": "/final", "cache-control": "max-age=300"},
255 body=b"redirect body",
256 add_date=True,
257 )
258 with tests.server_const_bytes(response) as uri:
259 response, _ = http.request(uri, "GET")
260 assert response.status == 301
261 assert not response.fromcache
262 response, _ = http.request(uri, "GET")
263 assert response.status == 301
264 assert response.fromcache
265
266
267 def test_get_302():
268 # Test that we automatically follow 302 redirects
269 # and that we DO NOT cache the 302 response
270 http = httplib2.Http(cache=tests.get_cache_path())
271 second_url, final_url = "", ""
272 routes = {
273 "/final": tests.http_response_bytes(body=b"This is the final destination.\n"),
274 "/second": tests.http_response_bytes(
275 status="302 Found", headers={"location": "/final"}, body=b"second redirect"
276 ),
277 "": tests.http_response_bytes(status="302 Found", headers={"location": "/second"}, body=b"redirect body"),
278 }
279 with tests.server_route(routes, request_count=7) as uri:
280 second_url = urllib.parse.urljoin(uri, "/second")
281 final_url = urllib.parse.urljoin(uri, "/final")
282 response1, content1 = http.request(second_url, "GET")
283 response2, content2 = http.request(second_url, "GET")
284 response3, content3 = http.request(uri, "GET")
285 assert response1.status == 200
286 assert response1["content-location"] == final_url
287 assert content1 == b"This is the final destination.\n"
288 assert response1.previous.status == 302
289 assert not response1.previous.fromcache
290
291 assert response2.status == 200
292 # FIXME:
293 # assert response2.fromcache
294 assert response2["content-location"] == final_url
295 assert content2 == b"This is the final destination.\n"
296 assert response2.previous.status == 302
297 assert not response2.previous.fromcache
298 assert response2.previous["content-location"] == second_url
299
300 assert response3.status == 200
301 # FIXME:
302 # assert response3.fromcache
303 assert content3 == b"This is the final destination.\n"
304 assert response3.previous.status == 302
305 assert not response3.previous.fromcache
306
307
308 def test_get_302_redirection_limit():
309 # Test that we can set a lower redirection limit
310 # and that we raise an exception when we exceed
311 # that limit.
312 http = httplib2.Http()
313 http.force_exception_to_status_code = False
314 routes = {
315 "/second": tests.http_response_bytes(
316 status="302 Found", headers={"location": "/final"}, body=b"second redirect"
317 ),
318 "": tests.http_response_bytes(status="302 Found", headers={"location": "/second"}, body=b"redirect body"),
319 }
320 with tests.server_route(routes, request_count=4) as uri:
321 try:
322 http.request(uri, "GET", redirections=1)
323 assert False, "This should not happen"
324 except httplib2.RedirectLimit:
325 pass
326 except Exception:
327 assert False, "Threw wrong kind of exception "
328
329 # Re-run the test with out the exceptions
330 http.force_exception_to_status_code = True
331 response, content = http.request(uri, "GET", redirections=1)
332
333 assert response.status == 500
334 assert response.reason.startswith("Redirected more")
335 assert response["status"] == "302"
336 assert content == b"second redirect"
337 assert response.previous is not None
338
339
340 def test_get_302_no_location():
341 # Test that we throw an exception when we get
342 # a 302 with no Location: header.
343 http = httplib2.Http()
344 http.force_exception_to_status_code = False
345 with tests.server_const_http(status="302 Found", request_count=2) as uri:
346 try:
347 http.request(uri, "GET")
348 assert False, "Should never reach here"
349 except httplib2.RedirectMissingLocation:
350 pass
351 except Exception:
352 assert False, "Threw wrong kind of exception "
353
354 # Re-run the test with out the exceptions
355 http.force_exception_to_status_code = True
356 response, content = http.request(uri, "GET")
357
358 assert response.status == 500
359 assert response.reason.startswith("Redirected but")
360 assert "302" == response["status"]
361 assert content == b""
362
363
364 def test_303():
365 # Do a follow-up GET on a Location: header
366 # returned from a POST that gave a 303.
367 http = httplib2.Http()
368 routes = {
369 "/final": tests.make_http_reflect(),
370 "": tests.make_http_reflect(status="303 See Other", headers={"location": "/final"}),
371 }
372 with tests.server_route(routes, request_count=2) as uri:
373 response, content = http.request(uri, "POST", " ")
374 assert response.status == 200
375 reflected = tests.HttpRequest.from_bytes(content)
376 assert reflected.uri == "/final"
377 assert response.previous.status == 303
378
379 # Skip follow-up GET
380 http = httplib2.Http()
381 http.follow_redirects = False
382 with tests.server_route(routes, request_count=1) as uri:
383 response, content = http.request(uri, "POST", " ")
384 assert response.status == 303
385
386 # All methods can be used
387 http = httplib2.Http()
388 cases = "DELETE GET HEAD POST PUT EVEN_NEW_ONES".split(" ")
389 with tests.server_route(routes, request_count=len(cases) * 2) as uri:
390 for method in cases:
391 response, content = http.request(uri, method, body=b"q q")
392 assert response.status == 200
393 reflected = tests.HttpRequest.from_bytes(content)
394 assert reflected.method == "GET"
395
396
397 def test_etag_used():
398 # Test that we use ETags properly to validate our cache
399 cache_path = tests.get_cache_path()
400 http = httplib2.Http(cache=cache_path)
401 response_kwargs = dict(
402 add_date=True,
403 add_etag=True,
404 body=b"something",
405 headers={"cache-control": "public,max-age=300"},
406 )
407
408 def handler(request):
409 if request.headers.get("range"):
410 return tests.http_response_bytes(status=206, **response_kwargs)
411 return tests.http_response_bytes(**response_kwargs)
412
413 with tests.server_request(handler, request_count=2) as uri:
414 response, _ = http.request(uri, "GET", headers={"accept-encoding": "identity"})
415 assert response["etag"] == '"437b930db84b8079c2dd804a71936b5f"'
416
417 http.request(uri, "GET", headers={"accept-encoding": "identity"})
418 response, _ = http.request(
419 uri,
420 "GET",
421 headers={"accept-encoding": "identity", "cache-control": "must-revalidate"},
422 )
423 assert response.status == 200
424 assert response.fromcache
425
426 # TODO: API to read cache item, at least internal to tests
427 cache_file_name = os.path.join(cache_path, httplib2.safename(httplib2.urlnorm(uri)[-1]))
428 with open(cache_file_name, "r") as f:
429 status_line = f.readline()
430 assert status_line.startswith("status:")
431
432 response, content = http.request(uri, "HEAD", headers={"accept-encoding": "identity"})
433 assert response.status == 200
434 assert response.fromcache
435
436 response, content = http.request(uri, "GET", headers={"accept-encoding": "identity", "range": "bytes=0-0"})
437 assert response.status == 206
438 assert not response.fromcache
439
440
441 def test_etag_ignore():
442 # Test that we can forcibly ignore ETags
443 http = httplib2.Http(cache=tests.get_cache_path())
444 response_kwargs = dict(add_date=True, add_etag=True)
445 with tests.server_reflect(request_count=3, **response_kwargs) as uri:
446 response, content = http.request(uri, "GET", headers={"accept-encoding": "identity"})
447 assert response.status == 200
448 assert response["etag"] != ""
449
450 response, content = http.request(
451 uri,
452 "GET",
453 headers={"accept-encoding": "identity", "cache-control": "max-age=0"},
454 )
455 reflected = tests.HttpRequest.from_bytes(content)
456 assert reflected.headers.get("if-none-match")
457
458 http.ignore_etag = True
459 response, content = http.request(
460 uri,
461 "GET",
462 headers={"accept-encoding": "identity", "cache-control": "max-age=0"},
463 )
464 assert not response.fromcache
465 reflected = tests.HttpRequest.from_bytes(content)
466 assert not reflected.headers.get("if-none-match")
467
468
469 def test_etag_override():
470 # Test that we can forcibly ignore ETags
471 http = httplib2.Http(cache=tests.get_cache_path())
472 response_kwargs = dict(add_date=True, add_etag=True)
473 with tests.server_reflect(request_count=3, **response_kwargs) as uri:
474 response, _ = http.request(uri, "GET", headers={"accept-encoding": "identity"})
475 assert response.status == 200
476 assert response["etag"] != ""
477
478 response, content = http.request(
479 uri,
480 "GET",
481 headers={"accept-encoding": "identity", "cache-control": "max-age=0"},
482 )
483 assert response.status == 200
484 reflected = tests.HttpRequest.from_bytes(content)
485 assert reflected.headers.get("if-none-match")
486 assert reflected.headers.get("if-none-match") != "fred"
487
488 response, content = http.request(
489 uri,
490 "GET",
491 headers={
492 "accept-encoding": "identity",
493 "cache-control": "max-age=0",
494 "if-none-match": "fred",
495 },
496 )
497 assert response.status == 200
498 reflected = tests.HttpRequest.from_bytes(content)
499 assert reflected.headers.get("if-none-match") == "fred"
500
501
502 @pytest.mark.skip(reason="was commented in legacy code")
503 def test_get_304_end_to_end():
504 pass
505 # Test that end to end headers get overwritten in the cache
506 # uri = urllib.parse.urljoin(base, "304/end2end.cgi")
507 # response, content = http.request(uri, 'GET')
508 # assertNotEqual(response['etag'], "")
509 # old_date = response['date']
510 # time.sleep(2)
511
512 # response, content = http.request(uri, 'GET', headers = {'Cache-Control': 'max-age=0'})
513 # # The response should be from the cache, but the Date: header should be updated.
514 # new_date = response['date']
515 # assert new_date != old_date
516 # assert response.status == 200
517 # assert response.fromcache == True
518
519
520 def test_get_304_last_modified():
521 # Test that we can still handle a 304
522 # by only using the last-modified cache validator.
523 http = httplib2.Http(cache=tests.get_cache_path())
524 date = email.utils.formatdate()
525
526 def handler(read):
527 read()
528 yield tests.http_response_bytes(status=200, body=b"something", headers={"date": date, "last-modified": date})
529
530 request2 = read()
531 assert request2.headers["if-modified-since"] == date
532 yield tests.http_response_bytes(status=304)
533
534 with tests.server_yield(handler, request_count=2) as uri:
535 response, content = http.request(uri, "GET")
536 assert response.get("last-modified") == date
537
538 response, content = http.request(uri, "GET")
539 assert response.status == 200
540 assert response.fromcache
541
542
543 def test_get_307():
544 # Test that we do follow 307 redirects but
545 # do not cache the 307
546 http = httplib2.Http(cache=tests.get_cache_path(), timeout=1)
547 r307 = tests.http_response_bytes(status=307, headers={"location": "/final"})
548 r200 = tests.http_response_bytes(
549 status=200,
550 add_date=True,
551 body=b"final content\n",
552 headers={"cache-control": "max-age=300"},
553 )
554
555 with tests.server_list_http([r307, r200, r307]) as uri:
556 response, content = http.request(uri, "GET")
557 assert response.previous.status == 307
558 assert not response.previous.fromcache
559 assert response.status == 200
560 assert not response.fromcache
561 assert content == b"final content\n"
562
563 response, content = http.request(uri, "GET")
564 assert response.previous.status == 307
565 assert not response.previous.fromcache
566 assert response.status == 200
567 assert response.fromcache
568 assert content == b"final content\n"
569
570
571 def test_post_307():
572 # 307: follow with same method
573 http = httplib2.Http(cache=tests.get_cache_path(), timeout=1)
574 http.follow_all_redirects = True
575 r307 = tests.http_response_bytes(status=307, headers={"location": "/final"})
576 r200 = tests.http_response_bytes(status=200, body=b"final content\n")
577
578 with tests.server_list_http([r307, r200, r307, r200]) as uri:
579 response, content = http.request(uri, "POST")
580 assert response.previous.status == 307
581 assert not response.previous.fromcache
582 assert response.status == 200
583 assert not response.fromcache
584 assert content == b"final content\n"
585
586 response, content = http.request(uri, "POST")
587 assert response.previous.status == 307
588 assert not response.previous.fromcache
589 assert response.status == 200
590 assert not response.fromcache
591 assert content == b"final content\n"
592
593
594 def test_change_308():
595 # 308: follow with same method, cache redirect
596 http = httplib2.Http(cache=tests.get_cache_path(), timeout=1)
597 routes = {
598 "/final": tests.make_http_reflect(),
599 "": tests.http_response_bytes(
600 status="308 Permanent Redirect",
601 add_date=True,
602 headers={"cache-control": "max-age=300", "location": "/final"},
603 ),
604 }
605
606 with tests.server_route(routes, request_count=3) as uri:
607 response, content = http.request(uri, "CHANGE", body=b"hello308")
608 assert response.previous.status == 308
609 assert not response.previous.fromcache
610 assert response.status == 200
611 assert not response.fromcache
612 assert content.startswith(b"CHANGE /final HTTP")
613
614 response, content = http.request(uri, "CHANGE")
615 assert response.previous.status == 308
616 assert response.previous.fromcache
617 assert response.status == 200
618 assert not response.fromcache
619 assert content.startswith(b"CHANGE /final HTTP")
620
621
622 def test_get_410():
623 # Test that we pass 410's through
624 http = httplib2.Http()
625 with tests.server_const_http(status=410) as uri:
626 response, content = http.request(uri, "GET")
627 assert response.status == 410
628
629
630 def test_get_duplicate_headers():
631 # Test that duplicate headers get concatenated via ','
632 http = httplib2.Http()
633 response = b"""HTTP/1.0 200 OK\r\n\
634 Link: link1\r\n\
635 Content-Length: 7\r\n\
636 Link: link2\r\n\r\n\
637 content"""
638 with tests.server_const_bytes(response) as uri:
639 response, content = http.request(uri, "GET")
640 assert response.status == 200
641 assert content == b"content"
642 assert response["link"], "link1, link2"
643
644
645 def test_custom_redirect_codes():
646 http = httplib2.Http()
647 http.redirect_codes = set([300])
648 with tests.server_const_http(status=301, request_count=1) as uri:
649 response, content = http.request(uri, "GET")
650 assert response.status == 301
651 assert response.previous is None
652
653
654 def test_cwe93_inject_crlf():
655 # https://cwe.mitre.org/data/definitions/93.html
656 # GET /?q= HTTP/1.1 <- injected "HTTP/1.1" from attacker
657 # injected: attack
658 # ignore-http: HTTP/1.1 <- nominal "HTTP/1.1" from library
659 # Host: localhost:57285
660 http = httplib2.Http()
661 with tests.server_reflect() as uri:
662 danger_url = urllib.parse.urljoin(uri, "?q= HTTP/1.1\r\ninjected: attack\r\nignore-http:")
663 response, content = http.request(danger_url, "GET")
664 assert response.status == 200
665 req = tests.HttpRequest.from_bytes(content)
666 assert req.headers.get("injected") is None
667
668
669 def test_inject_space():
670 # Injecting space into request line is precursor to CWE-93 and possibly other injections
671 http = httplib2.Http()
672 with tests.server_reflect() as uri:
673 # "\r\nignore-http:" suffix is nuance for current server implementation
674 # please only pay attention to space after "?q="
675 danger_url = urllib.parse.urljoin(uri, "?q= HTTP/1.1\r\nignore-http:")
676 response, content = http.request(danger_url, "GET")
677 assert response.status == 200
678 req = tests.HttpRequest.from_bytes(content)
679 expect = (
680 # new behavior after bpo-43882 fix
681 # https://github.com/httplib2/httplib2/issues/193
682 "/?q=%20HTTP/1.1ignore-http:",
683 # old behavior
684 "/?q=%20HTTP/1.1%0D%0Aignore-http:",
685 )
686 assert req.uri in expect