Skip to content
Myr

Type check tests (#1054)

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

authored by Florimond Manca · committed by GitHub · parent 3230cb3 · Browse files · 17 files+76 added−51 removed
This commit

State

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

Diff stats

17 files+76 added−51 removed

  • tests:+74 added−49 removed
  • other:+2 added−2 removed

17 files+76 added−51 removed

modified:httpx/_types.py+1 added-1 removed
70 unmodified lines
71 Tuple[Optional[str], FileContent],72 # (filename, file (or text), content_type)73 Tuple[Optional[str], FileContent, Optional[str]],74]75RequestFiles = Union[Mapping[str, FileTypes], List[Tuple[str, FileTypes]]]75RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
modified:scripts/check+1 added-1 removed
8 unmodified lines
9set -x1011${PREFIX}black --check --diff --target-version=py36 $SOURCE_FILES12${PREFIX}flake8 $SOURCE_FILES13${PREFIX}mypy httpx13${PREFIX}mypy $SOURCE_FILES14${PREFIX}isort --check --diff --project=httpx $SOURCE_FILES
modified:tests/client/test_async_client.py+4 added-1 removed
172 unmodified lines
173 )174175176def test_asgi_dispatch_deprecated():177 async def app(scope, receive, send):178 pass179180 with pytest.warns(DeprecationWarning) as record:178 ASGIDispatch(None)181 ASGIDispatch(app)182183 assert len(record) == 1184 assert (185 record[0].message.args[0]
2 unmodified lines
modified:tests/client/test_auth.py+11 added-8 removed
9 unmodified lines
10 AsyncClient,11 Auth,12 Client,13 DigestAuth,14 Headers,14 ProtocolError,15 Request,16 RequestBodyUnavailable,17 Response,
66 unmodified lines
8485 async def request(86 self,87 method: bytes,89 url: typing.Tuple[bytes, bytes, int, bytes],90 headers: typing.List[typing.Tuple[bytes, bytes]],91 stream: ContentStream,88 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],89 headers: typing.List[typing.Tuple[bytes, bytes]] = None,90 stream: httpcore.AsyncByteStream = None,91 timeout: typing.Dict[str, typing.Optional[float]] = None,92 ) -> typing.Tuple[93 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream94 ]:95 if self._response_count < self.send_response_after_attempt:96 assert headers is not None97 return self.challenge_send(method, url, headers, stream)97 return self.challenge_send(method, headers)9899 authorization = get_header_value(headers, "Authorization")100 body = JSONStream({"auth": authorization})101 return b"HTTP/1.1", 200, b"", [], body102103 def challenge_send(104 self, method: bytes, url: URL, headers: Headers, stream: ContentStream,105 ) -> typing.Tuple[int, bytes, Headers, ContentStream]:104 self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]],105 ) -> typing.Tuple[106 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream107 ]:108 self._response_count += 1109 nonce = (110 hashlib.sha256(os.urandom(8)).hexdigest()111 if self._regenerate_nonce
186 unmodified lines
298@pytest.mark.asyncio299async def test_auth_invalid_type() -> None:300 url = "https://example.org/"301 client = AsyncClient(300 transport=AsyncMockTransport(), auth="not a tuple, not a callable",302 transport=AsyncMockTransport(),303 auth="not a tuple, not a callable", # type: ignore304 )305 with pytest.raises(TypeError):306 await client.get(url)307
301 unmodified lines
modified:tests/client/test_client.py+4 added-1 removed
180 unmodified lines
181 )182183184def test_wsgi_dispatch_deprecated():185 def app(start_response, environ):186 pass187188 with pytest.warns(DeprecationWarning) as record:186 WSGIDispatch(None)189 WSGIDispatch(app)190191 assert len(record) == 1192 assert (193 record[0].message.args[0]
2 unmodified lines
modified:tests/client/test_cookies.py+4 added-3 removed
18 unmodified lines
19class MockTransport(httpcore.AsyncHTTPTransport):20 async def request(21 self,22 method: bytes,23 url: typing.Tuple[bytes, bytes, int, bytes],24 headers: typing.List[typing.Tuple[bytes, bytes]],25 stream: ContentStream,23 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],24 headers: typing.List[typing.Tuple[bytes, bytes]] = None,25 stream: httpcore.AsyncByteStream = None,26 timeout: typing.Dict[str, typing.Optional[float]] = None,27 ) -> typing.Tuple[28 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream29 ]:30 host, scheme, port, path = url31 body: ContentStream32 if path.startswith(b"/echo_cookies"):33 cookie = get_header_value(headers, "cookie")34 body = JSONStream({"cookies": cookie})35 return b"HTTP/1.1", 200, b"OK", [], body
144 unmodified lines
modified:tests/client/test_headers.py+4 added-3 removed
11 unmodified lines
12class MockTransport(httpcore.AsyncHTTPTransport):13 async def request(14 self,15 method: bytes,16 url: typing.Tuple[bytes, bytes, int, bytes],17 headers: typing.List[typing.Tuple[bytes, bytes]],18 stream: ContentStream,16 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],17 headers: typing.List[typing.Tuple[bytes, bytes]] = None,18 stream: httpcore.AsyncByteStream = None,19 timeout: typing.Dict[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})
156 unmodified lines
modified:tests/client/test_properties.py+2 added-2 removed
1 unmodified line
234def test_client_headers():5 client = AsyncClient()6 client.headers = {"a": "b"}6 client.headers = {"a": "b"} # type: ignore7 assert isinstance(client.headers, Headers)8 assert client.headers["A"] == "b"91011def test_client_cookies():12 client = AsyncClient()13 client.cookies = {"a": "b"}13 client.cookies = {"a": "b"} # type: ignore14 assert isinstance(client.cookies, Cookies)15 mycookies = list(client.cookies.jar)16 assert len(mycookies) == 117 assert mycookies[0].name == "a" and mycookies[0].value == "b"
modified:tests/client/test_proxies.py+5 added-1 removed
1import httpcore2import pytest34import httpx5
18 unmodified lines
24 client = httpx.AsyncClient(proxies=proxies)2526 for proxy_key, url in expected_proxies:27 assert proxy_key in client.proxies28 proxy = client.proxies[proxy_key]29 assert isinstance(proxy, httpcore.AsyncHTTPProxy)27 assert client.proxies[proxy_key].proxy_origin == httpx.URL(url).raw[:3]30 assert proxy.proxy_origin == httpx.URL(url).raw[:3]3132 assert len(expected_proxies) == len(client.proxies)3334
48 unmodified lines
8384 if expected is None:85 assert transport is client.transport86 else:87 assert isinstance(transport, httpcore.AsyncHTTPProxy)88 assert transport.proxy_origin == httpx.URL(expected).raw[:3]899091@pytest.mark.asyncio
43 unmodified lines
modified:tests/client/test_queryparams.py+6 added-7 removed
1 unmodified line
23import httpcore4import pytest56from httpx import URL, AsyncClient, Headers, QueryParams6from httpx import URL, AsyncClient, QueryParams7from httpx._content_streams import ContentStream, JSONStream8910class MockTransport(httpcore.AsyncHTTPTransport):11 async def request(12 self,13 method: bytes,14 url: typing.Tuple[bytes, bytes, int, bytes],15 headers: typing.List[typing.Tuple[bytes, bytes]],16 stream: ContentStream,14 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],15 headers: typing.List[typing.Tuple[bytes, bytes]] = None,16 stream: httpcore.AsyncByteStream = None,17 timeout: typing.Dict[str, typing.Optional[float]] = None,18 ) -> typing.Tuple[19 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream20 ]:21 headers = Headers()21 body = JSONStream({"ok": "ok"})23 return b"HTTP/1.1", 200, b"OK", headers, body22 return b"HTTP/1.1", 200, b"OK", [], body232425def test_client_queryparams():26 client = AsyncClient(params={"a": "b"})
6 unmodified lines
33 assert isinstance(client.params, QueryParams)34 assert client.params["a"] == "b"3536 client = AsyncClient()38 client.params = "a=b"37 client.params = "a=b" # type: ignore38 assert isinstance(client.params, QueryParams)39 assert client.params["a"] == "b"4041
12 unmodified lines
modified:tests/client/test_redirects.py+9 added-8 removed
101 unmodified lines
102 elif path == b"/cross_domain_target":103 headers_dict = {104 key.decode("ascii"): value.decode("ascii") for key, value in headers105 }106 content = ByteStream(json.dumps({"headers": headers_dict}).encode())107 return b"HTTP/1.1", 200, b"OK", [], content106 stream = ByteStream(json.dumps({"headers": headers_dict}).encode())107 return b"HTTP/1.1", 200, b"OK", [], stream108109 elif path == b"/redirect_body":110 code = codes.PERMANENT_REDIRECT111 headers = [(b"location", b"/redirect_body_target")]
8 unmodified lines
120 content = b"".join(stream)121 headers_dict = {122 key.decode("ascii"): value.decode("ascii") for key, value in headers123 }124 body = ByteStream(124 stream = ByteStream(125 json.dumps({"body": content.decode(), "headers": headers_dict}).encode()126 )127 return b"HTTP/1.1", 200, b"OK", [], body127 return b"HTTP/1.1", 200, b"OK", [], stream128129 elif path == b"/cross_subdomain":130 host = get_header_value(headers, "host")131 if host != "www.example.org":
269 unmodified lines
401class MockCookieTransport(httpcore.AsyncHTTPTransport):402 async def request(403 self,404 method: bytes,405 url: typing.Tuple[bytes, bytes, int, bytes],406 headers: typing.List[typing.Tuple[bytes, bytes]],407 stream: ContentStream,405 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],406 headers: typing.List[typing.Tuple[bytes, bytes]] = None,407 stream: httpcore.AsyncByteStream = None,408 timeout: typing.Dict[str, typing.Optional[float]] = None,409 ) -> typing.Tuple[410 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream411 ]:
19 unmodified lines
431 ),432 ]433 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")434435 elif path == b"/logout":435 else:436 assert path == b"/logout"437 status_code = codes.SEE_OTHER438 headers = [439 (b"location", b"/"),440 (
46 unmodified lines
modified:tests/conftest.py+1 added-1 removed
54 unmodified lines
55 return request.param565758@pytest.fixture(scope="function", autouse=True)59def clean_environ() -> typing.Dict[str, typing.Any]:59def clean_environ():60 """Keeps os.environ clean for every test without having to mock os.environ"""61 original_environ = os.environ.copy()62 os.environ.clear()63 os.environ.update(
230 unmodified lines
modified:tests/test_api.py+2 added-3 removed
66 unmodified lines
67 assert response.text == "Hello, world!"68 assert response.http_version == "HTTP/1.1"697071@pytest.mark.asyncio72async def test_get_invalid_url(server):71def test_get_invalid_url():72 with pytest.raises(httpx.InvalidURL):74 await httpx.get("invalid://example.org")73 httpx.get("invalid://example.org")
modified:tests/test_config.py+4 added-4 removed
54 unmodified lines
555657def test_load_ssl_config_verify_directory():58 path = Path(certifi.where()).parent59 ssl_config = SSLConfig(verify=path)59 ssl_config = SSLConfig(verify=str(path))60 context = ssl_config.ssl_context61 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED62 assert context.check_hostname is True63
127 unmodified lines
191 m.delenv("SSLKEYLOGFILE", raising=False)192193 ssl_config = SSLConfig(trust_env=True)194195 assert ssl_config.ssl_context.keylog_filename is None195 assert ssl_config.ssl_context.keylog_filename is None # type: ignore196197 filename = str(tmpdir.join("test.log"))198199 with monkeypatch.context() as m:200 m.setenv("SSLKEYLOGFILE", filename)201202 ssl_config = SSLConfig(trust_env=True)203204 assert ssl_config.ssl_context.keylog_filename == filename204 assert ssl_config.ssl_context.keylog_filename == filename # type: ignore205206 ssl_config = SSLConfig(trust_env=False)207208 assert ssl_config.ssl_context.keylog_filename is None208 assert ssl_config.ssl_context.keylog_filename is None # type: ignore209210211@pytest.mark.parametrize(212 "url,expected_url,expected_headers,expected_mode",
29 unmodified lines
modified:tests/test_content_streams.py+1 added-1 removed
201 unmodified lines
202203204def test_invalid_argument():205 with pytest.raises(TypeError):206 encode(123)206 encode(123) # type: ignore207208209@pytest.mark.asyncio210async def test_multipart_multiple_files_single_input_content():
43 unmodified lines
modified:tests/test_multipart.py+16 added-5 removed
6 unmodified lines
7import httpcore8import pytest910import httpx11from httpx._content_streams import AsyncIteratorStream, encode11from httpx._content_streams import AsyncIteratorStream, MultipartStream, encode12from httpx._utils import format_form_param131415class MockTransport(httpcore.AsyncHTTPTransport):16 async def request(17 self,18 method: bytes,19 url: typing.Tuple[bytes, bytes, int, bytes],19 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,21 stream: httpcore.AsyncByteStream = None,22 timeout: typing.Dict[str, typing.Optional[float]] = None,23 ) -> typing.Tuple[
2 unmodified lines
26 bytes,27 typing.List[typing.Tuple[bytes, bytes]],28 httpcore.AsyncByteStream,29 ]:30 assert stream is not None31 content = AsyncIteratorStream(aiterator=(part async for part in stream))32 return b"HTTP/1.1", 200, b"OK", [], content3334
11 unmodified lines
46 # We're using the cgi module to verify the behavior here, which is a47 # bit grungy, but sufficient just for our testing purposes.48 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]49 content_length = response.request.headers["Content-Length"]49 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}50 pdict: dict = {51 "boundary": boundary.encode("ascii"),52 "CONTENT-LENGTH": content_length,53 }54 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5556 # Note that the expected return type for text fields57 # appears to differs from 3.6 to 3.7+
36 unmodified lines
94 # We're using the cgi module to verify the behavior here, which is a95 # bit grungy, but sufficient just for our testing purposes.96 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]97 content_length = response.request.headers["Content-Length"]94 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}98 pdict: dict = {99 "boundary": boundary.encode("ascii"),100 "CONTENT-LENGTH": content_length,101 }102 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)103104 # Note that the expected return type for text fields105 # appears to differs from 3.6 to 3.7+
17 unmodified lines
123 with mock.patch("os.urandom", return_value=os.urandom(16)):124 boundary = os.urandom(16).hex()125126 stream = encode(data=data, files=files)127 assert isinstance(stream, MultipartStream)128 assert stream.can_replay()129130 assert stream.content_type == f"multipart/form-data; boundary={boundary}"131 content = (
18 unmodified lines
150 with mock.patch("os.urandom", return_value=os.urandom(16)):151 boundary = os.urandom(16).hex()152153 stream = encode(data={}, files=files)154 assert isinstance(stream, MultipartStream)155 assert stream.can_replay()156157 assert stream.content_type == f"multipart/form-data; boundary={boundary}"158 assert b"".join(stream) == (
18 unmodified lines
177 with mock.patch("os.urandom", return_value=os.urandom(16)):178 boundary = os.urandom(16).hex()179180 stream = encode(data={}, files=files)181 assert isinstance(stream, MultipartStream)182 assert stream.can_replay()183184 assert stream.content_type == f"multipart/form-data; boundary={boundary}"185 assert b"".join(stream) == (
15 unmodified lines
201 with mock.patch("os.urandom", return_value=os.urandom(16)):202 boundary = os.urandom(16).hex()203204 stream = encode(data={}, files=files)205 assert isinstance(stream, MultipartStream)206 assert stream.can_replay()207208 assert stream.content_type == f"multipart/form-data; boundary={boundary}"209 content = (
26 unmodified lines
236 def data() -> typing.Iterator[bytes]:237 yield b"Hello"238 yield b"World"239229 fileobj = IteratorIO(data())240 fileobj: typing.Any = IteratorIO(data())241 files = {"file": fileobj}242 stream = encode(files=files, boundary=b"+++")243 assert not stream.can_replay()244
31 unmodified lines
modified:tests/test_status_codes.py+1 added-1 removed
5 unmodified lines
6 assert str(httpx.codes.NOT_FOUND) == "404"789def test_lowercase_status_code():10 assert httpx.codes.not_found == 40410 assert httpx.codes.not_found == 404 # type: ignore111213def test_reason_phrase_for_status_code():14 assert httpx.codes.get_reason_phrase(404) == "Not Found"
4 unmodified lines