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
Provenance
- Commit
0296c2b- Tree
72540b2- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
3230cb3
17 files changed+76 added−51 removed
modified:httpx/_types.py+1 added-1 removed
70 unmodified lines71 Tuple[Optional[str], FileContent],72 # (filename, file (or text), content_type)73 Tuple[Optional[str], FileContent, Optional[str]],74 ]75-RequestFiles = Union[Mapping[str, FileTypes], List[Tuple[str, FileTypes]]]75+RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]modified:scripts/check+1 added-1 removed
8 unmodified lines9 set -x10 11 ${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_FILESmodified:tests/client/test_async_client.py+4 added-1 removed
172 unmodified lines173 )174 175 176 def test_asgi_dispatch_deprecated():177+ async def app(scope, receive, send):178+ pass179+180 with pytest.warns(DeprecationWarning) as record:178- ASGIDispatch(None)181+ ASGIDispatch(app)182 183 assert len(record) == 1184 assert (185 record[0].message.args[0]2 unmodified linesmodified:tests/client/test_auth.py+11 added-8 removed
9 unmodified lines10 AsyncClient,11 Auth,12 Client,13 DigestAuth,14- Headers,14 ProtocolError,15 Request,16 RequestBodyUnavailable,17 Response,66 unmodified lines84 85 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)98 99 authorization = get_header_value(headers, "Authorization")100 body = JSONStream({"auth": authorization})101 return b"HTTP/1.1", 200, b"", [], body102 103 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_nonce186 unmodified lines298 @pytest.mark.asyncio299 async 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 linesmodified:tests/client/test_client.py+4 added-1 removed
180 unmodified lines181 )182 183 184 def test_wsgi_dispatch_deprecated():185+ def app(start_response, environ):186+ pass187+188 with pytest.warns(DeprecationWarning) as record:186- WSGIDispatch(None)189+ WSGIDispatch(app)190 191 assert len(record) == 1192 assert (193 record[0].message.args[0]2 unmodified linesmodified:tests/client/test_cookies.py+4 added-3 removed
18 unmodified lines19 class 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", [], body144 unmodified linesmodified:tests/client/test_headers.py+4 added-3 removed
11 unmodified lines12 class 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 linesmodified:tests/client/test_properties.py+2 added-2 removed
1 unmodified line2 3 4 def 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"9 10 11 def 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
1+import httpcore2 import pytest3 4 import httpx5 18 unmodified lines24 client = httpx.AsyncClient(proxies=proxies)25 26 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]31 32 assert len(expected_proxies) == len(client.proxies)33 34 48 unmodified lines83 84 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]89 90 91 @pytest.mark.asyncio43 unmodified linesmodified:tests/client/test_queryparams.py+6 added-7 removed
1 unmodified line2 3 import httpcore4 import pytest5 6-from httpx import URL, AsyncClient, Headers, QueryParams6+from httpx import URL, AsyncClient, QueryParams7 from httpx._content_streams import ContentStream, JSONStream8 9 10 class 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", [], body23 24 25 def test_client_queryparams():26 client = AsyncClient(params={"a": "b"})6 unmodified lines33 assert isinstance(client.params, QueryParams)34 assert client.params["a"] == "b"35 36 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"40 41 12 unmodified linesmodified:tests/client/test_redirects.py+9 added-8 removed
101 unmodified lines102 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", [], stream108 109 elif path == b"/redirect_body":110 code = codes.PERMANENT_REDIRECT111 headers = [(b"location", b"/redirect_body_target")]8 unmodified lines120 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", [], stream128 129 elif path == b"/cross_subdomain":130 host = get_header_value(headers, "host")131 if host != "www.example.org":269 unmodified lines401 class 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 lines431 ),432 ]433 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")434 435- 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 linesmodified:tests/conftest.py+1 added-1 removed
54 unmodified lines55 return request.param56 57 58 @pytest.fixture(scope="function", autouse=True)59-def clean_environ() -> typing.Dict[str, typing.Any]:59+def 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 linesmodified:tests/test_api.py+2 added-3 removed
66 unmodified lines67 assert response.text == "Hello, world!"68 assert response.http_version == "HTTP/1.1"69 70 71-@pytest.mark.asyncio72-async def test_get_invalid_url(server):71+def 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 lines55 56 57 def 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 lines191 m.delenv("SSLKEYLOGFILE", raising=False)192 193 ssl_config = SSLConfig(trust_env=True)194 195- assert ssl_config.ssl_context.keylog_filename is None195+ assert ssl_config.ssl_context.keylog_filename is None # type: ignore196 197 filename = str(tmpdir.join("test.log"))198 199 with monkeypatch.context() as m:200 m.setenv("SSLKEYLOGFILE", filename)201 202 ssl_config = SSLConfig(trust_env=True)203 204- assert ssl_config.ssl_context.keylog_filename == filename204+ assert ssl_config.ssl_context.keylog_filename == filename # type: ignore205 206 ssl_config = SSLConfig(trust_env=False)207 208- assert ssl_config.ssl_context.keylog_filename is None208+ assert ssl_config.ssl_context.keylog_filename is None # type: ignore209 210 211 @pytest.mark.parametrize(212 "url,expected_url,expected_headers,expected_mode",29 unmodified linesmodified:tests/test_content_streams.py+1 added-1 removed
201 unmodified lines202 203 204 def test_invalid_argument():205 with pytest.raises(TypeError):206- encode(123)206+ encode(123) # type: ignore207 208 209 @pytest.mark.asyncio210 async def test_multipart_multiple_files_single_input_content():43 unmodified linesmodified:tests/test_multipart.py+16 added-5 removed
6 unmodified lines7 import httpcore8 import pytest9 10 import httpx11-from httpx._content_streams import AsyncIteratorStream, encode11+from httpx._content_streams import AsyncIteratorStream, MultipartStream, encode12 from httpx._utils import format_form_param13 14 15 class 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 lines26 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", [], content33 34 11 unmodified lines46 # 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)55 56 # Note that the expected return type for text fields57 # appears to differs from 3.6 to 3.7+36 unmodified lines94 # 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)103 104 # Note that the expected return type for text fields105 # appears to differs from 3.6 to 3.7+17 unmodified lines123 with mock.patch("os.urandom", return_value=os.urandom(16)):124 boundary = os.urandom(16).hex()125 126 stream = encode(data=data, files=files)127+ assert isinstance(stream, MultipartStream)128 assert stream.can_replay()129 130 assert stream.content_type == f"multipart/form-data; boundary={boundary}"131 content = (18 unmodified lines150 with mock.patch("os.urandom", return_value=os.urandom(16)):151 boundary = os.urandom(16).hex()152 153 stream = encode(data={}, files=files)154+ assert isinstance(stream, MultipartStream)155 assert stream.can_replay()156 157 assert stream.content_type == f"multipart/form-data; boundary={boundary}"158 assert b"".join(stream) == (18 unmodified lines177 with mock.patch("os.urandom", return_value=os.urandom(16)):178 boundary = os.urandom(16).hex()179 180 stream = encode(data={}, files=files)181+ assert isinstance(stream, MultipartStream)182 assert stream.can_replay()183 184 assert stream.content_type == f"multipart/form-data; boundary={boundary}"185 assert b"".join(stream) == (15 unmodified lines201 with mock.patch("os.urandom", return_value=os.urandom(16)):202 boundary = os.urandom(16).hex()203 204 stream = encode(data={}, files=files)205+ assert isinstance(stream, MultipartStream)206 assert stream.can_replay()207 208 assert stream.content_type == f"multipart/form-data; boundary={boundary}"209 content = (26 unmodified lines236 def data() -> typing.Iterator[bytes]:237 yield b"Hello"238 yield b"World"239 229- 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 linesmodified:tests/test_status_codes.py+1 added-1 removed
5 unmodified lines6 assert str(httpx.codes.NOT_FOUND) == "404"7 8 9 def test_lowercase_status_code():10- assert httpx.codes.not_found == 40410+ assert httpx.codes.not_found == 404 # type: ignore11 12 13 def test_reason_phrase_for_status_code():14 assert httpx.codes.get_reason_phrase(404) == "Not Found"4 unmodified lines