|
| 1 | +"""Request-builder fixtures for REST API / functional HTTP tests.""" |
| 2 | + |
| 3 | +from plone.app.testing import SITE_OWNER_NAME |
| 4 | +from plone.app.testing import SITE_OWNER_PASSWORD |
| 5 | +from Products.CMFPlone.Portal import PloneSite |
| 6 | +from pytest_plone import _types as t |
| 7 | +from urllib.parse import urljoin |
| 8 | +from urllib.parse import urlparse |
| 9 | + |
| 10 | +import pytest |
| 11 | +import requests |
| 12 | + |
| 13 | + |
| 14 | +_ROLE_AUTH: dict[str, tuple[str, str] | None] = { |
| 15 | + "Manager": (SITE_OWNER_NAME, SITE_OWNER_PASSWORD), |
| 16 | + "Anonymous": None, |
| 17 | +} |
| 18 | + |
| 19 | + |
| 20 | +class RelativeSession(requests.Session): |
| 21 | + """`requests.Session` that resolves relative URLs against a base URL. |
| 22 | +
|
| 23 | + Minimal standalone equivalent of ``plone.restapi.testing.RelativeSession`` |
| 24 | + — avoids pulling the full ``plone.restapi[test]`` import chain into |
| 25 | + pytest-plone's runtime. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, base_url: str) -> None: |
| 29 | + super().__init__() |
| 30 | + if not base_url.endswith("/"): |
| 31 | + base_url += "/" |
| 32 | + self._base_url = base_url |
| 33 | + |
| 34 | + def request(self, method: str, url: str, **kwargs): # type: ignore[override] |
| 35 | + if urlparse(url).scheme not in ("http", "https"): |
| 36 | + url = urljoin(self._base_url, url.lstrip("/")) |
| 37 | + return super().request(method, url, **kwargs) |
| 38 | + |
| 39 | + |
| 40 | +@pytest.fixture |
| 41 | +def request_factory( |
| 42 | + functional_portal: PloneSite, request: pytest.FixtureRequest |
| 43 | +) -> t.RequestFactory: |
| 44 | + """Builder fixture for HTTP request sessions against the functional portal. |
| 45 | +
|
| 46 | + Returns a callable that produces a :class:`RelativeSession` bound to the |
| 47 | + portal URL. The session is closed automatically at the end of the test. |
| 48 | +
|
| 49 | + Parameters accepted by the returned callable: |
| 50 | +
|
| 51 | + - ``role`` — ``"Manager"`` or ``"Anonymous"`` (default). Maps to |
| 52 | + predefined test credentials. Unknown roles raise ``ValueError`` — use |
| 53 | + ``basic_auth`` for other identities. |
| 54 | + - ``basic_auth`` — ``(username, password)`` tuple; takes precedence over |
| 55 | + ``role`` when provided. |
| 56 | + - ``api`` — when ``True`` (default), the base URL is suffixed with |
| 57 | + ``++api++`` so relative requests hit the REST API traverser. |
| 58 | +
|
| 59 | + Example usage: |
| 60 | + ```python |
| 61 | + def test_list_content(request_factory): |
| 62 | + session = request_factory(role="Manager") |
| 63 | + response = session.get("/") |
| 64 | + assert response.status_code == 200 |
| 65 | + ``` |
| 66 | + """ |
| 67 | + |
| 68 | + def factory( |
| 69 | + *, |
| 70 | + role: str = "Anonymous", |
| 71 | + basic_auth: tuple[str, str] | None = None, |
| 72 | + api: bool = True, |
| 73 | + ) -> RelativeSession: |
| 74 | + base_url = functional_portal.absolute_url() |
| 75 | + if api: |
| 76 | + base_url = f"{base_url}/++api++" |
| 77 | + session = RelativeSession(base_url) |
| 78 | + session.headers.update({"Accept": "application/json"}) |
| 79 | + if basic_auth is not None: |
| 80 | + session.auth = basic_auth |
| 81 | + elif role in _ROLE_AUTH: |
| 82 | + auth = _ROLE_AUTH[role] |
| 83 | + if auth is not None: |
| 84 | + session.auth = auth |
| 85 | + else: |
| 86 | + raise ValueError( |
| 87 | + f"Unknown role {role!r}. Pass role='Manager' or 'Anonymous', " |
| 88 | + "or use basic_auth=(username, password) for other identities." |
| 89 | + ) |
| 90 | + request.addfinalizer(session.close) |
| 91 | + return session |
| 92 | + |
| 93 | + return factory |
| 94 | + |
| 95 | + |
| 96 | +@pytest.fixture |
| 97 | +def manager_request(request_factory: t.RequestFactory) -> RelativeSession: |
| 98 | + """A `RelativeSession` authenticated as the portal owner (Manager). |
| 99 | +
|
| 100 | + Example usage: |
| 101 | + ```python |
| 102 | + def test_admin_endpoint(manager_request): |
| 103 | + response = manager_request.get("/@controlpanels") |
| 104 | + assert response.status_code == 200 |
| 105 | + ``` |
| 106 | + """ |
| 107 | + return request_factory(role="Manager") |
| 108 | + |
| 109 | + |
| 110 | +@pytest.fixture |
| 111 | +def anon_request(request_factory: t.RequestFactory) -> RelativeSession: |
| 112 | + """A `RelativeSession` with no authentication (Anonymous). |
| 113 | +
|
| 114 | + Example usage: |
| 115 | + ```python |
| 116 | + def test_public_endpoint(anon_request): |
| 117 | + response = anon_request.get("/") |
| 118 | + assert response.status_code == 200 |
| 119 | + ``` |
| 120 | + """ |
| 121 | + return request_factory(role="Anonymous") |
0 commit comments