Skip to content
Myr

Refactor tests to use `MockTransport(<handler_function>)` (#1281)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Support Response(content=<bytes iterator>) * Update test for merged master * Add MockTransport for test cases * Use MockTransport for redirect tests * Reduce change footprint * Reduce change footprint * Clean up headers slightly * Update requirements.txt

authored by Tom Christie · committed by GitHub · parent 8a5050e · Browse files · 7 files+280 added−330 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

7 files+280 added−330 removed

  • tests:+279 added−329 removed
  • other:+1 added−1 removed

7 files+280 added−330 removed

modified:tests/client/test_cookies.py+17 added-41 removed
1import typing1import json2from http.cookiejar import Cookie, CookieJar34import httpcore54import httpx7from httpx._content_streams import ByteStream, ContentStream, JSONStream5from tests.utils import MockTransport6710def get_header_value(headers, key, default=None):11 lookup = key.encode("ascii").lower()12 for header_key, header_value in headers:13 if header_key.lower() == lookup:14 return header_value.decode("ascii")15 return default8def get_and_set_cookies(request: httpx.Request) -> httpx.Response:9 if request.url.path == "/echo_cookies":10 data = {"cookies": request.headers.get("cookie")}11 content = json.dumps(data).encode("utf-8")12 return httpx.Response(200, content=content)13 elif request.url.path == "/set_cookie":14 return httpx.Response(200, headers={"set-cookie": "example-name=example-value"})15 else:16 raise NotImplementedError() # pragma: no cover171818class MockTransport(httpcore.SyncHTTPTransport):19 def request(20 self,21 method: bytes,22 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],23 headers: typing.List[typing.Tuple[bytes, bytes]] = None,24 stream: httpcore.SyncByteStream = None,25 timeout: typing.Mapping[str, typing.Optional[float]] = None,26 ) -> typing.Tuple[27 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream28 ]:29 host, scheme, port, path = url30 body: ContentStream31 if path.startswith(b"/echo_cookies"):32 cookie = get_header_value(headers, "cookie")33 body = JSONStream({"cookies": cookie})34 return b"HTTP/1.1", 200, b"OK", [], body35 elif path.startswith(b"/set_cookie"):36 headers = [(b"set-cookie", b"example-name=example-value")]37 body = ByteStream(b"")38 return b"HTTP/1.1", 200, b"OK", headers, body39 else:40 raise NotImplementedError() # pragma: no cover414219def test_set_cookie() -> None:20 """21 Send a request including a cookie.22 """23 url = "http://example.org/echo_cookies"24 cookies = {"example-name": "example-value"}2550 client = httpx.Client(transport=MockTransport())26 client = httpx.Client(transport=MockTransport(get_and_set_cookies))27 response = client.get(url, cookies=cookies)2829 assert response.status_code == 20030 assert response.json() == {"cookies": "example-name=example-value"}
26 unmodified lines
57 rfc2109=False,58 )59 cookies.set_cookie(cookie)6085 client = httpx.Client(transport=MockTransport())61 client = httpx.Client(transport=MockTransport(get_and_set_cookies))62 response = client.get(url, cookies=cookies)6364 assert response.status_code == 20065 assert response.json() == {"cookies": "example-name=example-value"}
26 unmodified lines
92 rfc2109=False,93 )94 cookies.set_cookie(cookie)95120 client = httpx.Client(transport=MockTransport())96 client = httpx.Client(transport=MockTransport(get_and_set_cookies))97 client.cookies = cookies # type: ignore98 response = client.get(url)99100 assert response.status_code == 200
8 unmodified lines
109 url = "http://example.org/echo_cookies"110 cookies = httpx.Cookies()111 cookies["example-name"] = "example-value"112137 client = httpx.Client(transport=MockTransport())113 client = httpx.Client(transport=MockTransport(get_and_set_cookies))114 response = client.get(url, cookies=cookies)115116 assert response.status_code == 200117 assert response.json() == {"cookies": "example-name=example-value"}
1 unmodified line
119120def test_get_cookie() -> None:121 url = "http://example.org/set_cookie"122147 client = httpx.Client(transport=MockTransport())123 client = httpx.Client(transport=MockTransport(get_and_set_cookies))124 response = client.get(url)125126 assert response.status_code == 200127 assert response.cookies["example-name"] == "example-value"
3 unmodified lines
131def test_cookie_persistence() -> None:132 """133 Ensure that Client instances persist cookies between requests.134 """159 client = httpx.Client(transport=MockTransport())135 client = httpx.Client(transport=MockTransport(get_and_set_cookies))136137 response = client.get("http://example.org/echo_cookies")138 assert response.status_code == 200139 assert response.json() == {"cookies": None}
9 unmodified lines
modified:tests/client/test_headers.py+13 added-27 removed
1#!/usr/bin/env python323import typing3import json45import httpcore5import pytest67import httpx9from httpx._content_streams import ContentStream, JSONStream8from tests.utils import MockTransport91012class MockTransport(httpcore.SyncHTTPTransport):13 def request(14 self,15 method: bytes,16 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],17 headers: typing.List[typing.Tuple[bytes, bytes]] = None,18 stream: httpcore.SyncByteStream = None,19 timeout: typing.Mapping[str, typing.Optional[float]] = None,20 ) -> typing.Tuple[21 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream22 ]:23 assert headers is not None24 headers_dict = {25 key.decode("ascii"): value.decode("ascii") for key, value in headers26 }27 body = JSONStream({"headers": headers_dict})28 return b"HTTP/1.1", 200, b"OK", [], body11def echo_headers(request: httpx.Request) -> httpx.Response:12 data = {"headers": dict(request.headers)}13 content = json.dumps(data).encode("utf-8")14 return httpx.Response(200, content=content)151617def test_client_header():18 """
1 unmodified line
20 """21 url = "http://example.org/echo_headers"22 headers = {"Example-Header": "example-value"}2338 client = httpx.Client(transport=MockTransport(), headers=headers)24 client = httpx.Client(transport=MockTransport(echo_headers), headers=headers)25 response = client.get(url)2627 assert response.status_code == 20028 assert response.json() == {
11 unmodified lines
40def test_header_merge():41 url = "http://example.org/echo_headers"42 client_headers = {"User-Agent": "python-myclient/0.2.1"}43 request_headers = {"X-Auth-Token": "FooBarBazToken"}58 client = httpx.Client(transport=MockTransport(), headers=client_headers)44 client = httpx.Client(transport=MockTransport(echo_headers), headers=client_headers)45 response = client.get(url, headers=request_headers)4647 assert response.status_code == 20048 assert response.json() == {
11 unmodified lines
60def test_header_merge_conflicting_headers():61 url = "http://example.org/echo_headers"62 client_headers = {"X-Auth-Token": "FooBar"}63 request_headers = {"X-Auth-Token": "BazToken"}78 client = httpx.Client(transport=MockTransport(), headers=client_headers)64 client = httpx.Client(transport=MockTransport(echo_headers), headers=client_headers)65 response = client.get(url, headers=request_headers)6667 assert response.status_code == 20068 assert response.json() == {
9 unmodified lines
787980def test_header_update():81 url = "http://example.org/echo_headers"96 client = httpx.Client(transport=MockTransport())82 client = httpx.Client(transport=MockTransport(echo_headers))83 first_response = client.get(url)84 client.headers.update(85 {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}86 )
28 unmodified lines
115 Remove a default header from the Client.116 """117 url = "http://example.org/echo_headers"118133 client = httpx.Client(transport=MockTransport())119 client = httpx.Client(transport=MockTransport(echo_headers))120 del client.headers["User-Agent"]121122 response = client.get(url)123
21 unmodified lines
145 be present.146 """147 url = "http://username:password@example.org:80/echo_headers"148163 client = httpx.Client(transport=MockTransport())149 client = httpx.Client(transport=MockTransport(echo_headers))150 response = client.get(url)151152 assert response.status_code == 200153 assert response.json() == {
14 unmodified lines
168 the Host header.169 """170 url = "http://username:password@example.org:123/echo_headers"171186 client = httpx.Client(transport=MockTransport())172 client = httpx.Client(transport=MockTransport(echo_headers))173 response = client.get(url)174175 assert response.status_code == 200176 assert response.json() == {
14 unmodified lines
modified:tests/client/test_queryparams.py+6 added-19 removed
1import typing23import httpcore41import httpx6from httpx._content_streams import ContentStream, JSONStream2from tests.utils import MockTransport349class MockTransport(httpcore.SyncHTTPTransport):10 def request(11 self,12 method: bytes,13 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],14 headers: typing.List[typing.Tuple[bytes, bytes]] = None,15 stream: httpcore.SyncByteStream = None,16 timeout: typing.Mapping[str, typing.Optional[float]] = None,17 ) -> typing.Tuple[18 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream19 ]:20 body = JSONStream({"ok": "ok"})21 return b"HTTP/1.1", 200, b"OK", [], body5def hello_world(request: httpx.Request) -> httpx.Response:6 return httpx.Response(200, content=b"Hello, world")789def test_client_queryparams():10 client = httpx.Client(params={"a": "b"})
15 unmodified lines
26def test_client_queryparams_echo():27 url = "http://example.org/echo_queryparams"28 client_queryparams = "first=str"29 request_queryparams = {"second": "dict"}45 client = httpx.Client(transport=MockTransport(), params=client_queryparams)30 client = httpx.Client(31 transport=MockTransport(hello_world), params=client_queryparams32 )33 response = client.get(url, params=request_queryparams)3435 assert response.status_code == 20036 assert response.url == "http://example.org/echo_queryparams?first=str&second=dict"
modified:tests/client/test_redirects.py+145 added-219 removed
1import json2import typing3from urllib.parse import parse_qs23import httpcore4import pytest56import httpx9from httpx._content_streams import ByteStream, ContentStream, IteratorStream7from tests.utils import AsyncMockTransport, MockTransport8912def get_header_value(headers, key, default=None):13 lookup = key.encode("ascii").lower()14 for header_key, header_value in headers:15 if header_key.lower() == lookup:16 return header_value.decode("ascii")17 return default10def redirects(request: httpx.Request) -> httpx.Response:11 if request.url.scheme not in ("http", "https"):12 raise httpcore.UnsupportedProtocol(13 f"Scheme {request.url.scheme!r} not supported."14 )1516 if request.url.path == "/no_redirect":17 return httpx.Response(200)1820class MockTransport:21 def _request(22 self,23 method: bytes,24 url: typing.Tuple[bytes, bytes, int, bytes],25 headers: typing.List[typing.Tuple[bytes, bytes]],26 stream: ContentStream,27 timeout: typing.Mapping[str, typing.Optional[float]] = None,28 ) -> typing.Tuple[29 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream30 ]:31 scheme, host, port, path = url32 if scheme not in (b"http", b"https"):33 raise httpcore.UnsupportedProtocol(f"Scheme {scheme!r} not supported.")19 elif request.url.path == "/redirect_301":20 status_code = httpx.codes.MOVED_PERMANENTLY21 content = b"<a href='https://example.org/'>here</a>"22 headers = {"location": "https://example.org/"}23 return httpx.Response(status_code, headers=headers, content=content)2435 path, _, query = path.partition(b"?")36 if path == b"/no_redirect":37 return b"HTTP/1.1", httpx.codes.OK, b"OK", [], ByteStream(b"")25 elif request.url.path == "/redirect_302":26 status_code = httpx.codes.FOUND27 headers = {"location": "https://example.org/"}28 return httpx.Response(status_code, headers=headers)2939 elif path == b"/redirect_301":30 elif request.url.path == "/redirect_303":31 status_code = httpx.codes.SEE_OTHER32 headers = {"location": "https://example.org/"}33 return httpx.Response(status_code, headers=headers)3441 def body():42 yield b"<a href='https://example.org/'>here</a>"35 elif request.url.path == "/relative_redirect":36 status_code = httpx.codes.SEE_OTHER37 headers = {"location": "/"}38 return httpx.Response(status_code, headers=headers)3944 status_code = httpx.codes.MOVED_PERMANENTLY45 headers = [(b"location", b"https://example.org/")]46 stream = IteratorStream(iterator=body())47 return b"HTTP/1.1", status_code, b"Moved Permanently", headers, stream40 elif request.url.path == "/malformed_redirect":41 status_code = httpx.codes.SEE_OTHER42 headers = {"location": "https://:443/"}43 return httpx.Response(status_code, headers=headers)4449 elif path == b"/redirect_302":50 status_code = httpx.codes.FOUND51 headers = [(b"location", b"https://example.org/")]52 return b"HTTP/1.1", status_code, b"Found", headers, ByteStream(b"")45 elif request.url.path == "/invalid_redirect":46 status_code = httpx.codes.SEE_OTHER47 raw_headers = [(b"location", "https://😇/".encode("utf-8"))]48 return httpx.Response(status_code, headers=raw_headers)4954 elif path == b"/redirect_303":55 status_code = httpx.codes.SEE_OTHER56 headers = [(b"location", b"https://example.org/")]57 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")50 elif request.url.path == "/no_scheme_redirect":51 status_code = httpx.codes.SEE_OTHER52 headers = {"location": "//example.org/"}53 return httpx.Response(status_code, headers=headers)5459 elif path == b"/relative_redirect":60 status_code = httpx.codes.SEE_OTHER61 headers = [(b"location", b"/")]62 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")6364 elif path == b"/malformed_redirect":65 status_code = httpx.codes.SEE_OTHER66 headers = [(b"location", b"https://:443/")]67 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")6869 elif path == b"/invalid_redirect":70 status_code = httpx.codes.SEE_OTHER71 headers = [(b"location", "https://😇/".encode("utf-8"))]72 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")7374 elif path == b"/no_scheme_redirect":75 status_code = httpx.codes.SEE_OTHER76 headers = [(b"location", b"//example.org/")]77 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")7879 elif path == b"/multiple_redirects":80 params = parse_qs(query.decode("ascii"))81 count = int(params.get("count", "0")[0])82 redirect_count = count - 183 code = httpx.codes.SEE_OTHER if count else httpx.codes.OK84 phrase = b"See Other" if count else b"OK"85 location = b"/multiple_redirects"55 elif request.url.path == "/multiple_redirects":56 params = httpx.QueryParams(request.url.query)57 count = int(params.get("count", "0"))58 redirect_count = count - 159 status_code = httpx.codes.SEE_OTHER if count else httpx.codes.OK60 if count:61 location = "/multiple_redirects"62 if redirect_count:87 location += b"?count=" + str(redirect_count).encode("ascii")88 headers = [(b"location", location)] if count else []89 return b"HTTP/1.1", code, phrase, headers, ByteStream(b"")63 location += f"?count={redirect_count}"64 headers = {"location": location}65 else:66 headers = {}67 return httpx.Response(status_code, headers=headers)6891 if path == b"/redirect_loop":92 code = httpx.codes.SEE_OTHER93 headers = [(b"location", b"/redirect_loop")]94 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")69 if request.url.path == "/redirect_loop":70 status_code = httpx.codes.SEE_OTHER71 headers = {"location": "/redirect_loop"}72 return httpx.Response(status_code, headers=headers)7396 elif path == b"/cross_domain":97 code = httpx.codes.SEE_OTHER98 headers = [(b"location", b"https://example.org/cross_domain_target")]99 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")74 elif request.url.path == "/cross_domain":75 status_code = httpx.codes.SEE_OTHER76 headers = {"location": "https://example.org/cross_domain_target"}77 return httpx.Response(status_code, headers=headers)78101 elif path == b"/cross_domain_target":102 headers_dict = {103 key.decode("ascii"): value.decode("ascii") for key, value in headers104 }105 stream = ByteStream(json.dumps({"headers": headers_dict}).encode())106 return b"HTTP/1.1", 200, b"OK", [], stream79 elif request.url.path == "/cross_domain_target":80 status_code = httpx.codes.OK81 content = json.dumps({"headers": dict(request.headers)}).encode("utf-8")82 return httpx.Response(status_code, content=content)83108 elif path == b"/redirect_body":109 code = httpx.codes.PERMANENT_REDIRECT110 headers = [(b"location", b"/redirect_body_target")]111 return b"HTTP/1.1", code, b"Permanent Redirect", headers, ByteStream(b"")84 elif request.url.path == "/redirect_body":85 status_code = httpx.codes.PERMANENT_REDIRECT86 headers = {"location": "/redirect_body_target"}87 return httpx.Response(status_code, headers=headers)88113 elif path == b"/redirect_no_body":114 code = httpx.codes.SEE_OTHER115 headers = [(b"location", b"/redirect_body_target")]116 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")89 elif request.url.path == "/redirect_no_body":90 status_code = httpx.codes.SEE_OTHER91 headers = {"location": "/redirect_body_target"}92 return httpx.Response(status_code, headers=headers)93118 elif path == b"/redirect_body_target":119 content = b"".join(stream)120 headers_dict = {121 key.decode("ascii"): value.decode("ascii") for key, value in headers122 }123 stream = ByteStream(124 json.dumps({"body": content.decode(), "headers": headers_dict}).encode()125 )126 return b"HTTP/1.1", 200, b"OK", [], stream94 elif request.url.path == "/redirect_body_target":95 content = json.dumps(96 {"body": request.content.decode("ascii"), "headers": dict(request.headers)}97 ).encode("utf-8")98 return httpx.Response(200, content=content)99128 elif path == b"/cross_subdomain":129 host = get_header_value(headers, "host")130 if host != "www.example.org":131 headers = [(b"location", b"https://www.example.org/cross_subdomain")]132 return (133 b"HTTP/1.1",134 httpx.codes.PERMANENT_REDIRECT,135 b"Permanent Redirect",136 headers,137 ByteStream(b""),138 )139 else:140 return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")100 elif request.url.path == "/cross_subdomain":101 if request.headers["Host"] != "www.example.org":102 status_code = httpx.codes.PERMANENT_REDIRECT103 headers = {"location": "https://www.example.org/cross_subdomain"}104 return httpx.Response(status_code, headers=headers)105 else:106 return httpx.Response(200, content=b"Hello, world!")107142 elif path == b"/redirect_custom_scheme":143 status_code = httpx.codes.MOVED_PERMANENTLY144 headers = [(b"location", b"market://details?id=42")]145 return (146 b"HTTP/1.1",147 status_code,148 b"Moved Permanently",149 headers,150 ByteStream(b""),151 )108 elif request.url.path == "/redirect_custom_scheme":109 status_code = httpx.codes.MOVED_PERMANENTLY110 headers = {"location": "market://details?id=42"}111 return httpx.Response(status_code, headers=headers)112153 stream = ByteStream(b"Hello, world!") if method != b"HEAD" else ByteStream(b"")113 if request.method == "HEAD":114 return httpx.Response(200)115155 return b"HTTP/1.1", 200, b"OK", [], stream116 return httpx.Response(200, content=b"Hello, world!")117118158class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):159 async def request(160 self, *args, **kwargs161 ) -> typing.Tuple[162 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream163 ]:164 return self._request(*args, **kwargs)165166167class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):168 def request(169 self, *args, **kwargs170 ) -> typing.Tuple[171 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream172 ]:173 return self._request(*args, **kwargs)174175119def test_no_redirect():177 client = httpx.Client(transport=SyncMockTransport())120 client = httpx.Client(transport=MockTransport(redirects))121 url = "https://example.com/no_redirect"122 response = client.get(url)123 assert response.status_code == 200124 with pytest.raises(httpx.NotRedirectResponse):125 response.next()126127128def test_redirect_301():186 client = httpx.Client(transport=SyncMockTransport())129 client = httpx.Client(transport=MockTransport(redirects))130 response = client.post("https://example.org/redirect_301")131 assert response.status_code == httpx.codes.OK132 assert response.url == "https://example.org/"133 assert len(response.history) == 1134135136def test_redirect_302():194 client = httpx.Client(transport=SyncMockTransport())137 client = httpx.Client(transport=MockTransport(redirects))138 response = client.post("https://example.org/redirect_302")139 assert response.status_code == httpx.codes.OK140 assert response.url == "https://example.org/"141 assert len(response.history) == 1142143144def test_redirect_303():202 client = httpx.Client(transport=SyncMockTransport())145 client = httpx.Client(transport=MockTransport(redirects))146 response = client.get("https://example.org/redirect_303")147 assert response.status_code == httpx.codes.OK148 assert response.url == "https://example.org/"149 assert len(response.history) == 1150151152def test_disallow_redirects():210 client = httpx.Client(transport=SyncMockTransport())153 client = httpx.Client(transport=MockTransport(redirects))154 response = client.post("https://example.org/redirect_303", allow_redirects=False)155 assert response.status_code == httpx.codes.SEE_OTHER156 assert response.url == "https://example.org/redirect_303"157 assert response.is_redirect is True
9 unmodified lines
167def test_head_redirect():168 """169 Contrary to Requests, redirects remain enabled by default for HEAD requests.170 """228 client = httpx.Client(transport=SyncMockTransport())171 client = httpx.Client(transport=MockTransport(redirects))172 response = client.head("https://example.org/redirect_302")173 assert response.status_code == httpx.codes.OK174 assert response.url == "https://example.org/"175 assert response.request.method == "HEAD"
1 unmodified line
177 assert response.text == ""178179180def test_relative_redirect():238 client = httpx.Client(transport=SyncMockTransport())181 client = httpx.Client(transport=MockTransport(redirects))182 response = client.get("https://example.org/relative_redirect")183 assert response.status_code == httpx.codes.OK184 assert response.url == "https://example.org/"185 assert len(response.history) == 1186187188def test_malformed_redirect():189 # https://github.com/encode/httpx/issues/771247 client = httpx.Client(transport=SyncMockTransport())190 client = httpx.Client(transport=MockTransport(redirects))191 response = client.get("http://example.org/malformed_redirect")192 assert response.status_code == httpx.codes.OK193 assert response.url == "https://example.org:443/"194 assert len(response.history) == 1195196197def test_invalid_redirect():255 client = httpx.Client(transport=SyncMockTransport())198 client = httpx.Client(transport=MockTransport(redirects))199 with pytest.raises(httpx.RemoteProtocolError):200 client.get("http://example.org/invalid_redirect")201202203def test_no_scheme_redirect():261 client = httpx.Client(transport=SyncMockTransport())204 client = httpx.Client(transport=MockTransport(redirects))205 response = client.get("https://example.org/no_scheme_redirect")206 assert response.status_code == httpx.codes.OK207 assert response.url == "https://example.org/"208 assert len(response.history) == 1209210211def test_fragment_redirect():269 client = httpx.Client(transport=SyncMockTransport())212 client = httpx.Client(transport=MockTransport(redirects))213 response = client.get("https://example.org/relative_redirect#fragment")214 assert response.status_code == httpx.codes.OK215 assert response.url == "https://example.org/#fragment"216 assert len(response.history) == 1217218219def test_multiple_redirects():277 client = httpx.Client(transport=SyncMockTransport())220 client = httpx.Client(transport=MockTransport(redirects))221 response = client.get("https://example.org/multiple_redirects?count=20")222 assert response.status_code == httpx.codes.OK223 assert response.url == "https://example.org/multiple_redirects"224 assert len(response.history) == 20
4 unmodified lines
229230231@pytest.mark.usefixtures("async_environment")232async def test_async_too_many_redirects():290 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:233 async with httpx.AsyncClient(transport=AsyncMockTransport(redirects)) as client:234 with pytest.raises(httpx.TooManyRedirects):235 await client.get("https://example.org/multiple_redirects?count=21")236237238@pytest.mark.usefixtures("async_environment")239async def test_async_too_many_redirects_calling_next():297 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:240 async with httpx.AsyncClient(transport=AsyncMockTransport(redirects)) as client:241 url = "https://example.org/multiple_redirects?count=21"242 response = await client.get(url, allow_redirects=False)243 with pytest.raises(httpx.TooManyRedirects):244 while response.is_redirect:245 response = await response.anext()246247248def test_sync_too_many_redirects():306 client = httpx.Client(transport=SyncMockTransport())249 client = httpx.Client(transport=MockTransport(redirects))250 with pytest.raises(httpx.TooManyRedirects):251 client.get("https://example.org/multiple_redirects?count=21")252253254def test_sync_too_many_redirects_calling_next():312 client = httpx.Client(transport=SyncMockTransport())255 client = httpx.Client(transport=MockTransport(redirects))256 url = "https://example.org/multiple_redirects?count=21"257 response = client.get(url, allow_redirects=False)258 with pytest.raises(httpx.TooManyRedirects):259 while response.is_redirect:260 response = response.next()261262263def test_redirect_loop():321 client = httpx.Client(transport=SyncMockTransport())264 client = httpx.Client(transport=MockTransport(redirects))265 with pytest.raises(httpx.TooManyRedirects):266 client.get("https://example.org/redirect_loop")267268269def test_cross_domain_redirect_with_auth_header():327 client = httpx.Client(transport=SyncMockTransport())270 client = httpx.Client(transport=MockTransport(redirects))271 url = "https://example.com/cross_domain"272 headers = {"Authorization": "abc"}273 response = client.get(url, headers=headers)274 assert response.url == "https://example.org/cross_domain_target"275 assert "authorization" not in response.json()["headers"]276277278def test_cross_domain_redirect_with_auth():336 client = httpx.Client(transport=SyncMockTransport())279 client = httpx.Client(transport=MockTransport(redirects))280 url = "https://example.com/cross_domain"281 response = client.get(url, auth=("user", "pass"))282 assert response.url == "https://example.org/cross_domain_target"283 assert "authorization" not in response.json()["headers"]284285286def test_same_domain_redirect():344 client = httpx.Client(transport=SyncMockTransport())287 client = httpx.Client(transport=MockTransport(redirects))288 url = "https://example.org/cross_domain"289 headers = {"Authorization": "abc"}290 response = client.get(url, headers=headers)291 assert response.url == "https://example.org/cross_domain_target"
3 unmodified lines
295def test_body_redirect():296 """297 A 308 redirect should preserve the request body.298 """356 client = httpx.Client(transport=SyncMockTransport())299 client = httpx.Client(transport=MockTransport(redirects))300 url = "https://example.org/redirect_body"301 data = b"Example request body"302 response = client.post(url, data=data)303 assert response.url == "https://example.org/redirect_body_target"
4 unmodified lines
308def test_no_body_redirect():309 """310 A 303 redirect should remove the request body.311 """369 client = httpx.Client(transport=SyncMockTransport())312 client = httpx.Client(transport=MockTransport(redirects))313 url = "https://example.org/redirect_no_body"314 data = b"Example request body"315 response = client.post(url, data=data)316 assert response.url == "https://example.org/redirect_body_target"
1 unmodified line
318 assert "content-length" not in response.json()["headers"]319320321def test_can_stream_if_no_redirect():379 client = httpx.Client(transport=SyncMockTransport())322 client = httpx.Client(transport=MockTransport(redirects))323 url = "https://example.org/redirect_301"324 with client.stream("GET", url, allow_redirects=False) as response:325 assert not response.is_closed326 assert response.status_code == httpx.codes.MOVED_PERMANENTLY327 assert response.headers["location"] == "https://example.org/"328329330def test_cannot_redirect_streaming_body():388 client = httpx.Client(transport=SyncMockTransport())331 client = httpx.Client(transport=MockTransport(redirects))332 url = "https://example.org/redirect_body"333334 def streaming_body():335 yield b"Example request body" # pragma: nocover
2 unmodified lines
338 client.post(url, data=streaming_body())339340341def test_cross_subdomain_redirect():399 client = httpx.Client(transport=SyncMockTransport())342 client = httpx.Client(transport=MockTransport(redirects))343 url = "https://example.com/cross_subdomain"344 response = client.get(url)345 assert response.url == "https://www.example.org/cross_subdomain"346347405class MockCookieTransport(httpcore.SyncHTTPTransport):406 def request(407 self,408 method: bytes,409 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],410 headers: typing.List[typing.Tuple[bytes, bytes]] = None,411 stream: httpcore.SyncByteStream = None,412 timeout: typing.Mapping[str, typing.Optional[float]] = None,413 ) -> typing.Tuple[414 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream415 ]:416 scheme, host, port, path = url417 if path == b"/":418 cookie = get_header_value(headers, "Cookie")419 if cookie is not None:420 content = b"Logged in"421 else:422 content = b"Not logged in"423 return b"HTTP/1.1", 200, b"OK", [], ByteStream(content)348def cookie_sessions(request: httpx.Request) -> httpx.Response:349 if request.url.path == "/":350 cookie = request.headers.get("Cookie")351 if cookie is not None:352 content = b"Logged in"353 else:354 content = b"Not logged in"355 return httpx.Response(200, content=content)356425 elif path == b"/login":426 status_code = httpx.codes.SEE_OTHER427 headers = [428 (b"location", b"/"),429 (430 b"set-cookie",431 (432 b"session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "433 b"httponly; samesite=lax"434 ),435 ),436 ]437 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")357 elif request.url.path == "/login":358 status_code = httpx.codes.SEE_OTHER359 headers = {360 "location": "/",361 "set-cookie": (362 "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "363 "httponly; samesite=lax"364 ),365 }366 return httpx.Response(status_code, headers=headers)367439 else:440 assert path == b"/logout"441 status_code = httpx.codes.SEE_OTHER442 headers = [443 (b"location", b"/"),444 (445 b"set-cookie",446 (447 b"session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "448 b"httponly; samesite=lax"449 ),450 ),451 ]452 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")368 else:369 assert request.url.path == "/logout"370 status_code = httpx.codes.SEE_OTHER371 headers = {372 "location": "/",373 "set-cookie": (374 "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "375 "httponly; samesite=lax"376 ),377 }378 return httpx.Response(status_code, headers=headers)379380381def test_redirect_cookie_behavior():456 client = httpx.Client(transport=MockCookieTransport())382 client = httpx.Client(transport=MockTransport(cookie_sessions))383384 # The client is not logged in.385 response = client.get("https://example.com/")386 assert response.url == "https://example.com/"
20 unmodified lines
407 assert response.text == "Not logged in"408409410def test_redirect_custom_scheme():485 client = httpx.Client(transport=SyncMockTransport())411 client = httpx.Client(transport=MockTransport(redirects))412 with pytest.raises(httpx.UnsupportedProtocol) as e:413 client.post("https://example.org/redirect_custom_scheme")488 assert str(e.value) == "Scheme b'market' not supported."414 assert str(e.value) == "Scheme 'market' not supported."
modified:tests/test_multipart.py+7 added-23 removed
2 unmodified lines
3import os4import typing5from unittest import mock67import httpcore7import pytest89import httpx10from httpx._content_streams import MultipartStream, encode11from httpx._utils import format_form_param12from tests.utils import MockTransport131415class MockTransport(httpcore.SyncHTTPTransport):16 def request(17 self,18 method: bytes,19 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,21 stream: httpcore.SyncByteStream = None,22 timeout: typing.Mapping[str, typing.Optional[float]] = None,23 ) -> typing.Tuple[24 bytes,25 int,26 bytes,27 typing.List[typing.Tuple[bytes, bytes]],28 httpcore.SyncByteStream,29 ]:30 assert stream is not None31 content = httpcore.IteratorByteStream(iterator=(part for part in stream))32 return b"HTTP/1.1", 200, b"OK", [], content15def echo_request_content(request: httpx.Request) -> httpx.Response:16 return httpx.Response(200, content=request.content)171819@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))20def test_multipart(value, output):37 client = httpx.Client(transport=MockTransport())21 client = httpx.Client(transport=MockTransport(echo_request_content))2223 # Test with a single-value 'data' argument, and a plain file 'files' argument.24 data = {"text": value}25 files = {"file": io.BytesIO(b"<file content>")}
17 unmodified lines
434445@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))46def test_multipart_invalid_key(key):63 client = httpx.Client(transport=MockTransport())47 client = httpx.Client(transport=MockTransport(echo_request_content))4849 data = {key: "abc"}50 files = {"file": io.BytesIO(b"<file content>")}51 with pytest.raises(TypeError) as e:
6 unmodified lines
585960@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))61def test_multipart_invalid_value(value):78 client = httpx.Client(transport=MockTransport())62 client = httpx.Client(transport=MockTransport(echo_request_content))6364 data = {"text": value}65 files = {"file": io.BytesIO(b"<file content>")}66 with pytest.raises(TypeError) as e:
1 unmodified line
68 assert "Invalid type for value" in str(e.value)697071def test_multipart_file_tuple():88 client = httpx.Client(transport=MockTransport())72 client = httpx.Client(transport=MockTransport(echo_request_content))7374 # Test with a list of values 'data' argument,75 # and a tuple style 'files' argument.76 data = {"text": ["abc"]}
186 unmodified lines
modified:tests/utils.py+91 added
1import contextlib2import logging3import os4from typing import Callable, List, Mapping, Optional, Tuple56import httpcore78import httpx9from httpx import _utils101112@contextlib.contextmanager
8 unmodified lines
21 yield22 finally:23 # Reset the logger so we don't have verbose output in all unit tests24 logging.getLogger("httpx").handlers = []252627class MockTransport(httpcore.SyncHTTPTransport):28 def __init__(self, handler: Callable) -> None:29 self.handler = handler3031 def request(32 self,33 method: bytes,34 url: Tuple[bytes, bytes, Optional[int], bytes],35 headers: List[Tuple[bytes, bytes]] = None,36 stream: httpcore.SyncByteStream = None,37 timeout: Mapping[str, Optional[float]] = None,38 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:39 raw_scheme, raw_host, port, raw_path = url40 scheme = raw_scheme.decode("ascii")41 host = raw_host.decode("ascii")42 port_str = "" if port is None else f":{port}"43 path = raw_path.decode("ascii")4445 request_headers = httpx.Headers(headers)46 data = (47 (item for item in stream)48 if stream49 and (50 "Content-Length" in request_headers51 or "Transfer-Encoding" in request_headers52 )53 else None54 )5556 request = httpx.Request(57 method=method.decode("ascii"),58 url=f"{scheme}://{host}{port_str}{path}",59 headers=request_headers,60 data=data,61 )62 request.read()63 response = self.handler(request)64 return (65 response.http_version.encode("ascii")66 if response.http_version67 else b"HTTP/1.1",68 response.status_code,69 response.reason_phrase.encode("ascii"),70 response.headers.raw,71 response._raw_stream,72 )737475class AsyncMockTransport(httpcore.AsyncHTTPTransport):76 def __init__(self, handler: Callable) -> None:77 self.impl = MockTransport(handler)7879 async def request(80 self,81 method: bytes,82 url: Tuple[bytes, bytes, Optional[int], bytes],83 headers: List[Tuple[bytes, bytes]] = None,84 stream: httpcore.AsyncByteStream = None,85 timeout: Mapping[str, Optional[float]] = None,86 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:87 content = (88 httpcore.PlainByteStream(b"".join([part async for part in stream]))89 if stream90 else httpcore.PlainByteStream(b"")91 )9293 (94 http_version,95 status_code,96 reason_phrase,97 headers,98 response_stream,99 ) = self.impl.request(100 method, url, headers=headers, stream=content, timeout=timeout101 )102103 content = httpcore.PlainByteStream(b"".join([part for part in response_stream]))104105 return (106 http_version,107 status_code,108 reason_phrase,109 headers,110 content,111 )
modified:requirements.txt+1 added-1 removed
16 unmodified lines
17black==20.8b118cryptography19flake820flake8-bugbear21flake8-pie21flake8-pie==0.5.*22isort==5.*23mypy24pytest==5.*25pytest-asyncio
9 unmodified lines