Skip to content

Commit

Permalink
Type check tests (#1054)
Browse files Browse the repository at this point in the history
  • Loading branch information
florimondmanca authored Jul 7, 2020
1 parent 3230cb3 commit 0296c2b
Show file tree
Hide file tree
Showing 17 changed files with 76 additions and 51 deletions.
2 changes: 1 addition & 1 deletion httpx/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,4 @@
# (filename, file (or text), content_type)
Tuple[Optional[str], FileContent, Optional[str]],
]
RequestFiles = Union[Mapping[str, FileTypes], List[Tuple[str, FileTypes]]]
RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
2 changes: 1 addition & 1 deletion scripts/check
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ set -x

${PREFIX}black --check --diff --target-version=py36 $SOURCE_FILES
${PREFIX}flake8 $SOURCE_FILES
${PREFIX}mypy httpx
${PREFIX}mypy $SOURCE_FILES
${PREFIX}isort --check --diff --project=httpx $SOURCE_FILES
5 changes: 4 additions & 1 deletion tests/client/test_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,11 @@ def test_dispatch_deprecated():


def test_asgi_dispatch_deprecated():
async def app(scope, receive, send):
pass

with pytest.warns(DeprecationWarning) as record:
ASGIDispatch(None)
ASGIDispatch(app)

assert len(record) == 1
assert (
Expand Down
19 changes: 11 additions & 8 deletions tests/client/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
Auth,
Client,
DigestAuth,
Headers,
ProtocolError,
Request,
RequestBodyUnavailable,
Expand Down Expand Up @@ -86,23 +85,26 @@ def __init__(
async def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, int, bytes],
headers: typing.List[typing.Tuple[bytes, bytes]],
stream: ContentStream,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.AsyncByteStream = None,
timeout: typing.Dict[str, typing.Optional[float]] = None,
) -> typing.Tuple[
bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream
]:
if self._response_count < self.send_response_after_attempt:
return self.challenge_send(method, url, headers, stream)
assert headers is not None
return self.challenge_send(method, headers)

authorization = get_header_value(headers, "Authorization")
body = JSONStream({"auth": authorization})
return b"HTTP/1.1", 200, b"", [], body

def challenge_send(
self, method: bytes, url: URL, headers: Headers, stream: ContentStream,
) -> typing.Tuple[int, bytes, Headers, ContentStream]:
self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]],
) -> typing.Tuple[
bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream
]:
self._response_count += 1
nonce = (
hashlib.sha256(os.urandom(8)).hexdigest()
Expand Down Expand Up @@ -297,7 +299,8 @@ async def test_auth_hidden_header() -> None:
async def test_auth_invalid_type() -> None:
url = "https://example.org/"
client = AsyncClient(
transport=AsyncMockTransport(), auth="not a tuple, not a callable",
transport=AsyncMockTransport(),
auth="not a tuple, not a callable", # type: ignore
)
with pytest.raises(TypeError):
await client.get(url)
Expand Down
5 changes: 4 additions & 1 deletion tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,11 @@ def test_dispatch_deprecated():


def test_wsgi_dispatch_deprecated():
def app(start_response, environ):
pass

with pytest.warns(DeprecationWarning) as record:
WSGIDispatch(None)
WSGIDispatch(app)

assert len(record) == 1
assert (
Expand Down
7 changes: 4 additions & 3 deletions tests/client/test_cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@ class MockTransport(httpcore.AsyncHTTPTransport):
async def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, int, bytes],
headers: typing.List[typing.Tuple[bytes, bytes]],
stream: ContentStream,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.AsyncByteStream = None,
timeout: typing.Dict[str, typing.Optional[float]] = None,
) -> typing.Tuple[
bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream
]:
host, scheme, port, path = url
body: ContentStream
if path.startswith(b"/echo_cookies"):
cookie = get_header_value(headers, "cookie")
body = JSONStream({"cookies": cookie})
Expand Down
7 changes: 4 additions & 3 deletions tests/client/test_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ class MockTransport(httpcore.AsyncHTTPTransport):
async def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, int, bytes],
headers: typing.List[typing.Tuple[bytes, bytes]],
stream: ContentStream,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.AsyncByteStream = None,
timeout: typing.Dict[str, typing.Optional[float]] = None,
) -> typing.Tuple[
bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream
]:
assert headers is not None
headers_dict = {
key.decode("ascii"): value.decode("ascii") for key, value in headers
}
Expand Down
4 changes: 2 additions & 2 deletions tests/client/test_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@

def test_client_headers():
client = AsyncClient()
client.headers = {"a": "b"}
client.headers = {"a": "b"} # type: ignore
assert isinstance(client.headers, Headers)
assert client.headers["A"] == "b"


def test_client_cookies():
client = AsyncClient()
client.cookies = {"a": "b"}
client.cookies = {"a": "b"} # type: ignore
assert isinstance(client.cookies, Cookies)
mycookies = list(client.cookies.jar)
assert len(mycookies) == 1
Expand Down
6 changes: 5 additions & 1 deletion tests/client/test_proxies.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import httpcore
import pytest

import httpx
Expand All @@ -24,7 +25,9 @@ def test_proxies_parameter(proxies, expected_proxies):

for proxy_key, url in expected_proxies:
assert proxy_key in client.proxies
assert client.proxies[proxy_key].proxy_origin == httpx.URL(url).raw[:3]
proxy = client.proxies[proxy_key]
assert isinstance(proxy, httpcore.AsyncHTTPProxy)
assert proxy.proxy_origin == httpx.URL(url).raw[:3]

