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

Test client init to support headers argument #1966

Merged
merged 8 commits into from Dec 3, 2022
8 changes: 7 additions & 1 deletion starlette/testclient.py
Expand Up @@ -368,6 +368,7 @@ def __init__(
backend: str = "asyncio",
backend_options: typing.Optional[typing.Dict[str, typing.Any]] = None,
cookies: httpx._client.CookieTypes = None,
headers: typing.Dict[str, str] = None,
) -> None:
self.async_backend = _AsyncBackend(
backend=backend, backend_options=backend_options or {}
Expand All @@ -385,10 +386,15 @@ def __init__(
raise_server_exceptions=raise_server_exceptions,
root_path=root_path,
)
if headers is None:
headers = {}
if "user-agent" not in headers:
roy-pstr marked this conversation as resolved.
Show resolved Hide resolved
# for backwards compatibility in case no user-agent is set
headers["user-agent"] = "testclient"
super().__init__(
app=self.app,
base_url=base_url,
headers={"user-agent": "testclient"},
headers=headers,
transport=transport,
follow_redirects=True,
cookies=cookies,
Expand Down
22 changes: 22 additions & 0 deletions tests/test_testclient.py
Expand Up @@ -11,6 +11,7 @@
from starlette.middleware import Middleware
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
from starlette.testclient import TestClient
from starlette.websockets import WebSocket, WebSocketDisconnect


Expand Down Expand Up @@ -67,6 +68,27 @@ def homepage(request):
assert response.json() == {"mock": "example"}


def test_testclient_headers_behavior():
"""
We should be able to use the test client with user defined headers.

This could useful if we need to set custom headers for authentication
roy-pstr marked this conversation as resolved.
Show resolved Hide resolved
during tests or in development.

make sure default value of "user-agent" is "testclient" unless overridden.
roy-pstr marked this conversation as resolved.
Show resolved Hide resolved
"""

client = TestClient(mock_service)
assert client.headers.get("user-agent") == "testclient"

client = TestClient(mock_service, headers={"user-agent": "non-default-agent"})
assert client.headers.get("user-agent") == "non-default-agent"

client = TestClient(mock_service, headers={"Authentication": "Bearer 123"})
assert client.headers.get("user-agent") == "testclient"
assert client.headers.get("Authentication") == "Bearer 123"


def test_use_testclient_as_contextmanager(test_client_factory, anyio_backend_name):
"""
This test asserts a number of properties that are important for an
Expand Down