Skip to content

Commit

Permalink
test-case-headers
Browse files Browse the repository at this point in the history
  • Loading branch information
c4ffein committed Aug 8, 2024
1 parent 3c55d99 commit d2d3146
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
12 changes: 11 additions & 1 deletion ninja/testing/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ def build_absolute_uri(location: Optional[str] = None) -> str:
class NinjaClientBase:
__test__ = False # <- skip pytest

def __init__(self, router_or_app: Union[NinjaAPI, Router]) -> None:
def __init__(
self,
router_or_app: Union[NinjaAPI, Router],
headers: Optional[Dict[str, str]] = None,
) -> None:
self.headers = headers or {}
self.router_or_app = router_or_app

def get(
Expand Down Expand Up @@ -82,6 +87,11 @@ def request(
request_params["body"] = json_dumps(json, cls=NinjaJSONEncoder)
if data is None:
data = {}
if self.headers or request_params.get("headers"):
request_params["headers"] = {
**self.headers,
**request_params.get("headers", {}),
}
func, request, kwargs = self._resolve(method, path, data, request_params)
return self._call(func, request, kwargs) # type: ignore

Expand Down
23 changes: 23 additions & 0 deletions tests/test_test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ def simple_get(request):
return "test"


@router.get("/test-headers")
def get_headers(request):
return dict(request.headers)


client = TestClient(router)


Expand Down Expand Up @@ -78,3 +83,21 @@ def test_json_as_body():
ClientTestSchema.model_validate_json(request.body).model_dump_json()
== schema_instance.model_dump_json()
)


headered_client = TestClient(router, headers={"A": "a", "B": "b"})


def test_client_request_only_header():
r = client.get("/test-headers", headers={"A": "na"})
assert r.json() == {"A": "na"}


def test_headered_client_request_with_default_headers():
r = headered_client.get("/test-headers")
assert r.json() == {"A": "a", "B": "b"}


def test_headered_client_request_with_overwritten_and_additional_headers():
r = headered_client.get("/test-headers", headers={"A": "na", "C": "nc"})
assert r.json() == {"A": "na", "B": "b", "C": "nc"}

0 comments on commit d2d3146

Please sign in to comment.