assert len(expected_proxies) == len(client.proxies)

Expand Down Expand Up @@ -81,6 +84,7 @@ def test_transport_for_request(url, proxies, expected):
if expected is None:
assert transport is client.transport
else:
assert isinstance(transport, httpcore.AsyncHTTPProxy)
assert transport.proxy_origin == httpx.URL(expected).raw[:3]


Expand Down
13 changes: 6 additions & 7 deletions tests/client/test_queryparams.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,23 @@
import httpcore
import pytest

from httpx import URL, AsyncClient, Headers, QueryParams
from httpx import URL, AsyncClient, QueryParams
from httpx._content_streams import ContentStream, JSONStream


class MockTransport(httpcore.AsyncHTTPTransport):
async def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, int, bytes],
headers: typing.List[typing.Tuple[bytes, bytes]],
stream: ContentStream,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.AsyncByteStream = None,
timeout: typing.Dict[str, typing.Optional[float]] = None,
) -> typing.Tuple[
bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream
]:
headers = Headers()
body = JSONStream({"ok": "ok"})
return b"HTTP/1.1", 200, b"OK", headers, body
return b"HTTP/1.1", 200, b"OK", [], body


def test_client_queryparams():
Expand All @@ -35,7 +34,7 @@ def test_client_queryparams_string():
assert client.params["a"] == "b"

client = AsyncClient()
client.params = "a=b"
client.params = "a=b" # type: ignore
assert isinstance(client.params, QueryParams)
assert client.params["a"] == "b"

Expand Down
17 changes: 9 additions & 8 deletions tests/client/test_redirects.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ async def body():
headers_dict = {
key.decode("ascii"): value.decode("ascii") for key, value in headers
}
content = ByteStream(json.dumps({"headers": headers_dict}).encode())
return b"HTTP/1.1", 200, b"OK", [], content
stream = ByteStream(json.dumps({"headers": headers_dict}).encode())
return b"HTTP/1.1", 200, b"OK", [], stream

elif path == b"/redirect_body":
code = codes.PERMANENT_REDIRECT
Expand All @@ -121,10 +121,10 @@ async def body():
headers_dict = {
key.decode("ascii"): value.decode("ascii") for key, value in headers
}
body = ByteStream(
stream = ByteStream(
json.dumps({"body": content.decode(), "headers": headers_dict}).encode()
)
return b"HTTP/1.1", 200, b"OK", [], body
return b"HTTP/1.1", 200, b"OK", [], stream

elif path == b"/cross_subdomain":
host = get_header_value(headers, "host")
Expand Down Expand Up @@ -402,9 +402,9 @@ class MockCookieTransport(httpcore.AsyncHTTPTransport):
async def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, int, bytes],
headers: typing.List[typing.Tuple[bytes, bytes]],
stream: ContentStream,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.AsyncByteStream = None,
timeout: typing.Dict[str, typing.Optional[float]] = None,
) -> typing.Tuple[
bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream
Expand Down Expand Up @@ -432,7 +432,8 @@ async def request(
]
return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")

elif path == b"/logout":
else:
assert path == b"/logout"
status_code = codes.SEE_OTHER
headers = [
(b"location", b"/"),
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ async def my_async_test():


@pytest.fixture(scope="function", autouse=True)
def clean_environ() -> typing.Dict[str, typing.Any]:
def clean_environ():
"""Keeps os.environ clean for every test without having to mock os.environ"""
original_environ = os.environ.copy()
os.environ.clear()
Expand Down
5 changes: 2 additions & 3 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ def test_stream(server):
assert response.http_version == "HTTP/1.1"


@pytest.mark.asyncio
async def test_get_invalid_url(server):
def test_get_invalid_url():
with pytest.raises(httpx.InvalidURL):
await httpx.get("invalid://example.org")
httpx.get("invalid://example.org")
8 changes: 4 additions & 4 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_load_ssl_config_verify_env_file(https_server, ca_cert_pem_file, config)

def test_load_ssl_config_verify_directory():
path = Path(certifi.where()).parent
ssl_config = SSLConfig(verify=path)
ssl_config = SSLConfig(verify=str(path))
context = ssl_config.ssl_context
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
Expand Down Expand Up @@ -192,7 +192,7 @@ def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: noc

ssl_config = SSLConfig(trust_env=True)

assert ssl_config.ssl_context.keylog_filename is None
assert ssl_config.ssl_context.keylog_filename is None # type: ignore

filename = str(tmpdir.join("test.log"))

Expand All @@ -201,11 +201,11 @@ def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: noc

ssl_config = SSLConfig(trust_env=True)

assert ssl_config.ssl_context.keylog_filename == filename
assert ssl_config.ssl_context.keylog_filename == filename # type: ignore

ssl_config = SSLConfig(trust_env=False)

assert ssl_config.ssl_context.keylog_filename is None
assert ssl_config.ssl_context.keylog_filename is None # type: ignore


@pytest.mark.parametrize(
Expand Down
2 changes: 1 addition & 1 deletion tests/test_content_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ async def test_empty_request():

def test_invalid_argument():
with pytest.raises(TypeError):
encode(123)
encode(123) # type: ignore


@pytest.mark.asyncio
Expand Down
Loading

0 comments on commit 0296c2b

Please sign in to comment.