Typing: enable disallow_untyped_calls (#2479)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Typing: enable disallow_untyped_calls Only the test suite needed adjusting to add type hints. * Update setup.cfg
authored by Martijn Pieters · committed by GitHub · parent 884a69a · Browse files · 13 files·+96 added−80 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: Tom Christie <tom@tomchristie.com>
Diff stats
13 files+96 added−80 removed
- tests:+95 added−65 removed
- other:+1 added−15 removed
Provenance
- Commit
933551c- Tree
4389669- Author
Martijn Pieters <mj@zopatista.com>- Committer
GitHub <noreply@github.com>- Parent
884a69a
13 files changed+96 added−80 removed
modified:tests/client/test_async_client.py+4 added-4 removed
87 unmodified lines88 89 90 @pytest.mark.usefixtures("async_environment")91 async def test_stream_request(server):92- async def hello_world():92+ async def hello_world() -> typing.AsyncIterator[bytes]:93 yield b"Hello, "94 yield b"world!"95 96 async with httpx.AsyncClient() as client:2 unmodified lines99 100 101 @pytest.mark.usefixtures("async_environment")102 async def test_cannot_stream_sync_request(server):103- def hello_world(): # pragma: no cover103+ def hello_world() -> typing.Iterator[bytes]: # pragma: no cover104 yield b"Hello, "105 yield b"world!"106 107 async with httpx.AsyncClient() as client:71 unmodified lines179 180 @pytest.mark.usefixtures("async_environment")181 async def test_context_managed_transport():182 class Transport(httpx.AsyncBaseTransport):183- def __init__(self):184- self.events = []183+ def __init__(self) -> None:184+ self.events: typing.List[str] = []185 186 async def aclose(self):187 # The base implementation of httpx.AsyncBaseTransport just188 # calls into `.aclose`, so simple transport cases can just override185 unmodified linesmodified:tests/client/test_auth.py+2 added-2 removed
111 unmodified lines112 """113 114 requires_response_body = True115 116- def __init__(self, token):116+ def __init__(self, token: str) -> None:117 self.token = token118 119 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:120 request.headers["Authorization"] = self.token567 unmodified lines688 url = "https://example.org/"689 auth = DigestAuth(username="user", password="password123")690 app = DigestApp()691 692- async def streaming_body():692+ async def streaming_body() -> typing.AsyncIterator[bytes]:693 yield b"Example request body" # pragma: no cover694 695 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:696 with pytest.raises(httpx.StreamConsumed):67 unmodified linesmodified:tests/client/test_client.py+3 added-3 removed
118 unmodified lines119 assert body == b"Hello, world!"120 121 122 def test_cannot_stream_async_request(server):123- async def hello_world(): # pragma: no cover123+ async def hello_world() -> typing.AsyncIterator[bytes]: # pragma: no cover124 yield b"Hello, "125 yield b"world!"126 127 with httpx.Client() as client:100 unmodified lines228 229 230 def test_context_managed_transport():231 class Transport(httpx.BaseTransport):232- def __init__(self):233- self.events = []232+ def __init__(self) -> None:233+ self.events: typing.List[str] = []234 235 def close(self):236 # The base implementation of httpx.BaseTransport just237 # calls into `.close`, so simple transport cases can just override223 unmodified linesmodified:tests/client/test_redirects.py+3 added-1 removed
1+import typing2+3 import pytest4 5 import httpx6 345 unmodified lines352 def test_cannot_redirect_streaming_body():353 client = httpx.Client(transport=ConsumeBodyTransport(redirects))354 url = "https://example.org/redirect_body"355 354- def streaming_body():356+ def streaming_body() -> typing.Iterator[bytes]:357 yield b"Example request body" # pragma: no cover358 359 with pytest.raises(httpx.StreamConsumed):360 client.post(url, content=streaming_body(), follow_redirects=True)87 unmodified linesmodified:tests/models/test_requests.py+9 added-9 removed
29 unmodified lines30 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}31 32 33 def test_generator_with_transfer_encoding_header():34- def content():34+ def content() -> typing.Iterator[bytes]:35 yield b"test 123" # pragma: no cover36 37 request = httpx.Request("POST", "http://example.org", content=content())38 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}39 40 41 def test_generator_with_content_length_header():42- def content():42+ def content() -> typing.Iterator[bytes]:43 yield b"test 123" # pragma: no cover44 45 headers = {"Content-Length": "8"}46 request = httpx.Request(52 unmodified lines99 100 101 def test_cannot_access_streaming_content_without_read():102 # Ensure that streaming requests103- def streaming_body(): # pragma: no cover104- yield ""103+ def streaming_body() -> typing.Iterator[bytes]: # pragma: no cover104+ yield b""105 106 request = httpx.Request("POST", "http://example.org", content=streaming_body())107 with pytest.raises(httpx.RequestNotRead):108 request.content109 110 111 def test_transfer_encoding_header():112- async def streaming_body(data):112+ async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:113 yield data # pragma: no cover114 115 data = streaming_body(b"test 123")116 7 unmodified lines124 `Transfer-Encoding` should be ignored if `Content-Length` has been set explicitly.125 See https://github.com/encode/httpx/issues/1168126 """127 128- def streaming_body(data):128+ def streaming_body(data: bytes) -> typing.Iterator[bytes]:129 yield data # pragma: no cover130 131 data = streaming_body(b"abcd")132 17 unmodified lines150 assert request.headers["Accept-Encoding"] == "identity"151 152 153 def test_override_content_length_header():154- async def streaming_body(data):154+ async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:155 yield data # pragma: no cover156 157 data = streaming_body(b"test 123")158 headers = {"Content-Length": "8"}34 unmodified lines193 194 195 @pytest.mark.asyncio196 async def test_request_async_streaming_content_picklable():197- async def streaming_body(data):197+ async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:198 yield data199 200 data = streaming_body(b"test 123")201 request = httpx.Request("POST", "http://example.org", content=data)9 unmodified lines211 assert pickle_request.content == b"test 123"212 213 214 def test_request_generator_content_picklable():215- def content():215+ def content() -> typing.Iterator[bytes]:216 yield b"test 123" # pragma: no cover217 218 request = httpx.Request("POST", "http://example.org", content=content())219 pickle_request = pickle.loads(pickle.dumps(request))9 unmodified linesmodified:tests/models/test_responses.py+7 added-6 removed
1 import json2 import pickle3+import typing4 5 import chardet6 import pytest7 6 unmodified lines14 yield b"Hello, "15 yield b"world!"16 17 17-def streaming_body():18+def streaming_body() -> typing.Iterator[bytes]:19 yield b"Hello, "20 yield b"world!"21 22 22-async def async_streaming_body():23+async def async_streaming_body() -> typing.AsyncIterator[bytes]:24 yield b"Hello, "25 yield b"world!"26 27 368 unmodified lines396 assert parts == [b"Hello, world!"]397 398 399 def test_iter_raw_doesnt_return_empty_chunks():399- def streaming_body_with_empty_chunks():400+ def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:401 yield b"Hello, "402 yield b""403 yield b"world!"404 yield b""134 unmodified lines539 assert parts == []540 541 542 def test_iter_bytes_doesnt_return_empty_chunks():542- def streaming_body_with_empty_chunks():543+ def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:544 yield b"Hello, "545 yield b""546 yield b"world!"547 yield b""367 unmodified lines915 response.request916 917 918 def test_generator_with_transfer_encoding_header():918- def content():919+ def content() -> typing.Iterator[bytes]:920 yield b"test 123" # pragma: no cover921 922 response = httpx.Response(200, content=content())923 assert response.headers == {"Transfer-Encoding": "chunked"}924 925 926 def test_generator_with_content_length_header():926- def content():927+ def content() -> typing.Iterator[bytes]:928 yield b"test 123" # pragma: no cover929 930 headers = {"Content-Length": "8"}931 response = httpx.Response(200, content=content(), headers=headers)83 unmodified linesmodified:tests/conftest.py+16 added-10 removed
18 unmodified lines19 20 from httpx import URL21 from tests.concurrency import sleep22 23+if typing.TYPE_CHECKING: # pragma: no cover24+ from httpx._transports.asgi import _Receive, _Send25+26 ENVIRONMENT_VARIABLES = {27 "SSL_CERT_FILE",28 "SSL_CERT_DIR",29 "HTTP_PROXY",44 unmodified lines74 os.environ.clear()75 os.environ.update(original_environ)76 77 75-async def app(scope, receive, send):78+_Scope = typing.Dict[str, typing.Any]79+80+81+async def app(scope: _Scope, receive: "_Receive", send: "_Send") -> None:82 assert scope["type"] == "http"83 if scope["path"].startswith("/slow_response"):84 await slow_response(scope, receive, send)85 elif scope["path"].startswith("/status"):11 unmodified lines97 else:98 await hello_world(scope, receive, send)99 100 95-async def hello_world(scope, receive, send):101+async def hello_world(scope: _Scope, receive: "_Receive", send: "_Send") -> None:102 await send(103 {104 "type": "http.response.start",105 "status": 200,2 unmodified lines108 )109 await send({"type": "http.response.body", "body": b"Hello, world!"})110 111 106-async def hello_world_json(scope, receive, send):112+async def hello_world_json(scope: _Scope, receive: "_Receive", send: "_Send") -> None:113 await send(114 {115 "type": "http.response.start",116 "status": 200,2 unmodified lines119 )120 await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})121 122 117-async def slow_response(scope, receive, send):123+async def slow_response(scope: _Scope, receive: "_Receive", send: "_Send") -> None:124 await sleep(1.0)125 await send(126 {127 "type": "http.response.start",3 unmodified lines131 )132 await send({"type": "http.response.body", "body": b"Hello, world!"})133 134 129-async def status_code(scope, receive, send):135+async def status_code(scope: _Scope, receive: "_Receive", send: "_Send") -> None:136 status_code = int(scope["path"].replace("/status/", ""))137 await send(138 {139 "type": "http.response.start",3 unmodified lines143 )144 await send({"type": "http.response.body", "body": b"Hello, world!"})145 146 141-async def echo_body(scope, receive, send):147+async def echo_body(scope: _Scope, receive: "_Receive", send: "_Send") -> None:148 body = b""149 more_body = True150 151 while more_body:10 unmodified lines162 )163 await send({"type": "http.response.body", "body": body})164 165 160-async def echo_binary(scope, receive, send):166+async def echo_binary(scope: _Scope, receive: "_Receive", send: "_Send") -> None:167 body = b""168 more_body = True169 170 while more_body:10 unmodified lines181 )182 await send({"type": "http.response.body", "body": body})183 184 179-async def echo_headers(scope, receive, send):185+async def echo_headers(scope: _Scope, receive: "_Receive", send: "_Send") -> None:186 body = {187 name.capitalize().decode(): value.decode()188 for name, value in scope.get("headers", [])189 }6 unmodified lines196 )197 await send({"type": "http.response.body", "body": json.dumps(body).encode()})198 199 194-async def redirect_301(scope, receive, send):200+async def redirect_301(scope: _Scope, receive: "_Receive", send: "_Send") -> None:201 await send(202 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}203 )204 await send({"type": "http.response.body"})75 unmodified lines280 self.restart_requested.set()281 while not self.started:282 await sleep(0.2)283 278- async def watch_restarts(self): # pragma: no cover284+ async def watch_restarts(self) -> None: # pragma: no cover285 while True:286 if self.should_exit:287 return288 41 unmodified linesmodified:tests/test_api.py+3 added-1 removed
1+import typing2+3 import pytest4 5 import httpx6 12 unmodified lines19 assert response.reason_phrase == "OK"20 21 22 def test_post_byte_iterator(server):21- def data():23+ def data() -> typing.Iterator[bytes]:24 yield b"Hello"25 yield b", "26 yield b"world!"27 60 unmodified linesmodified:tests/test_content.py+7 added-7 removed
61 unmodified lines62 63 @pytest.mark.asyncio64 async def test_async_bytesio_content():65 class AsyncBytesIO:66- def __init__(self, content: bytes):66+ def __init__(self, content: bytes) -> None:67 self._idx = 068 self._content = content69 70 async def aread(self, chunk_size: int) -> bytes:15 unmodified lines86 87 88 @pytest.mark.asyncio89 async def test_iterator_content():90- def hello_world():90+ def hello_world() -> typing.Iterator[bytes]:91 yield b"Hello, "92 yield b"world!"93 94 headers, stream = encode_request(content=hello_world())9 unmodified lines104 [part for part in stream]105 106 # Support 'data' for compat with requests.107 with pytest.warns(DeprecationWarning):108- headers, stream = encode_request(data=hello_world())108+ headers, stream = encode_request(data=hello_world()) # type: ignore109 assert isinstance(stream, typing.Iterable)110 assert not isinstance(stream, typing.AsyncIterable)111 112 content = b"".join([part for part in stream])3 unmodified lines116 117 118 @pytest.mark.asyncio119 async def test_aiterator_content():120- async def hello_world():120+ async def hello_world() -> typing.AsyncIterator[bytes]:121 yield b"Hello, "122 yield b"world!"123 124 headers, stream = encode_request(content=hello_world())9 unmodified lines134 [part async for part in stream]135 136 # Support 'data' for compat with requests.137 with pytest.warns(DeprecationWarning):138- headers, stream = encode_request(data=hello_world())138+ headers, stream = encode_request(data=hello_world()) # type: ignore139 assert not isinstance(stream, typing.Iterable)140 assert isinstance(stream, typing.AsyncIterable)141 142 content = b"".join([part async for part in stream])265 unmodified lines408 409 410 @pytest.mark.asyncio411 async def test_response_iterator_content():412- def hello_world():412+ def hello_world() -> typing.Iterator[bytes]:413 yield b"Hello, "414 yield b"world!"415 416 headers, stream = encode_response(content=hello_world())10 unmodified lines427 428 429 @pytest.mark.asyncio430 async def test_response_aiterator_content():431- async def hello_world():431+ async def hello_world() -> typing.AsyncIterator[bytes]:432 yield b"Hello, "433 yield b"world!"434 435 headers, stream = encode_response(content=hello_world())15 unmodified linesmodified:tests/test_decoders.py+4 added-3 removed
1+import typing2 import zlib3 4 import chardet5 import pytest121 unmodified lines127 async def test_streaming():128 body = b"test 123"129 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)130 130- async def compress(body):131+ async def compress(body: bytes) -> typing.AsyncIterator[bytes]:132 yield compressor.compress(body)133 yield compressor.flush()134 135 headers = [(b"Content-Encoding", b"gzip")]50 unmodified lines186 ],187 )188 @pytest.mark.asyncio189 async def test_text_decoder_with_autodetect(data, encoding):189- async def iterator():190+ async def iterator() -> typing.AsyncIterator[bytes]:191 nonlocal data192 for chunk in data:193 yield chunk194 14 unmodified lines209 210 211 @pytest.mark.asyncio212 async def test_text_decoder_known_encoding():212- async def iterator():213+ async def iterator() -> typing.AsyncIterator[bytes]:214 yield b"\x83g"215 yield b"\x83"216 yield b"\x89\x83x\x83\x8b"217 142 unmodified linesmodified:tests/test_main.py+19 added-13 removed
1 import os2+import typing3 4 from click.testing import CliRunner5 6 import httpx7+from httpx import main8 9+if typing.TYPE_CHECKING: # pragma: no cover10+ # don't let mypy be misled by the fallback defined in httpx/__init__.py11+ from httpx._main import main # noqa: F81112 8-def splitlines(output):13+14+def splitlines(output: str) -> typing.Iterable[str]:15 return [line.strip() for line in output.splitlines()]16 17 12-def remove_date_header(lines):18+def remove_date_header(lines: typing.Iterable[str]) -> typing.Iterable[str]:19 return [line for line in lines if not line.startswith("date:")]20 21 22 def test_help():23 runner = CliRunner()18- result = runner.invoke(httpx.main, ["--help"])24+ result = runner.invoke(main, ["--help"])25 assert result.exit_code == 026 assert "A next generation HTTP client." in result.output27 28 29 def test_get(server):30 url = str(server.url)31 runner = CliRunner()26- result = runner.invoke(httpx.main, [url])32+ result = runner.invoke(main, [url])33 assert result.exit_code == 034 assert remove_date_header(splitlines(result.output)) == [35 "HTTP/1.1 200 OK",36 "server: uvicorn",6 unmodified lines43 44 def test_json(server):45 url = str(server.url.copy_with(path="/json"))46 runner = CliRunner()41- result = runner.invoke(httpx.main, [url])47+ result = runner.invoke(main, [url])48 assert result.exit_code == 049 assert remove_date_header(splitlines(result.output)) == [50 "HTTP/1.1 200 OK",51 "server: uvicorn",9 unmodified lines61 def test_binary(server):62 url = str(server.url.copy_with(path="/echo_binary"))63 runner = CliRunner()64 content = "Hello, world!"59- result = runner.invoke(httpx.main, [url, "-c", content])65+ result = runner.invoke(main, [url, "-c", content])66 assert result.exit_code == 067 assert remove_date_header(splitlines(result.output)) == [68 "HTTP/1.1 200 OK",69 "server: uvicorn",6 unmodified lines76 77 def test_redirects(server):78 url = str(server.url.copy_with(path="/redirect_301"))79 runner = CliRunner()74- result = runner.invoke(httpx.main, [url])80+ result = runner.invoke(main, [url])81 assert result.exit_code == 182 assert remove_date_header(splitlines(result.output)) == [83 "HTTP/1.1 301 Moved Permanently",84 "server: uvicorn",5 unmodified lines90 91 def test_follow_redirects(server):92 url = str(server.url.copy_with(path="/redirect_301"))93 runner = CliRunner()88- result = runner.invoke(httpx.main, [url, "--follow-redirects"])94+ result = runner.invoke(main, [url, "--follow-redirects"])95 assert result.exit_code == 096 assert remove_date_header(splitlines(result.output)) == [97 "HTTP/1.1 301 Moved Permanently",98 "server: uvicorn",11 unmodified lines110 111 def test_post(server):112 url = str(server.url.copy_with(path="/echo_body"))113 runner = CliRunner()108- result = runner.invoke(httpx.main, [url, "-m", "POST", "-j", '{"hello": "world"}'])114+ result = runner.invoke(main, [url, "-m", "POST", "-j", '{"hello": "world"}'])115 assert result.exit_code == 0116 assert remove_date_header(splitlines(result.output)) == [117 "HTTP/1.1 200 OK",118 "server: uvicorn",6 unmodified lines125 126 def test_verbose(server):127 url = str(server.url)128 runner = CliRunner()123- result = runner.invoke(httpx.main, [url, "-v"])129+ result = runner.invoke(main, [url, "-v"])130 assert result.exit_code == 0131 assert remove_date_header(splitlines(result.output)) == [132 "* Connecting to '127.0.0.1'",133 "* Connected to '127.0.0.1' on port 8000",15 unmodified lines149 150 def test_auth(server):151 url = str(server.url)152 runner = CliRunner()147- result = runner.invoke(httpx.main, [url, "-v", "--auth", "username", "password"])153+ result = runner.invoke(main, [url, "-v", "--auth", "username", "password"])154 print(result.output)155 assert result.exit_code == 0156 assert remove_date_header(splitlines(result.output)) == [157 "* Connecting to '127.0.0.1'",18 unmodified lines176 def test_download(server):177 url = str(server.url)178 runner = CliRunner()179 with runner.isolated_filesystem():174- runner.invoke(httpx.main, [url, "--download", "index.txt"])180+ runner.invoke(main, [url, "--download", "index.txt"])181 assert os.path.exists("index.txt")182 with open("index.txt", "r") as input_file:183 assert input_file.read() == "Hello, world!"184 185 186 def test_errors():187 runner = CliRunner()182- result = runner.invoke(httpx.main, ["invalid://example.org"])188+ result = runner.invoke(main, ["invalid://example.org"])189 assert result.exit_code == 1190 assert splitlines(result.output) == [191 "UnsupportedProtocol: Request URL has an unsupported protocol 'invalid://'.",192 ]modified:tests/test_wsgi.py+18 added-6 removed
1 import sys2+import typing3 import wsgiref.validate4 from functools import partial5 from io import StringIO6 7 import pytest8 9 import httpx10 11+if typing.TYPE_CHECKING: # pragma: no cover12+ from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment13 11-def application_factory(output):14+15+def application_factory(output: typing.Iterable[bytes]) -> "WSGIApplication":16 def application(environ, start_response):17 status = "200 OK"18 19 response_headers = [7 unmodified lines27 28 return wsgiref.validate.validator(application)29 30 27-def echo_body(environ, start_response):31+def echo_body(32+ environ: "WSGIEnvironment", start_response: "StartResponse"33+) -> typing.Iterable[bytes]:34 status = "200 OK"35 output = environ["wsgi.input"].read()36 37 response_headers = [4 unmodified lines42 43 return [output]44 45 40-def echo_body_with_response_stream(environ, start_response):46+def echo_body_with_response_stream(47+ environ: "WSGIEnvironment", start_response: "StartResponse"48+) -> typing.Iterable[bytes]:49 status = "200 OK"50 51 response_headers = [("Content-Type", "text/plain")]52 53 start_response(status, response_headers)54 47- def output_generator(f):55+ def output_generator(f: typing.IO[bytes]) -> typing.Iterator[bytes]:56 while True:57 output = f.read(2)58 if not output:59 break1 unmodified line61 62 return output_generator(f=environ["wsgi.input"])63 64 57-def raise_exc(environ, start_response, exc=ValueError):65+def raise_exc(66+ environ: "WSGIEnvironment",67+ start_response: "StartResponse",68+ exc: typing.Type[Exception] = ValueError,69+) -> typing.Iterable[bytes]:70 status = "500 Server Error"71 output = b"Nope!"72 73 response_headers = [3 unmodified lines77 try:78 raise exc()79 except exc:80 exc_info = sys.exc_info()69- start_response(status, response_headers, exc_info=exc_info)81+ start_response(status, response_headers, exc_info)82 83 return [output]84 85 90 unmodified linesmodified:setup.cfg+1 added-15 removed
1 unmodified line2 ignore = W503, E203, B305, PIE8013 max-line-length = 1204 5 [mypy]6-disallow_untyped_defs = True7-disallow_any_generics = True6 ignore_missing_imports = True9-no_implicit_optional = True10-show_error_codes = True11-warn_unused_ignores = True12-warn_unused_configs = True13-disallow_subclassing_any = True14-check_untyped_defs = True15-disallow_untyped_decorators = True16-warn_redundant_casts = True17-strict_concatenate = True18-disallow_incomplete_defs = True19-no_implicit_reexport = True20-warn_return_any = True21-strict_equality = True7+strict = True8 9 [mypy-tests.*]10 disallow_untyped_defs = False11 check_untyped_defs = True17 unmodified lines