61 lines
1.5 KiB
Python
61 lines
1.5 KiB
Python
|
|
import json
|
||
|
|
import os
|
||
|
|
import textwrap
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
import requests as _requests
|
||
|
|
|
||
|
|
BASE_URL = os.environ.get("WP_BASE_URL", "http://localhost/wordpress")
|
||
|
|
|
||
|
|
# Capture every HTTP exchange made during a test so we can print it on failure.
|
||
|
|
_exchanges: list[_requests.Response] = []
|
||
|
|
|
||
|
|
_original_request = _requests.Session.request
|
||
|
|
|
||
|
|
|
||
|
|
def _patched_request(self, method, url, **kwargs):
|
||
|
|
resp = _original_request(self, method, url, **kwargs)
|
||
|
|
_exchanges.append(resp)
|
||
|
|
return resp
|
||
|
|
|
||
|
|
|
||
|
|
_requests.Session.request = _patched_request # type: ignore[method-assign]
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture(scope="session")
|
||
|
|
def base_url():
|
||
|
|
return BASE_URL
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.hookimpl(hookwrapper=True)
|
||
|
|
def pytest_runtest_call(item): # noqa: ARG001
|
||
|
|
_exchanges.clear()
|
||
|
|
yield
|
||
|
|
|
||
|
|
|
||
|
|
def _pretty(raw) -> str:
|
||
|
|
try:
|
||
|
|
return json.dumps(json.loads(raw), indent=2)
|
||
|
|
except Exception:
|
||
|
|
return raw if isinstance(raw, str) else raw.decode(errors="replace")
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.hookimpl(hookwrapper=True)
|
||
|
|
def pytest_runtest_makereport(item, call): # noqa: ARG001
|
||
|
|
outcome = yield
|
||
|
|
report = outcome.get_result()
|
||
|
|
|
||
|
|
if not (report.failed and call.when == "call" and _exchanges):
|
||
|
|
return
|
||
|
|
|
||
|
|
lines = []
|
||
|
|
for i, resp in enumerate(_exchanges, 1):
|
||
|
|
req = resp.request
|
||
|
|
lines.append(f"[{i}] {req.method} {req.url}")
|
||
|
|
if req.body:
|
||
|
|
lines.append(textwrap.indent(_pretty(req.body), " req "))
|
||
|
|
lines.append(f" {resp.status_code}")
|
||
|
|
lines.append(textwrap.indent(_pretty(resp.text), " resp "))
|
||
|
|
|
||
|
|
report.sections.append(("HTTP", "\n".join(lines)))
|