diff --git a/tests/test_testclient.py b/tests/test_testclient.py index 6690289c6..1bf9692a6 100644 --- a/tests/test_testclient.py +++ b/tests/test_testclient.py @@ -1,4 +1,5 @@ import itertools +import sys from asyncio import current_task as asyncio_current_task from contextlib import asynccontextmanager @@ -273,3 +274,48 @@ def homepage(request): client = test_client_factory(app) response = client.get("/", params={"param": param}) assert response.text == param + + +@pytest.mark.parametrize( + "domain, ok", + [ + pytest.param( + "testserver", + True, + marks=[ + pytest.mark.xfail( + sys.version_info < (3, 11), + reason="Fails due to domain handling in http.cookiejar module (see " + "#2152)", + ), + ], + ), + ("testserver.local", True), + ("localhost", False), + ("example.com", False), + ], +) +def test_domain_restricted_cookies(test_client_factory, domain, ok): + """ + Test that test client discards domain restricted cookies which do not match the + base_url of the testclient (`http://testserver` by default). + + The domain `testserver.local` works because the Python http.cookiejar module derives + the "effective domain" by appending `.local` to non-dotted request domains + in accordance with RFC 2965. + """ + + async def app(scope, receive, send): + response = Response("Hello, world!", media_type="text/plain") + response.set_cookie( + "mycookie", + "myvalue", + path="/", + domain=domain, + ) + await response(scope, receive, send) + + client = test_client_factory(app) + response = client.get("/") + cookie_set = len(response.cookies) == 1 + assert cookie_set == ok