Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor tests to use MockTransport(<handler_function>) #1281

Merged
merged 11 commits into from
Sep 12, 2020
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ black==20.8b1
cryptography
flake8
flake8-bugbear
flake8-pie
flake8-pie==0.5.*
isort==5.*
mypy
pytest==5.*
Expand Down
62 changes: 19 additions & 43 deletions tests/client/test_cookies.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,19 @@
import typing
import json
from http.cookiejar import Cookie, CookieJar

import httpcore

import httpx
from httpx._content_streams import ByteStream, ContentStream, JSONStream


def get_header_value(headers, key, default=None):
lookup = key.encode("ascii").lower()
for header_key, header_value in headers:
if header_key.lower() == lookup:
return header_value.decode("ascii")
return default


class MockTransport(httpcore.SyncHTTPTransport):
def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.SyncByteStream = None,
timeout: typing.Mapping[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})
return b"HTTP/1.1", 200, b"OK", [], body
elif path.startswith(b"/set_cookie"):
headers = [(b"set-cookie", b"example-name=example-value")]
body = ByteStream(b"")
return b"HTTP/1.1", 200, b"OK", headers, body
else:
raise NotImplementedError() # pragma: no cover
from tests.utils import MockTransport


def get_and_set_cookies(request: httpx.Request) -> httpx.Response:
if request.url.path == "/echo_cookies":
data = {"cookies": request.headers.get("cookie")}
content = json.dumps(data).encode("utf-8")
return httpx.Response(200, content=content)
elif request.url.path == "/set_cookie":
return httpx.Response(200, headers={"set-cookie": "example-name=example-value"})
else:
raise NotImplementedError() # pragma: no cover


def test_set_cookie() -> None:
Expand All @@ -47,7 +23,7 @@ def test_set_cookie() -> None:
url = "http://example.org/echo_cookies"
cookies = {"example-name": "example-value"}

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(get_and_set_cookies))
response = client.get(url, cookies=cookies)

assert response.status_code == 200
Expand Down Expand Up @@ -82,7 +58,7 @@ def test_set_cookie_with_cookiejar() -> None:
)
cookies.set_cookie(cookie)

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(get_and_set_cookies))
response = client.get(url, cookies=cookies)

assert response.status_code == 200
Expand Down Expand Up @@ -117,7 +93,7 @@ def test_setting_client_cookies_to_cookiejar() -> None:
)
cookies.set_cookie(cookie)

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(get_and_set_cookies))
client.cookies = cookies # type: ignore
response = client.get(url)

Expand All @@ -134,7 +110,7 @@ def test_set_cookie_with_cookies_model() -> None:
cookies = httpx.Cookies()
cookies["example-name"] = "example-value"

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(get_and_set_cookies))
response = client.get(url, cookies=cookies)

assert response.status_code == 200
Expand All @@ -144,7 +120,7 @@ def test_set_cookie_with_cookies_model() -> None:
def test_get_cookie() -> None:
url = "http://example.org/set_cookie"

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(get_and_set_cookies))
response = client.get(url)

assert response.status_code == 200
Expand All @@ -156,7 +132,7 @@ def test_cookie_persistence() -> None:
"""
Ensure that Client instances persist cookies between requests.
"""
client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(get_and_set_cookies))

response = client.get("http://example.org/echo_cookies")
assert response.status_code == 200
Expand Down
44 changes: 15 additions & 29 deletions tests/client/test_headers.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,17 @@
#!/usr/bin/env python3

import typing
import json

import httpcore
import pytest

import httpx
from httpx._content_streams import ContentStream, JSONStream


class MockTransport(httpcore.SyncHTTPTransport):
def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.SyncByteStream = None,
timeout: typing.Mapping[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
}
body = JSONStream({"headers": headers_dict})
return b"HTTP/1.1", 200, b"OK", [], body
from tests.utils import MockTransport


def echo_headers(request: httpx.Request) -> httpx.Response:
data = {"headers": dict(request.headers)}
content = json.dumps(data).encode("utf-8")
return httpx.Response(200, content=content)


def test_client_header():
Expand All @@ -35,7 +21,7 @@ def test_client_header():
url = "http://example.org/echo_headers"
headers = {"Example-Header": "example-value"}

client = httpx.Client(transport=MockTransport(), headers=headers)
client = httpx.Client(transport=MockTransport(echo_headers), headers=headers)
response = client.get(url)

assert response.status_code == 200
Expand All @@ -55,7 +41,7 @@ def test_header_merge():
url = "http://example.org/echo_headers"
client_headers = {"User-Agent": "python-myclient/0.2.1"}
request_headers = {"X-Auth-Token": "FooBarBazToken"}
client = httpx.Client(transport=MockTransport(), headers=client_headers)
client = httpx.Client(transport=MockTransport(echo_headers), headers=client_headers)
response = client.get(url, headers=request_headers)

assert response.status_code == 200
Expand All @@ -75,7 +61,7 @@ def test_header_merge_conflicting_headers():
url = "http://example.org/echo_headers"
client_headers = {"X-Auth-Token": "FooBar"}
request_headers = {"X-Auth-Token": "BazToken"}
client = httpx.Client(transport=MockTransport(), headers=client_headers)
client = httpx.Client(transport=MockTransport(echo_headers), headers=client_headers)
response = client.get(url, headers=request_headers)

assert response.status_code == 200
Expand All @@ -93,7 +79,7 @@ def test_header_merge_conflicting_headers():

def test_header_update():
url = "http://example.org/echo_headers"
client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(echo_headers))
first_response = client.get(url)
client.headers.update(
{"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}
Expand Down Expand Up @@ -130,7 +116,7 @@ def test_remove_default_header():
"""
url = "http://example.org/echo_headers"

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(echo_headers))
del client.headers["User-Agent"]

response = client.get(url)
Expand Down Expand Up @@ -160,7 +146,7 @@ def test_host_with_auth_and_port_in_url():
"""
url = "http://username:[email protected]:80/echo_headers"

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(echo_headers))
response = client.get(url)

assert response.status_code == 200
Expand All @@ -183,7 +169,7 @@ def test_host_with_non_default_port_in_url():
"""
url = "http://username:[email protected]:123/echo_headers"

client = httpx.Client(transport=MockTransport())
client = httpx.Client(transport=MockTransport(echo_headers))
response = client.get(url)

assert response.status_code == 200
Expand Down
25 changes: 6 additions & 19 deletions tests/client/test_queryparams.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,9 @@
import typing

import httpcore

import httpx
from httpx._content_streams import ContentStream, JSONStream
from tests.utils import MockTransport


class MockTransport(httpcore.SyncHTTPTransport):
def request(
self,
method: bytes,
url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
headers: typing.List[typing.Tuple[bytes, bytes]] = None,
stream: httpcore.SyncByteStream = None,
timeout: typing.Mapping[str, typing.Optional[float]] = None,
) -> typing.Tuple[
bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream
]:
body = JSONStream({"ok": "ok"})
return b"HTTP/1.1", 200, b"OK", [], body
def hello_world(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, content=b"Hello, world")


def test_client_queryparams():
Expand All @@ -42,7 +27,9 @@ def test_client_queryparams_echo():
url = "http://example.org/echo_queryparams"
client_queryparams = "first=str"
request_queryparams = {"second": "dict"}
client = httpx.Client(transport=MockTransport(), params=client_queryparams)
client = httpx.Client(
transport=MockTransport(hello_world), params=client_queryparams
)
response = client.get(url, params=request_queryparams)

assert response.status_code == 200
Expand Down
Loading