pytest-httpchain 0.15.0__tar.gz → 0.15.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/PKG-INFO +2 -2
  2. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/pyproject.toml +5 -4
  3. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/pyproject.toml.orig +7 -5
  4. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/carrier.py +24 -10
  5. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/cli.py +11 -9
  6. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/constants.py +13 -9
  7. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/dataflow.py +6 -3
  8. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/factory.py +1 -1
  9. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/har_writer.py +25 -32
  10. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/jsonref/plumbing/circular.py +2 -3
  11. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/jsonref/plumbing/path.py +1 -1
  12. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/jsonref/plumbing/reference.py +4 -5
  13. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/models/entities.py +6 -2
  14. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/models/types.py +5 -5
  15. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/plugin.py +76 -37
  16. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/response_steps.py +1 -1
  17. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/schema.py +24 -16
  18. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/templates/substitution.py +2 -2
  19. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/userfunc.py +7 -11
  20. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/utils.py +11 -10
  21. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/validation/deep.py +5 -7
  22. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/validation/loader.py +7 -8
  23. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/validation/semantic.py +1 -1
  24. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/LICENSE +0 -0
  25. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/README.md +0 -0
  26. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/__init__.py +0 -0
  27. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/errors.py +0 -0
  28. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/jsonref/__init__.py +0 -0
  29. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/jsonref/exceptions.py +0 -0
  30. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/jsonref/loader.py +0 -0
  31. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/jsonref/plumbing/__init__.py +0 -0
  32. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/models/__init__.py +0 -0
  33. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/py.typed +0 -0
  34. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/report_formatter.py +0 -0
  35. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/request_builder.py +0 -0
  36. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/scoping.py +0 -0
  37. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/templates/__init__.py +0 -0
  38. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/templates/exceptions.py +0 -0
  39. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/templates/expressions.py +0 -0
  40. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/validation/__init__.py +0 -0
  41. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/validation/diagnostics.py +0 -0
  42. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/validation/validate.py +0 -0
  43. {pytest_httpchain-0.15.0 → pytest_httpchain-0.15.2}/src/pytest_httpchain/warnings.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-httpchain
3
- Version: 0.15.0
3
+ Version: 0.15.2
4
4
  Summary: pytest plugin for HTTP testing using JSON files
5
5
  Keywords: testing,pytest,httpx,http,api,integration-testing
6
6
  Author: Alexander Eresov
@@ -24,7 +24,7 @@ Requires-Dist: pydantic>=2.13.4
24
24
  Requires-Dist: referencing>=0.28.4
25
25
  Requires-Dist: pyrate-limiter>=4.2.0
26
26
  Requires-Dist: pytest>=9.0
27
- Requires-Dist: simpleeval>=1.0.3
27
+ Requires-Dist: simpleeval>=1.0.8
28
28
  Requires-Dist: typer>=0.26.0
29
29
  Requires-Python: >=3.13
30
30
  Project-URL: Repository, https://github.com/aeresov/pytest-httpchain
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytest-httpchain"
3
- version = "0.15.0"
3
+ version = "0.15.2"
4
4
  description = "pytest plugin for HTTP testing using JSON files"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -14,7 +14,7 @@ dependencies = [
14
14
  "referencing>=0.28.4",
15
15
  "pyrate-limiter>=4.2.0",
16
16
  "pytest>=9.0",
17
- "simpleeval>=1.0.3",
17
+ "simpleeval>=1.0.8",
18
18
  "typer>=0.26.0",
19
19
  ]
