import json import shlex from pathlib import Path import pytest CONFIG = Path(__file__).resolve().parents[2] / "infra/haproxy/haproxy.cfg" @pytest.mark.parametrize("status", [502, 503, 504]) @pytest.mark.parametrize("request_id", ['a"b', "a\\b", "a\tb", "aÿb", "x" * 200]) def test_error_templates_escape_json_without_changing_header(status: int, request_id: str) -> None: line = next( line.strip() for line in CONFIG.read_text().splitlines() if line.strip().startswith(f"http-error status {status} ") ) tokens = shlex.split(line) header = tokens[tokens.index("hdr") + 1 : tokens.index("lf-string")] assert header == ["X-Request-Id", "%[var(txn.request_id)]"] template = tokens[tokens.index("lf-string") + 1] escaped = json.dumps(request_id, ensure_ascii=True)[1:-1] rendered = template.replace("%[var(txn.request_id),json(ascii)]", escaped) body = json.loads(rendered) assert body["error"]["request_id"] == request_id assert body["error"]["code"] == "unavailable"