Skip to content
Myr

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

13 files+96 added−80 removed

modified:tests/client/test_async_client.py+4 added-4 removed
87 unmodified lines
888990@pytest.mark.usefixtures("async_environment")91async 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!"9596 async with httpx.AsyncClient() as client:
2 unmodified lines
99100101@pytest.mark.usefixtures("async_environment")102async 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!"106107 async with httpx.AsyncClient() as client:
71 unmodified lines
179180@pytest.mark.usefixtures("async_environment")181async 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] = []185186 async def aclose(self):187 # The base implementation of httpx.AsyncBaseTransport just188 # calls into `.aclose`, so simple transport cases can just override
185 unmodified lines
modified:tests/client/test_auth.py+2 added-2 removed
111 unmodified lines
112 """113114 requires_response_body = True115116 def __init__(self, token):116 def __init__(self, token: str) -> None:117 self.token = token118119 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:120 request.headers["Authorization"] = self.token
567 unmodified lines
688 url = "https://example.org/"689 auth = DigestAuth(username="user", password="password123")690 app = DigestApp()691692 async def streaming_body():692 async def streaming_body() -> typing.AsyncIterator[bytes]:693 yield b"Example request body" # pragma: no cover694695 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:696 with pytest.raises(httpx.StreamConsumed):
67 unmodified lines
modified:tests/client/test_client.py+3 added-3 removed
118 unmodified lines
119 assert body == b"Hello, world!"120121122def 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!"126127 with httpx.Client() as client:
100 unmodified lines
228229230def 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] = []234235 def close(self):236 # The base implementation of httpx.BaseTransport just237 # calls into `.close`, so simple transport cases can just override
223 unmodified lines
modified:tests/client/test_redirects.py+3 added-1 removed
1import typing23import pytest45import httpx6
345 unmodified lines
352def test_cannot_redirect_streaming_body():353 client = httpx.Client(transport=ConsumeBodyTransport(redirects))354 url = "https://example.org/redirect_body"355354 def streaming_body():356 def streaming_body() -> typing.Iterator[bytes]:357 yield b"Example request body" # pragma: no cover358359 with pytest.raises(httpx.StreamConsumed):360 client.post(url, content=streaming_body(), follow_redirects=True)
87 unmodified lines
modified:tests/models/test_requests.py+9 added-9 removed
29 unmodified lines
30 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}313233def test_generator_with_transfer_encoding_header():34 def content():34 def content() -> typing.Iterator[bytes]:35 yield b"test 123" # pragma: no cover3637 request = httpx.Request("POST", "http://example.org", content=content())38 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}394041def test_generator_with_content_length_header():42 def content():42 def content() -> typing.Iterator[bytes]:43 yield b"test 123" # pragma: no cover4445 headers = {"Content-Length": "8"}46 request = httpx.Request(
52 unmodified lines
99100101def 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""105106 request = httpx.Request("POST", "http://example.org", content=streaming_body())107 with pytest.raises(httpx.RequestNotRead):108 request.content109110111def 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 cover114115 data = streaming_body(b"test 123")116
7 unmodified lines
124 `Transfer-Encoding` should be ignored if `Content-Length` has been set explicitly.125 See https://github.com/encode/httpx/issues/1168126 """127128 def streaming_body(data):128 def streaming_body(data: bytes) -> typing.Iterator[bytes]:129 yield data # pragma: no cover130131 data = streaming_body(b"abcd")132
17 unmodified lines
150 assert request.headers["Accept-Encoding"] == "identity"151152153def 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 cover156157 data = streaming_body(b"test 123")158 headers = {"Content-Length": "8"}
34 unmodified lines
193194195@pytest.mark.asyncio196async 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 data199200 data = streaming_body(b"test 123")201 request = httpx.Request("POST", "http://example.org", content=data)
9 unmodified lines
211 assert pickle_request.content == b"test 123"212213214def test_request_generator_content_picklable():215 def content():215 def content() -> typing.Iterator[bytes]:216 yield b"test 123" # pragma: no cover217218 request = httpx.Request("POST", "http://example.org", content=content())219 pickle_request = pickle.loads(pickle.dumps(request))
9 unmodified lines
modified:tests/models/test_responses.py+7 added-6 removed
1import json2import pickle3import typing45import chardet6import pytest7
6 unmodified lines
14 yield b"Hello, "15 yield b"world!"161717def streaming_body():18def streaming_body() -> typing.Iterator[bytes]:19 yield b"Hello, "20 yield b"world!"212222async def async_streaming_body():23async def async_streaming_body() -> typing.AsyncIterator[bytes]:24 yield b"Hello, "25 yield b"world!"2627
368 unmodified lines
396 assert parts == [b"Hello, world!"]397398399def 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 lines
539 assert parts == []540541542def 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 lines
915 response.request916917918def test_generator_with_transfer_encoding_header():918 def content():919 def content() -> typing.Iterator[bytes]:920 yield b"test 123" # pragma: no cover921922 response = httpx.Response(200, content=content())923 assert response.headers == {"Transfer-Encoding": "chunked"}924925926def test_generator_with_content_length_header():926 def content():927 def content() -> typing.Iterator[bytes]:928 yield b"test 123" # pragma: no cover929930 headers = {"Content-Length": "8"}931 response = httpx.Response(200, content=content(), headers=headers)
83 unmodified lines
modified:tests/conftest.py+16 added-10 removed
18 unmodified lines
1920from httpx import URL21from tests.concurrency import sleep2223if typing.TYPE_CHECKING: # pragma: no cover24 from httpx._transports.asgi import _Receive, _Send2526ENVIRONMENT_VARIABLES = {27 "SSL_CERT_FILE",28 "SSL_CERT_DIR",29 "HTTP_PROXY",
44 unmodified lines
74 os.environ.clear()75 os.environ.update(original_environ)767775async def app(scope, receive, send):78_Scope = typing.Dict[str, typing.Any]798081async 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 lines
97 else:98 await hello_world(scope, receive, send)9910095async def hello_world(scope, receive, send):101async def hello_world(scope: _Scope, receive: "_Receive", send: "_Send") -> None:102 await send(103 {104 "type": "http.response.start",105 "status": 200,
2 unmodified lines
108 )109 await send({"type": "http.response.body", "body": b"Hello, world!"})110111106async def hello_world_json(scope, receive, send):112async 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 lines
119 )120 await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})121122117async def slow_response(scope, receive, send):123async 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 lines
131 )132 await send({"type": "http.response.body", "body": b"Hello, world!"})133134129async def status_code(scope, receive, send):135async 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 lines
143 )144 await send({"type": "http.response.body", "body": b"Hello, world!"})145146141async def echo_body(scope, receive, send):147async def echo_body(scope: _Scope, receive: "_Receive", send: "_Send") -> None:148 body = b""149 more_body = True150151 while more_body:
10 unmodified lines
162 )163 await send({"type": "http.response.body", "body": body})164165160async def echo_binary(scope, receive, send):166async def echo_binary(scope: _Scope, receive: "_Receive", send: "_Send") -> None:167 body = b""168 more_body = True169170 while more_body:
10 unmodified lines
181 )182 await send({"type": "http.response.body", "body": body})183184179async def echo_headers(scope, receive, send):185async 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 lines
196 )197 await send({"type": "http.response.body", "body": json.dumps(body).encode()})198199194async def redirect_301(scope, receive, send):200async 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 lines
280 self.restart_requested.set()281 while not self.started:282 await sleep(0.2)283278 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 lines
modified:tests/test_api.py+3 added-1 removed
1import typing23import pytest45import httpx6
12 unmodified lines
19 assert response.reason_phrase == "OK"202122def 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 lines
modified:tests/test_content.py+7 added-7 removed
61 unmodified lines
6263@pytest.mark.asyncio64async 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 = content6970 async def aread(self, chunk_size: int) -> bytes:
15 unmodified lines
868788@pytest.mark.asyncio89async def test_iterator_content():90 def hello_world():90 def hello_world() -> typing.Iterator[bytes]:91 yield b"Hello, "92 yield b"world!"9394 headers, stream = encode_request(content=hello_world())
9 unmodified lines
104 [part for part in stream]105106 # 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)111112 content = b"".join([part for part in stream])
3 unmodified lines
116117118@pytest.mark.asyncio119async 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!"123124 headers, stream = encode_request(content=hello_world())
9 unmodified lines
134 [part async for part in stream]135136 # 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)141142 content = b"".join([part async for part in stream])
265 unmodified lines
408409410@pytest.mark.asyncio411async def test_response_iterator_content():412 def hello_world():412 def hello_world() -> typing.Iterator[bytes]:413 yield b"Hello, "414 yield b"world!"415416 headers, stream = encode_response(content=hello_world())
10 unmodified lines
427428429@pytest.mark.asyncio430async 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!"434435 headers, stream = encode_response(content=hello_world())
15 unmodified lines
modified:tests/test_decoders.py+4 added-3 removed
1import typing2import zlib34import chardet5import pytest
121 unmodified lines
127async def test_streaming():128 body = b"test 123"129 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)130130 async def compress(body):131 async def compress(body: bytes) -> typing.AsyncIterator[bytes]:132 yield compressor.compress(body)133 yield compressor.flush()134135 headers = [(b"Content-Encoding", b"gzip")]
50 unmodified lines
186 ],187)188@pytest.mark.asyncio189async 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 lines
209210211@pytest.mark.asyncio212async 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 lines
modified:tests/test_main.py+19 added-13 removed
1import os2import typing34from click.testing import CliRunner56import httpx7from httpx import main89if 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: F811128def splitlines(output):1314def splitlines(output: str) -> typing.Iterable[str]:15 return [line.strip() for line in output.splitlines()]161712def remove_date_header(lines):18def remove_date_header(lines: typing.Iterable[str]) -> typing.Iterable[str]:19 return [line for line in lines if not line.startswith("date:")]202122def 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.output272829def 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 lines
4344def 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 lines
61def 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 lines
7677def 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 lines
9091def 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 lines
110111def 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 lines
125126def 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 lines
149150def 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 lines
176def 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!"184185186def 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
1import sys2import typing3import wsgiref.validate4from functools import partial5from io import StringIO67import pytest89import httpx1011if typing.TYPE_CHECKING: # pragma: no cover12 from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment1311def application_factory(output):1415def application_factory(output: typing.Iterable[bytes]) -> "WSGIApplication":16 def application(environ, start_response):17 status = "200 OK"1819 response_headers = [
7 unmodified lines
2728 return wsgiref.validate.validator(application)293027def echo_body(environ, start_response):31def echo_body(32 environ: "WSGIEnvironment", start_response: "StartResponse"33) -> typing.Iterable[bytes]:34 status = "200 OK"35 output = environ["wsgi.input"].read()3637 response_headers = [
4 unmodified lines
4243 return [output]444540def echo_body_with_response_stream(environ, start_response):46def echo_body_with_response_stream(47 environ: "WSGIEnvironment", start_response: "StartResponse"48) -> typing.Iterable[bytes]:49 status = "200 OK"5051 response_headers = [("Content-Type", "text/plain")]5253 start_response(status, response_headers)5447 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 break
1 unmodified line
6162 return output_generator(f=environ["wsgi.input"])636457def raise_exc(environ, start_response, exc=ValueError):65def 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!"7273 response_headers = [
3 unmodified lines
77 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)8283 return [output]8485
90 unmodified lines
modified:setup.cfg+1 added-15 removed
1 unmodified line
2ignore = W503, E203, B305, PIE8013max-line-length = 12045[mypy]6disallow_untyped_defs = True7disallow_any_generics = True6ignore_missing_imports = True9no_implicit_optional = True10show_error_codes = True11warn_unused_ignores = True12warn_unused_configs = True13disallow_subclassing_any = True14check_untyped_defs = True15disallow_untyped_decorators = True16warn_redundant_casts = True17strict_concatenate = True18disallow_incomplete_defs = True19no_implicit_reexport = True20warn_return_any = True21strict_equality = True7strict = True89[mypy-tests.*]10disallow_untyped_defs = False11check_untyped_defs = True
17 unmodified lines