20
20
  keywords = [
@@ -59,6 +59,7 @@ dev = [
59
59
  "flask-httpauth>=4.8.0",
60
60
  "import-linter>=2.0",
61
61
  "ruff>=0.12.1",
62
+ "ty>=0.0.84",
62
63
  "coverage[toml]>=7.10",
63
64
  "pytest-datadir>=1.7.2",
64
65
  "pytest-order>=1.3.0",
@@ -152,7 +153,7 @@ patch = ["subprocess"]
152
153
  precision = 2
153
154
  show_missing = true
154
155
  skip_covered = false
155
- fail_under = 94
156
+ fail_under = 96
156
157
 
157
158
  [tool.importlinter]
158
159
  root_package = "pytest_httpchain"
@@ -181,5 +182,5 @@ source_modules = ["pytest_httpchain.models"]
181
182
  forbidden_modules = ["pytest_httpchain.jsonref"]
182
183
 
183
184
  [build-system]
184
- requires = ["uv_build>=0.11,<0.12"]
185
+ requires = ["uv_build>=0.12,<0.13"]
185
186
  build-backend = "uv_build"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytest-httpchain"
3
- version = "0.15.0"
3
+ version = "0.15.2"
4
4
  description = "pytest plugin for HTTP testing using JSON files"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -15,7 +15,8 @@ dependencies = [
15
15
  "referencing>=0.28.4",
16
16
  "pyrate-limiter>=4.2.0",
17
17
  "pytest>=9.0",
18
- "simpleeval>=1.0.3",
18
+ # 1.0.8 blocks sandbox escapes through the operator module and os.exec*/spawn*.
19
+ "simpleeval>=1.0.8",
19
20
  # 0.26.0 is the first release that stopped importing the deprecated
20
21
  # `click.utils.get_binary_stream`; with `filterwarnings = error` any older
21
22
  # typer fails collection against current click.
@@ -46,6 +47,7 @@ dev = [
46
47
  "flask-httpauth>=4.8.0",
47
48
  "import-linter>=2.0",
48
49
  "ruff>=0.12.1",
50
+ "ty>=0.0.84",
49
51
  "coverage[toml]>=7.10", # `patch = ["subprocess"]` needs 7.10
50
52
 
51
53
  "pytest-datadir>=1.7.2",
@@ -65,7 +67,7 @@ docs = [
65
67
  default-groups = ["dev", "docs"]
66
68
 
67
69
  [build-system]
68
- requires = ["uv_build>=0.11,<0.12"]
70
+ requires = ["uv_build>=0.12,<0.13"]
69
71
  build-backend = "uv_build"
70
72
 
71
73
  [tool.uv.build-backend]
@@ -171,10 +173,10 @@ precision = 2
171
173
  show_missing = true
172
174
  skip_covered = false
173
175
  # Regression floor for the CI `coverage report` step (full suite under
174
- # `coverage run -m pytest`, ~97%). Kept a few points below the real number to
176
+ # `coverage run -m pytest`, ~98%). Kept a few points below the real number to
175
177
  # tolerate platform/Python-version branch differences; ratchet upward as
176
178
  # coverage improves rather than letting it silently erode.
177
- fail_under = 94
179
+ fail_under = 96
178
180
 
179
181
  [tool.importlinter]
180
182
  root_package = "pytest_httpchain"
@@ -26,7 +26,7 @@ from dataclasses import dataclass
26
26
  from datetime import UTC, datetime
27
27
  from pathlib import Path
28
28
  from types import SimpleNamespace
29
- from typing import Any, ClassVar, cast
29
+ from typing import Any, ClassVar
30
30
 
31
31
  import httpx
32
32
  import pytest
@@ -34,6 +34,7 @@ from pydantic import ValidationError
34
34
  from pyrate_limiter import Duration, Limiter, Rate
35
35
 
36
36
  from pytest_httpchain.errors import RequestError, SaveError, StageExecutionError
37
+ from pytest_httpchain.har_writer import Exchange
37
38
  from pytest_httpchain.models import (
38
39
  CombinationsParameter,
39
40
  IndividualParameter,
@@ -141,6 +142,19 @@ def _parallel_int(field: str, value: Any) -> int:
141
142
  return int(number)
142
143
 
143
144
 
145
+ def _parallel_values(field: str, value: Any) -> list[Any]:
146
+ """A walk()-resolved ``parallel.foreach`` step's values, or a stage failure.
147
+
148
+ Like the numeric fields, both step kinds also accept a template string, so a
149
+ template resolving to another template arrives here as text: iterated, it
150
+ ran one iteration per character (``individual``) or escaped as a bare
151
+ TypeError (``combinations``).
152
+ """
153
+ if not isinstance(value, list):
154
+ raise StageExecutionError(f"parallel.foreach {field} must resolve to a list, got {value!r}")
155
+ return value
156
+
157
+
144
158
  def fresh_scenario_state() -> dict[str, Any]:
145
159
  """The per-scenario mutable class state, in its pristine form.
146
160
 
@@ -186,7 +200,7 @@ class Carrier:
186
200
  aborted: ClassVar[bool] = False
187
201
  last_request: ClassVar[httpx.Request | None] = None
188
202
  last_response: ClassVar[httpx.Response | None] = None
189
- last_exchanges: ClassVar[list[tuple[httpx.Request, httpx.Response | None, datetime | None]]] = []
203
+ last_exchanges: ClassVar[list[Exchange]] = []
190
204
  last_iterations_attempted: ClassVar[int] = 0
191
205
  last_shown_exchange_is_failed: ClassVar[bool] = False
192
206
  record_all_exchanges: ClassVar[bool] = False
@@ -338,7 +352,7 @@ class Carrier:
338
352
  return {name: cls._wrap_factory_fixture(value) if callable(value) and not inspect.isclass(value) else value for name, value in fixture_kwargs.items()}
339
353
 
340
354
  @staticmethod
341
- def _build_iteration_substitutions(parallel_config: "ParallelConfig | None", max_parallel_iterations: int) -> list[dict[str, Any]]:
355
+ def _build_iteration_substitutions(parallel_config: ParallelConfig | None, max_parallel_iterations: int) -> list[dict[str, Any]]:
342
356
  """Expand a resolved parallel config into per-iteration substitutions:
343
357
  no config -> one empty dict; ``repeat`` -> N empties; ``foreach`` -> the
344
358
  cross-product of its steps.
@@ -374,9 +388,9 @@ class Carrier:
374
388
  match step:
375
389
  case IndividualParameter(individual=individual):
376
390
  param_name = next(iter(individual))
377
- steps.append((param_name, individual[param_name]))
391
+ steps.append((param_name, _parallel_values(f"individual '{param_name}'", individual[param_name])))
378
392
  case CombinationsParameter(combinations=combinations):
379
- steps.append((None, cast(list[Any], combinations)))
393
+ steps.append((None, _parallel_values("combinations", combinations)))
380
394
  case _:
381
395
  raise RuntimeError(f"Unhandled foreach step: {type(step).__name__}")
382
396
  check_cap(math.prod(len(values) for _, values in steps))
@@ -391,7 +405,7 @@ class Carrier:
391
405
  return iteration_substitutions
392
406
 
393
407
  @classmethod
394
- def _record_exchanges(cls, completed: list["IterationResult"], failed: Exception | None, attempted: int) -> None:
408
+ def _record_exchanges(cls, completed: list[IterationResult], failed: Exception | None, attempted: int) -> None:
395
409
  """Record this stage's HTTP exchanges for the report and the HAR file.
396
410
 
397
411
  ``last_request``/``last_response`` are the one exchange the report shows:
@@ -402,7 +416,7 @@ class Carrier:
402
416
  """
403
417
  failed_request, failed_response, failed_started = (failed.request, failed.response, failed.started) if isinstance(failed, StageExecutionError) else (None, None, None)
404
418
 
405
- exchanges: list[tuple[httpx.Request, httpx.Response | None, datetime | None]] = []
419
+ exchanges: list[Exchange] = []
406
420
  for r in completed:
407
421
  # A redirect chain lives on .history, each hop carrying its own
408
422
  # request: expand it so the HAR shows every wire exchange. Individual
@@ -424,7 +438,7 @@ class Carrier:
424
438
  cls.last_request, cls.last_response = failed_request, failed_response
425
439
  cls.last_shown_exchange_is_failed = True
426
440
  elif exchanges:
427
- cls.last_request, cls.last_response = exchanges[-1][0], exchanges[-1][1]
441
+ cls.last_request, cls.last_response, _ = exchanges[-1]
428
442
 
429
443
  @classmethod
430
444
  def _run_iterations(
@@ -432,7 +446,7 @@ class Carrier:
432
446
  stage: Stage,
433
447
  local_context: ChainMap[str, Any],
434
448
  iteration_substitutions: list[dict[str, Any]],
435
- parallel_config: "ParallelConfig | None",
449
+ parallel_config: ParallelConfig | None,
436
450
  ) -> tuple[list[IterationResult | None], tuple[int, Exception] | None]:
437
451
  """Run the iterations and return ``(results_by_index, first_error)``.
438
452
 
@@ -684,7 +698,7 @@ class Carrier:
684
698
  try:
685
699
  ctx.__exit__(None, None, None)
686
700
  except Exception as e:
687
- logger.error(f"Error while cleaning up context manager fixture: {e}")
701
+ logger.error("Error while cleaning up context manager fixture: %s", e)
688
702
 
689
703
  if cls.client is not None:
690
704
  cls.client.close()
@@ -1,6 +1,9 @@
1
- import enum
1
+ """The ``pytest-httpchain`` command line: ``validate``, ``schema``, ``resolve``,
2
+ ``show`` and ``graph`` over scenario files, outside a pytest run."""
3
+
2
4
  import importlib.metadata
3
5
  import json
6
+ from enum import StrEnum
4
7
  from pathlib import Path
5
8
  from typing import Annotated
6
9
 
@@ -16,12 +19,12 @@ from pytest_httpchain.validation import ValidateResult, is_inline_schema_positio
16
19
  app = typer.Typer(no_args_is_help=True)
17
20
 
18
21
 
19
- class OutputFormat(enum.StrEnum):
22
+ class OutputFormat(StrEnum):
20
23
  text = "text"
21
24
  json = "json"
22
25
 
23
26
 
24
- class GraphDirection(enum.StrEnum):
27
+ class GraphDirection(StrEnum):
25
28
  TD = "TD"
26
29
  LR = "LR"
27
30
 
@@ -170,12 +173,11 @@ def _render_show_text(path: Path, scenario: Scenario, flow: DataFlow) -> list[st
170
173
  if s.consumes:
171
174
  parts: list[str] = []
172
175
  for var_name in s.consumes:
173
- producer = producer_of.get((s.index, var_name))
174
- if producer is None:
175
- parts.append(var_name)
176
- else:
177
- producer_name = flow.stages[producer].name or f"stage {producer + 1}"
178
- parts.append(f"{var_name} (from #{producer + 1} {producer_name})")
176
+ # analyze_dataflow lists a consume only when an earlier stage
177
+ # saved the name, so every one has a producing edge.
178
+ producer = producer_of[(s.index, var_name)]
179
+ producer_name = flow.stages[producer].name or f"stage {producer + 1}"
180
+ parts.append(f"{var_name} (from #{producer + 1} {producer_name})")
179
181
  lines.append(f" consumes: {', '.join(parts)}")
180
182
  if s.marks:
181
183
  lines.append(f" marks: {', '.join(s.marks)}")
@@ -6,24 +6,28 @@ from enum import StrEnum
6
6
  # "module.path:function_name": a required dotted module path (no leading,
7
7
  # trailing or doubled dots) and a single identifier. Shared by the models'
8
8
  # validator and the importer, so a bare name fails at validation, not at import.
9
- USER_FUNCTION_NAME_PATTERN = re.compile(r"^(?P<module>[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*):(?P<function>[a-zA-Z_][a-zA-Z0-9_]*)$")
9
+ # Anchored with \A and \Z, not ^ and $: "$" also matches just before a trailing
10
+ # "\n", so match() against "^...$" accepted "mod:func\n". The pattern is exported
11
+ # as userfunc.NAME_PATTERN, so match() has to be as strict as fullmatch() here.
12
+ USER_FUNCTION_NAME_PATTERN = re.compile(r"\A(?P<module>[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*):(?P<function>[a-zA-Z_][a-zA-Z0-9_]*)\Z")
10
13
 
11
14
  _BARE_NAME_PATTERN = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")
12
15
 
13
16
 
14
- def user_function_name_problem(name: str) -> str | None:
15
- """Why ``name`` is not a usable ``module.path:function_name``, or None.
17
+ def parse_user_function_name(name: str) -> tuple[str, str]:
18
+ """Split ``module.path:function_name`` into ``(module_path, function_name)``,
19
+ raising ``ValueError`` that says what is wrong with an unusable name.
16
20
 
17
- The wording is shared, not just the grammar: the models' validator raises it
18
- as a ``ValueError`` and the importer as a ``UserFunctionError``, and one
21
+ The wording is shared, not just the grammar: the models' validator surfaces
22
+ it as a validation error and the importer as a ``UserFunctionError``, and one
19
23
  mistake must not be described to the author in two different ways.
20
24
  """
21
- if USER_FUNCTION_NAME_PATTERN.match(name):
22
- return None
25
+ if match := USER_FUNCTION_NAME_PATTERN.fullmatch(name):
26
+ return match["module"], match["function"]
23
27
  # The most common mistake deserves an actionable hint.
24
28
  if _BARE_NAME_PATTERN.fullmatch(name):
25
- return f"Module path is required: use 'module:{name}' format instead of '{name}'"
26
- return f"Invalid function name format: {name}"
29
+ raise ValueError(f"Module path is required: use 'module:{name}' format instead of '{name}'")
30
+ raise ValueError(f"Invalid function name format: {name}")
27
31
 
28
32
 
29
33
  class ConfigOptions(StrEnum):
@@ -127,6 +127,9 @@ def analyze_dataflow(scenario: Scenario, test_data: dict[str, Any]) -> DataFlow:
127
127
  for name in scope.saves:
128
128
  last_save_stage[name] = i
129
129
 
130
- scenario_var_names = set(substitution_names(scenario.substitutions))
131
-
132
- return DataFlow(stages=stages, edges=edges, scenario_fixtures=sorted(scenario.fixtures), scenario_vars=sorted(scenario_var_names))
130
+ return DataFlow(
131
+ stages=stages,
132
+ edges=edges,
133
+ scenario_fixtures=sorted(scenario.fixtures),
134
+ scenario_vars=sorted(substitution_names(scenario.substitutions)),
135
+ )
@@ -115,7 +115,7 @@ def create_test_class(
115
115
  all_param_names.extend(param_names)
116
116
  stage_method = pytest.mark.parametrize(",".join(param_names), param_values, ids=step.ids or None)(stage_method)
117
117
 
118
- all_fixtures = ["self"] + list(dict.fromkeys(all_param_names + stage.fixtures + scenario.fixtures))
118
+ all_fixtures = ["self", *dict.fromkeys(all_param_names + stage.fixtures + scenario.fixtures)]
119
119
  stage_method.__signature__ = inspect.Signature([inspect.Parameter(name, inspect.Parameter.POSITIONAL_OR_KEYWORD) for name in all_fixtures]) # ty: ignore[unresolved-attribute]
120
120
 
121
121
  # Read by the chain-contiguity hook to restore stage order.
@@ -15,6 +15,10 @@ import httpx
15
15
 
16
16
  from pytest_httpchain.utils import request_content
17
17
 
18
+ # One wire exchange: the request, its response (None when none arrived), and when
19
+ # it went on the wire (None falls back to HAR write time).
20
+ type Exchange = tuple[httpx.Request, httpx.Response | None, datetime | None]
21
+
18
22
 
19
23
  @functools.cache
20
24
  def _get_version() -> str:
@@ -69,53 +73,42 @@ def _format_query_string(url: httpx.URL) -> list[dict[str, str]]:
69
73
  return [{"name": name, "value": value} for name, values in params.items() for value in values]
70
74
 
71
75
 
76
+ def _mime_type(content_type: str) -> str:
77
+ return content_type.split(";")[0].strip() if content_type else "application/octet-stream"
78
+
79
+
80
+ def _body_text(content: bytes) -> dict[str, str]:
81
+ """HAR ``text`` for a body: UTF-8 as is, anything else base64 with ``encoding`` set."""
82
+ try:
83
+ return {"text": content.decode("utf-8")}
84
+ except UnicodeDecodeError:
85
+ return {"text": base64.b64encode(content).decode("ascii"), "encoding": "base64"}
86
+
87
+
72
88
  def _format_post_data(request: httpx.Request) -> dict[str, Any] | None:
73
89
  content = request_content(request)
74
90
  if not content:
75
91
  return None
76
92
 
77
93
  content_type = request.headers.get("content-type", "")
78
- mime_type = content_type.split(";")[0].strip() if content_type else "application/octet-stream"
79
-
80
- try:
81
- text = content.decode("utf-8")
82
- except UnicodeDecodeError:
83
- text = base64.b64encode(content).decode("ascii")
84
- return {
85
- "mimeType": mime_type,
86
- "text": text,
87
- "encoding": "base64",
88
- }
89
-
90
- post_data: dict[str, Any] = {
91
- "mimeType": mime_type,
92
- "text": text,
93
- }
94
+ body_text = _body_text(content)
95
+ post_data: dict[str, Any] = {"mimeType": _mime_type(content_type), **body_text}
94
96
 
95
- if "application/x-www-form-urlencoded" in content_type:
97
+ if "application/x-www-form-urlencoded" in content_type and "encoding" not in body_text:
96
98
  # HAR params are repeated scalar name/value records, not one record with
97
99
  # an array value. parse_qsl also preserves the body's original ordering.
98
- post_data["params"] = [{"name": name, "value": value} for name, value in parse_qsl(text, keep_blank_values=True)]
100
+ post_data["params"] = [{"name": name, "value": value} for name, value in parse_qsl(body_text["text"], keep_blank_values=True)]
99
101
 
100
102
  return post_data
101
103
 
102
104
 
103
105
  def _format_response_content(response: httpx.Response) -> dict[str, Any]:
104
- content_type = response.headers.get("content-type", "")
105
- mime_type = content_type.split(";")[0].strip() if content_type else "application/octet-stream"
106
-
107
106
  content: dict[str, Any] = {
108
- "size": len(response.content) if response.content else 0,
109
- "mimeType": mime_type,
107
+ "size": len(response.content),
108
+ "mimeType": _mime_type(response.headers.get("content-type", "")),
110
109
  }
111
-
112
110
  if response.content:
113
- try:
114
- content["text"] = response.content.decode("utf-8")
115
- except UnicodeDecodeError:
116
- content["text"] = base64.b64encode(response.content).decode("ascii")
117
- content["encoding"] = "base64"
118
-
111
+ content |= _body_text(response.content)
119
112
  return content
120
113
 
121
114
 
@@ -163,7 +156,7 @@ def request_response_to_har_entry(
163
156
  "content": _format_response_content(response),
164
157
  "redirectURL": response.headers.get("location", ""),
165
158
  "headersSize": _calculate_headers_size(response.headers),
166
- "bodySize": len(response.content) if response.content else 0,
159
+ "bodySize": len(response.content),
167
160
  }
168
161
  else:
169
162
  response_har = {
@@ -258,7 +251,7 @@ def _har_filename(test_name: str) -> str:
258
251
  def write_har_file(
259
252
  output_dir: Path,
260
253
  test_name: str,
261
- exchanges: list[tuple[httpx.Request, httpx.Response | None, datetime | None]],
254
+ exchanges: list[Exchange],
262
255
  ) -> Path:
263
256
  """Write one test's exchanges to a HAR file and return its path.
264
257
 
@@ -9,7 +9,7 @@ from pytest_httpchain.jsonref.exceptions import ReferenceResolverError
9
9
  class CircularDependencyTracker:
10
10
  """Tracks references to detect circular dependencies."""
11
11
 
12
- def __init__(self):
12
+ def __init__(self) -> None:
13
13
  self.external_refs: set[tuple[Path, str]] = set()
14
14
  self.internal_refs: set[str] = set()
15
15
 
@@ -41,7 +41,6 @@ class CircularDependencyTracker:
41
41
  own document, and inheriting them would raise a phantom cycle for two
42
42
  documents that merely reuse a pointer string.
43
43
  """
44
- child = self.__class__()
44
+ child = type(self)()
45
45
  child.external_refs = self.external_refs.copy()
46
- child.internal_refs = set()
47
46
  return child
@@ -19,7 +19,7 @@ def validate_ref_path(ref_path: str, base_path: Path, root_path: Path, max_paren
19
19
  if PurePosixPath(ref_path).is_absolute() or PureWindowsPath(ref_path).is_absolute() or ref_path.startswith(("/", "\\")):
20
20
  raise ReferenceResolverError(f"Absolute reference paths are not allowed: {ref_path}")
21
21
 
22
- parent_traversals = sum(1 for part in Path(ref_path).parts if part == "..")
22
+ parent_traversals = Path(ref_path).parts.count("..")
23
23
 
24
24
  if parent_traversals > max_parent_traversal_depth:
25
25
  raise ReferenceResolverError(f"Reference path '{ref_path}' exceeds maximum parent traversal depth of {max_parent_traversal_depth}")
@@ -44,7 +44,7 @@ _SIBLING_MERGER = Merger(
44
44
  )
45
45
 
46
46
 
47
- def _build_opaque_aware_merger(opaque: "OpaquePredicate", base_path: tuple[str | int, ...]) -> Merger:
47
+ def _build_opaque_aware_merger(opaque: OpaquePredicate, base_path: tuple[str | int, ...]) -> Merger:
48
48
  """Sibling merger treating opaque positions as atomic: two opaque subtrees
49
49
  must be equal or conflict, never blend.
50
50
 
@@ -133,8 +133,8 @@ class ReferenceResolver:
133
133
  if self.opaque is not None and self.opaque(doc_path):
134
134
  return data
135
135
  match data:
136
- case dict() if self._get_ref_key(data):
137
- return self._resolve_single_ref(data, current_path, root_data, root_path, doc_path)
136
+ case dict() if (ref_key := self._get_ref_key(data)) is not None:
137
+ return self._resolve_single_ref(data, ref_key, current_path, root_data, root_path, doc_path)
138
138
  case dict():
139
139
  return {key: self._resolve_refs(value, current_path, root_data, root_path, doc_path + (key,)) for key, value in data.items()}
140
140
  case list():
@@ -152,13 +152,12 @@ class ReferenceResolver:
152
152
  def _resolve_single_ref(
153
153
  self,
154
154
  data: dict[str, Any],
155
+ ref_key: str,
155
156
  current_path: Path,
156
157
  root_data: Any,
157
158
  root_path: Path,
158
159
  doc_path: tuple[str | int, ...],
159
160
  ) -> Any:
160
- ref_key = self._get_ref_key(data)
161
- assert ref_key is not None
162
161
  ref_value = data[ref_key]
163
162
  if not isinstance(ref_value, str):
164
163
  raise ReferenceResolverError(f"{ref_key} value must be a string, got {type(ref_value).__name__}: {ref_value!r}")
@@ -59,7 +59,7 @@ def _create_discriminator(class_to_tag: dict[type, str]) -> Callable[[Any], str]
59
59
  return min(found)
60
60
 
61
61
  # Name the offending key, so the validation error points at it.
62
- return next(iter(v), "(empty object)") # ty: ignore[invalid-return-type]
62
+ return next(iter(v), "(empty object)")
63
63
 
64
64
  tag = class_to_tag.get(type(v))
65
65
  if tag:
@@ -115,7 +115,11 @@ def _normalize_stages_input(v: Any) -> Any:
115
115
  if isinstance(v, dict):
116
116
  result = []
117
117
  for name, stage_data in v.items():
118
- result.append({**stage_data, "name": name} if isinstance(stage_data, dict) else stage_data)
118
+ if isinstance(stage_data, dict):
119
+ stage_data = {**stage_data, "name": name}
120
+ elif isinstance(stage_data, Stage):
121
+ stage_data = stage_data.model_copy(update={"name": name})
122
+ result.append(stage_data)
119
123
  return result
120
124
 
121
125
  return v
@@ -17,7 +17,7 @@ import jmespath
17
17
  import jsonschema
18
18
  from pydantic import AfterValidator, BeforeValidator, Field, JsonValue, PlainSerializer, WithJsonSchema
19
19
 
20
- from pytest_httpchain.constants import user_function_name_problem
20
+ from pytest_httpchain.constants import parse_user_function_name
21
21
  from pytest_httpchain.templates import TEMPLATE_PATTERN, TEMPLATE_PATTERN_ECMA, is_complete_template
22
22
 
23
23
 
@@ -103,8 +103,7 @@ def validate_partial_template_str(v: str) -> str:
103
103
  def validate_function_import_name(v: str) -> str:
104
104
  """Validate a ``module.path:function_name`` against the grammar the importer
105
105
  accepts, so a bare name fails here rather than at runtime import."""
106
- if (problem := user_function_name_problem(v)) is not None:
107
- raise ValueError(problem)
106
+ parse_user_function_name(v)
108
107
  return v
109
108
 
110
109
 
@@ -173,8 +172,9 @@ NumberOrTemplate = Annotated[
173
172
  WithJsonSchema({"type": "string", "pattern": _NUMBER_OR_TEMPLATE_PATTERN}),
174
173
  ]
175
174
 
176
- # Any RFC 9110 token is a legal method (PROPFIND, PURGE, vendor verbs). Sits
177
- # after the ``HTTPMethod`` branch so common verbs still normalize to the enum.
175
+ # Any RFC 9110 token is a legal method (PROPFIND, PURGE, vendor verbs). The
176
+ # ``HTTPMethod`` branch before it only feeds the JSON Schema's verb autocompletion:
177
+ # the smart union keeps a str input a plain str (only the default is the enum).
178
178
  _HTTP_METHOD_TOKEN_PATTERN = r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$"
179
179
 
180
180
 
@@ -11,7 +11,7 @@ import re
11
11
  import sys
12
12
  import types
13
13
  import warnings
14
- from collections.abc import Iterable
14
+ from collections.abc import Callable, Iterable
15
15
  from pathlib import Path
16
16
  from typing import Any, Literal
17
17
 
@@ -135,10 +135,23 @@ class JsonModule(pytest.Module):
135
135
 
136
136
 
137
137
  # Collection order, recorded before any sorter runs: the regroup tiebreaker.
138
- _ORIGINAL_POSITIONS: pytest.StashKey[dict[pytest.Item, int]] = pytest.StashKey()
138
+ # Keyed by id(item), not the item: up to pytest 9.1 an item hashes its `_nodeid`,
139
+ # which an xdist loadgroup worker rewrites between recording and lookup.
140
+ _ORIGINAL_POSITIONS: pytest.StashKey[dict[int, int]] = pytest.StashKey()
139
141
 
140
142
 
141
- def _regroup_carrier_items(items: list[pytest.Item], original_position: dict[pytest.Item, int]) -> None:
143
+ def _carrier_class(item: pytest.Item) -> type[Carrier] | None:
144
+ """The generated scenario class ``item`` belongs to, or None for any other test."""
145
+ cls = getattr(item, "cls", None)
146
+ return cls if isinstance(cls, type) and issubclass(cls, Carrier) else None
147
+
148
+
149
+ def _stage_index(item: pytest.Item) -> int:
150
+ """The stage position `factory.create_test_class` stamped on the item's method."""
151
+ return getattr(getattr(item, "function", None), "_httpchain_stage_index", 0)
152
+
153
+
154
+ def _regroup_carrier_items(items: list[pytest.Item], original_position: dict[int, int]) -> None:
142
155
  """Re-sort collected items so each scenario class's stages run contiguously,
143
156
  in stage order.
144
157
 
@@ -147,28 +160,27 @@ def _regroup_carrier_items(items: list[pytest.Item], original_position: dict[pyt
147
160
  (a user-installed pytest-order acting on user-authored ``order(...)`` marks,
148
161
  pytest-randomly's shuffle, core's ``--ff``). Each class is pulled together
149
162
  at its first item (preserving inter-class order), with ``original_position``
150
- breaking ties so parametrized instances of a stage keep collection order.
163
+ (keyed by ``id(item)``) breaking ties so parametrized instances of a stage
164
+ keep collection order.
151
165
  """
152
- buckets: dict[type, list[pytest.Item]] = {}
166
+ buckets: dict[type[Carrier], list[pytest.Item]] = {}
153
167
  for item in items:
154
- cls = getattr(item, "cls", None)
155
- if cls is not None and issubclass(cls, Carrier):
168
+ if (cls := _carrier_class(item)) is not None:
156
169
  buckets.setdefault(cls, []).append(item)
157
170
  if not buckets:
158
171
  return
159
172
 
160
173
  def stage_key(item: pytest.Item) -> tuple[int, int]:
161
- index = getattr(getattr(item, "function", None), "_httpchain_stage_index", 0)
162
- return (index, original_position.get(item, sys.maxsize))
174
+ return (_stage_index(item), original_position.get(id(item), sys.maxsize))
163
175
 
164
176
  for bucket in buckets.values():
165
177
  bucket.sort(key=stage_key)
166
178
 
167
179
  regrouped: list[pytest.Item] = []
168
- emitted: set[type] = set()
180
+ emitted: set[type[Carrier]] = set()
169
181
  for item in items:
170
- cls = getattr(item, "cls", None)
171
- if cls is None or cls not in buckets:
182
+ cls = _carrier_class(item)
183
+ if cls is None:
172
184
  regrouped.append(item)
173
185
  elif cls not in emitted:
174
186
  emitted.add(cls)
@@ -176,6 +188,34 @@ def _regroup_carrier_items(items: list[pytest.Item], original_position: dict[pyt
176
188
  items[:] = regrouped
177
189
 
178
190
 
191
+ def _apply_xdist_group_nodeids(items: list[pytest.Item]) -> None:
192
+ """Make the ``@<group>`` suffix xdist writes into a scenario item's nodeid
193
+ actually reach the nodeid, so ``--dist loadgroup`` keeps a chain on one worker.
194
+
195
+ An xdist worker encodes each item's ``xdist_group`` by assigning the private
196
+ ``item._nodeid``, and the controller's loadgroup scheduler groups by the
197
+ text after ``@``. Up to pytest 9.1 ``_nodeid`` backs ``nodeid``. From pytest
198
+ 9.2 (pytest-dev/pytest#14758) ``nodeid`` is derived from a structured
199
+ ``item._id`` instead, so the assignment only adds an unused attribute: the
200
+ suffix is lost, every stage becomes its own work unit, and a scenario's stages
201
+ scatter across workers. This carries the id xdist wrote over to ``_id``.
202
+ Where ``_nodeid`` still backs ``nodeid``, or xdist wrote nothing (another dist
203
+ mode, no group), there is no mismatch and nothing changes.
204
+ """
205
+ for item in items:
206
+ if _carrier_class(item) is None:
207
+ continue
208
+ # From 9.2 `_nodeid` is not a slot, so xdist's write lands in __dict__.
209
+ written = item.__dict__.get("_nodeid")
210
+ node_id = getattr(item, "_id", None)
211
+ if written is None or node_id is None or written == item.nodeid:
212
+ continue
213
+ # parse() caches the exact string, so nodeid reads back verbatim. setattr
214
+ # because `_id` exists only from 9.2: a plain assignment fails the type
215
+ # check on older pytest, and a `ty: ignore` goes unused on newer.
216
+ setattr(item, "_id", type(node_id).parse(written)) # noqa: B010
217
+
218
+
179
219
  @pytest.hookimpl(wrapper=True)
180
220
  def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> Any:
181
221
  """Enforce chain contiguity after the non-wrapper sorters have run.
@@ -183,10 +223,12 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item
183
223
  Pre-yield the items are still in collection order, which is recorded as the
184
224
  tiebreaker; post-yield runs after pytest-order, pytest-randomly and friends.
185
225
  Sorters written as tryfirst wrappers finish even later — `pytest_collection_finish`
186
- catches those.
226
+ catches those. Post-yield is also after an xdist worker has written its
227
+ loadgroup nodeid suffix, which `_apply_xdist_group_nodeids` needs.
187
228
  """
188
- config.stash[_ORIGINAL_POSITIONS] = {item: i for i, item in enumerate(items)}
229
+ config.stash[_ORIGINAL_POSITIONS] = {id(item): i for i, item in enumerate(items)}
189
230
  result = yield
231
+ _apply_xdist_group_nodeids(items)
190
232
  _regroup_carrier_items(items, config.stash[_ORIGINAL_POSITIONS])
191
233
  return result
192
234
 
@@ -202,10 +244,8 @@ def _warn_on_split_chains(items: list[pytest.Item]) -> None:
202
244
  """
203
245
  selected_indices: dict[type[Carrier], set[int]] = {}
204
246
  for item in items:
205
- cls = getattr(item, "cls", None)
206
- if cls is not None and issubclass(cls, Carrier):
207
- index = getattr(getattr(item, "function", None), "_httpchain_stage_index", 0)
208
- selected_indices.setdefault(cls, set()).add(index)
247
+ if (cls := _carrier_class(item)) is not None:
248
+ selected_indices.setdefault(cls, set()).add(_stage_index(item))
209
249
 
210
250
  for cls, indices in selected_indices.items():
211
251
  scenario = cls.scenario
@@ -292,7 +332,7 @@ def pytest_configure(config: pytest.Config) -> None:
292
332
  return value
293
333
 
294
334
  suffix = str(config.getini(ConfigOptions.SUFFIX))
295
- if not re.match(r"^[a-zA-Z0-9_-]{1,32}$", suffix):
335
+ if not re.fullmatch(r"[a-zA-Z0-9_-]{1,32}", suffix):
296
336
  raise pytest.UsageError(f"{ConfigOptions.SUFFIX} must contain only alphanumeric characters, underscores, hyphens, and be ≤32 chars")
297
337
 
298
338
  _getint(ConfigOptions.REF_PARENT_TRAVERSAL_DEPTH, minimum=0, minimum_message="must be non-negative")
@@ -311,10 +351,8 @@ def pytest_unconfigure(config: pytest.Config) -> None:
311
351
 
312
352
  def pytest_collect_file(file_path: Path, parent: pytest.Collector) -> pytest.Collector | None:
313
353
  suffix: str = parent.config.getini(ConfigOptions.SUFFIX)
314
- pattern = re.compile(rf"^test_(?P<name>.+)\.{re.escape(suffix)}\.json$")
315
- file_match = pattern.match(file_path.name)
316
- if file_match:
317
- return JsonModule.from_parent(parent, path=file_path, name=file_match.group("name"))
354
+ if file_match := re.fullmatch(rf"test_(?P<name>.+)\.{re.escape(suffix)}\.json", file_path.name):
355
+ return JsonModule.from_parent(parent, path=file_path, name=file_match["name"])
318
356
  return None
319
357
 
320
358
 
@@ -335,14 +373,22 @@ def _sections_will_be_shown(config: pytest.Config, report: pytest.TestReport) ->
335
373
  return terminal_reporter.hasopt("P") or bool(config.option.xfail_tb)
336
374
 
337
375
 
376
+ def _format_section[T](what: str, formatter: Callable[[T], str], exchange: T) -> str:
377
+ """A report section body. Reporting must never break the report, so a
378
+ formatter failure becomes the section's text."""
379
+ try:
380
+ return formatter(exchange)
381
+ except Exception as e:
382
+ return f"<Error formatting {what}: {e}>"
383
+
384
+
338
385
  @pytest.hookimpl(wrapper=True, tryfirst=True)
339
386
  def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo[Any]) -> Any:
340
387
  # tryfirst makes this the outermost wrapper: its post-yield half sees the
341
388
  # final outcome after pytest has applied skip/xfail/strict semantics.
342
389
  report: pytest.TestReport = yield
343
390
 
344
- item_cls = getattr(item, "cls", None)
345
- carrier_class = item_cls if isinstance(item_cls, type) and issubclass(item_cls, Carrier) else None
391
+ carrier_class = _carrier_class(item)
346
392
 
347
393
  if call.when == "call" and carrier_class is not None:
348
394
  # An initialization failure breaks the whole scenario and must stay
@@ -375,17 +421,10 @@ def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo[Any]) ->
375
421
  suffix += f" (after {hops} redirect{'s' if hops != 1 else ''})"
376
422
 
377
423
  if _sections_will_be_shown(item.config, report):
378
- for title, what, exchange, formatter in (
379
- ("HTTP Request", "request", carrier_class.last_request, format_request),
380
- ("HTTP Response", "response", carrier_class.last_response, format_response),
381
- ):
382
- if exchange is None:
383
- continue
384
- try:
385
- body = formatter(exchange)
386
- except Exception as e:
387
- body = f"<Error formatting {what}: {e}>"
388
- report.sections.append((f"{title}{suffix}", body))
424
+ if (request := carrier_class.last_request) is not None:
425
+ report.sections.append((f"HTTP Request{suffix}", _format_section("request", format_request, request)))
426
+ if (response := carrier_class.last_response) is not None:
427
+ report.sections.append((f"HTTP Response{suffix}", _format_section("response", format_response, response)))
389
428
 
390
429
  output_dir = item.config.getoption("httpchain_output_dir")
391
430
  if output_dir and carrier_class.last_exchanges:
@@ -397,7 +436,7 @@ def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo[Any]) ->
397
436
  )
398
437
  report.sections.append(("HAR File", str(har_path)))
399
438
  except Exception as e:
400
- logger.warning(f"Failed to write HAR file for {item.nodeid}: {e}")
439
+ logger.warning("Failed to write HAR file for %s: %s", item.nodeid, e)
401
440
 
402
441
  # The report, not the stage body, is the source of truth. Fixture setup and
403
442
  # teardown can fail without execute_stage running, and strict XPASS plus
@@ -65,7 +65,7 @@ def process_save(save_model: Save, response: httpx.Response, context: ChainMap[s
65
65
 
66
66
  if not isinstance(func_result, dict):
67
67
  raise SaveError(f"Save function must return dict, got {type(func_result).__name__}")
68
- step_saved.update(func_result) # ty: ignore[no-matching-overload]
68
+ step_saved.update(func_result)
69
69
 
70
70
  case _:
71
71
  raise RuntimeError(f"Unhandled save type: {type(save_model).__name__}")
@@ -44,17 +44,24 @@ def _widen_with_jsonref(subschema: dict[str, Any], default_title: str | None = N
44
44
  return wrapper
45
45
 
46
46
 
47
+ def _accepts_jsonref(subschema: dict[str, Any]) -> bool:
48
+ """Whether a subschema already admits a reference object: every named type
49
+ is widened, so a `$ref` to one — alone or as an `anyOf` branch — does."""
50
+ return any("$ref" in branch for branch in (subschema, *subschema.get("anyOf", [])))
51
+
52
+
47
53
  def _add_jsonref_support(schema: dict[str, Any]) -> dict[str, Any]:
48
- """Accept reference objects at named-type and root-property sites.
54
+ """Accept reference objects at named-type, model-field and root-property sites.
49
55
 
50
56
  The resolver can substitute any element, but wrapping every inline subschema
51
- would balloon the output, so anonymous nested schemas are left untouched: a
52
- reference still resolves there at runtime, it is just not described.
57
+ would balloon the output, so schemas nested below a field (array items,
58
+ mapping values) are left untouched: a reference still resolves there at
59
+ runtime, it is just not described.
53
60
  """
54
- if "$defs" not in schema:
55
- schema["$defs"] = {}
61
+ defs = schema.setdefault("$defs", {})
62
+ properties = schema.setdefault("properties", {})
56
63
 
57
- schema["$defs"]["JsonRef"] = {
64
+ defs["JsonRef"] = {
58
65
  "type": "object",
59
66
  "description": "Reference to external JSON file or JSON pointer. Use $include or $merge (preferred) or $ref. Resolved when the scenario file is loaded.",
60
67
  "properties": {
@@ -81,23 +88,24 @@ def _add_jsonref_support(schema: dict[str, Any]) -> dict[str, Any]:
81
88
  "additionalProperties": True,
82
89
  }
83
90
 
84
- for type_name, original_def in list(schema["$defs"].items()):
85
- if type_name == "JsonRef":
86
- continue
87
- schema["$defs"][type_name] = _widen_with_jsonref(original_def)
91
+ for type_name, original_def in defs.items():
92
+ if type_name != "JsonRef":
93
+ fields = original_def.get("properties", {})
94
+ for field_name, field_def in fields.items():
95
+ if not _accepts_jsonref(field_def):
96
+ fields[field_name] = _widen_with_jsonref(field_def)
97
+ defs[type_name] = _widen_with_jsonref(original_def)
88
98
 
89
- for prop_name, prop_def in list(schema.get("properties", {}).items()):
90
- schema["properties"][prop_name] = _widen_with_jsonref(prop_def, default_title=prop_name)
99
+ for prop_name, prop_def in properties.items():
100
+ properties[prop_name] = _widen_with_jsonref(prop_def, default_title=prop_name)
91
101
 
92
102
  # The root forbids extra keys, so keys handled before model validation must
93
103
  # be declared: "$schema" and the directives the loader resolves.
94
- schema.setdefault("properties", {})
95
- schema["properties"]["$schema"] = {
104
+ properties["$schema"] = {
96
105
  "type": "string",
97
106
  "description": "URL of this schema, for editor as-you-type validation. Dropped during model validation.",
98
107
  }
99
- for directive, directive_def in schema["$defs"]["JsonRef"]["properties"].items():
100
- schema["properties"][directive] = directive_def
108
+ properties.update(defs["JsonRef"]["properties"])
101
109
 
102
110
  return schema
103
111
 
@@ -64,7 +64,7 @@ JSON_LITERALS = {
64
64
 
65
65
  # Names an expression gets for free. The validator reads this to tell an
66
66
  # undefined variable from an engine-provided name.
67
- TEMPLATE_BUILTINS = set(SAFE_FUNCTIONS) | set(JSON_LITERALS) | {"exists", "get"} | set(DEFAULT_FUNCTIONS)
67
+ TEMPLATE_BUILTINS = frozenset({*SAFE_FUNCTIONS, *JSON_LITERALS, "exists", "get", *DEFAULT_FUNCTIONS})
68
68
 
69
69
 
70
70
  def _build_evaluator(context: Mapping[str, Any]) -> EvalWithCompoundTypes:
@@ -178,7 +178,7 @@ def _walk(obj: Any, evaluator: EvalWithCompoundTypes) -> Any:
178
178
 
179
179
  obj_dict = obj.model_dump(mode="python")
180
180
  processed_dict = _walk(obj_dict, evaluator)
181
- return obj.__class__.model_validate(processed_dict)
181
+ return type(obj).model_validate(processed_dict)
182
182
  case SimpleNamespace():
183
183
  if not contains_template(obj):
184
184
  return obj
@@ -9,7 +9,7 @@ import importlib
9
9
  from collections.abc import Callable
10
10
  from typing import Any
11
11
 
12
- from pytest_httpchain.constants import USER_FUNCTION_NAME_PATTERN, user_function_name_problem
12
+ from pytest_httpchain.constants import USER_FUNCTION_NAME_PATTERN, parse_user_function_name
13
13
  from pytest_httpchain.errors import HttpChainError
14
14
  from pytest_httpchain.models import UserFunctionCall, UserFunctionKwargs, UserFunctionName
15
15
 
@@ -18,21 +18,17 @@ class UserFunctionError(HttpChainError):
18
18
  """Error importing or calling a user-supplied function."""
19
19
 
20
20
 
21
- # Shared with the models' validator; lives in constants so neither module has to
22
- # sit below the other.
21
+ # Re-exported: the grammar lives in constants, shared with the models' validator,
22
+ # so neither module has to sit below the other.
23
23
  NAME_PATTERN = USER_FUNCTION_NAME_PATTERN
24
24
 
25
25
 
26
26
  def import_function(name: str) -> Callable[..., Any]:
27
27
  """Import a ``"module.path:function_name"`` function."""
28
- if (problem := user_function_name_problem(name)) is not None:
29
- raise UserFunctionError(problem)
30
-
31
- match = NAME_PATTERN.match(name)
32
- assert match is not None, "user_function_name_problem() returns None only for names NAME_PATTERN matches"
33
-
34
- module_path = match.group("module")
35
- function_name = match.group("function")
28
+ try:
29
+ module_path, function_name = parse_user_function_name(name)
30
+ except ValueError as e:
31
+ raise UserFunctionError(str(e)) from None
36
32
 
37
33
  try:
38
34
  module = importlib.import_module(module_path)
@@ -17,9 +17,9 @@ import httpx
17
17
  import pytest
18
18
 
19
19
  from pytest_httpchain.errors import SchemaFileError, StageExecutionError
20
- from pytest_httpchain.models import FunctionsSubstitution, Substitution, UserFunctionKwargs, UserFunctionName, VarsSubstitution
20
+ from pytest_httpchain.models import FunctionsSubstitution, Substitution, VarsSubstitution
21
21
  from pytest_httpchain.templates import walk
22
- from pytest_httpchain.userfunc import wrap_function
22
+ from pytest_httpchain.userfunc import call_target, wrap_function
23
23
 
24
24
  logger = logging.getLogger(__name__)
25
25
 
@@ -79,7 +79,13 @@ def make_marker(mark_str: str) -> pytest.MarkDecorator:
79
79
 
80
80
  if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
81
81
  args = [ast.literal_eval(a) for a in node.args]
82
- kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in node.keywords if kw.arg is not None}
82
+ kwargs: dict[str, Any] = {}
83
+ for kw in node.keywords:
84
+ # literal_eval already rejects a `*args` node; a `**kwargs` entry
85
+ # (arg None) must fail too rather than silently drop its keys.
86
+ if kw.arg is None:
87
+ raise ValueError(f"unsupported marker expression: {mark_str} (** unpacking)")
88
+ kwargs[kw.arg] = ast.literal_eval(kw.value)
83
89
  return getattr(pytest.mark, node.func.id)(*args, **kwargs)
84
90
 
85
91
  raise ValueError(f"unsupported marker expression: {mark_str}")
@@ -119,13 +125,8 @@ def process_substitutions(
119
125
  match step:
120
126
  case FunctionsSubstitution():
121
127
  for alias, func_def in step.functions.items():
122
- match func_def:
123
- case UserFunctionName():
124
- result[alias] = wrap_function(_resolve_function_name(func_def.root, current_context))
125
- case UserFunctionKwargs():
126
- result[alias] = wrap_function(_resolve_function_name(func_def.name.root, current_context), default_kwargs=func_def.kwargs)
127
- case _:
128
- raise RuntimeError(f"Unhandled function definition for '{alias}': {type(func_def).__name__}")
128
+ name, default_kwargs = call_target(func_def)
129
+ result[alias] = wrap_function(_resolve_function_name(name, current_context), default_kwargs=default_kwargs)
129
130
  logger.debug("Seeded %s", alias)
130
131
 
131
132
  case VarsSubstitution():
@@ -52,13 +52,11 @@ def check_scenario_deep(scenario: Scenario, syspaths: list[Path] | None = None,
52
52
  def _literal_path(value: Any) -> Path | None:
53
53
  """A concrete filesystem path for a literal path value, else None (missing
54
54
  values, inline schemas, and anything holding a ``{{ }}`` template)."""
55
- if value is None or isinstance(value, dict):
56
- return None
57
- if isinstance(value, Path):
58
- return None if "{{" in str(value) else value
59
- if isinstance(value, str):
60
- return None if "{{" in value else Path(value)
61
- return None
55
+ match value:
56
+ case str() | Path() if "{{" not in str(value):
57
+ return Path(value)
58
+ case _:
59
+ return None
62
60
 
63
61
 
64
62
  def _check_path_value(value: Any, location: str, base_dir: Path | None = None) -> Iterator[Diagnostic]:
@@ -83,14 +83,13 @@ def is_inline_schema_position(path: tuple[str | int, ...]) -> bool:
83
83
  response steps accept both the list form (``K`` is an index) and the
84
84
  name-keyed mapping form, and a response mapping value may itself be a list.
85
85
  """
86
- if path[-3:] != ("verify", "body", "schema"):
87
- return False
88
- head = path[:-3]
89
- if len(head) == 4:
90
- return head[0] == "stages" and head[2] == "response"
91
- if len(head) == 5:
92
- return head[0] == "stages" and head[2] == "response" and isinstance(head[4], int)
93
- return False
86
+ match path:
87
+ case ("stages", _, "response", _, "verify", "body", "schema"):
88
+ return True
89
+ case ("stages", _, "response", _, int(), "verify", "body", "schema"):
90
+ return True
91
+ case _:
92
+ return False
94
93
 
95
94
 
96
95
  def load_scenario(path: Path, *, root_path: Path | None = None, ref_parent_traversal_depth: int = 3) -> tuple[Scenario, dict[str, Any]]:
@@ -54,7 +54,7 @@ def check_scenario(scenario: Scenario, test_data: dict[str, Any]) -> list[Diagno
54
54
  fixtures = _scenario_fixtures(scenario)
55
55
  vars_defined = extract_defined_variables(scenario)
56
56
  vars_saved = extract_saved_variables(scenario)
57
- scenario_sub_names = set(substitution_names(scenario.substitutions))
57
+ scenario_sub_names = substitution_names(scenario.substitutions)
58
58
 
59
59
  return [
60
60
  *_stage_name_diagnostics(scenario),