pytest-httpchain 0.16.1__tar.gz → 0.17.1__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 (54) hide show
  1. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/PKG-INFO +1 -1
  2. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/pyproject.toml +3 -2
  3. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/pyproject.toml.orig +4 -2
  4. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/cli.py +4 -4
  5. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/dataflow.py +24 -30
  6. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/har_writer.py +3 -3
  7. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/importers/builder.py +8 -2
  8. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/plumbing/path.py +6 -0
  9. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/models/entities.py +3 -4
  10. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/report_formatter.py +4 -4
  11. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/scoping.py +196 -22
  12. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/templates/substitution.py +12 -3
  13. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/userfunc.py +4 -4
  14. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/validation/deep.py +6 -2
  15. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/validation/semantic.py +34 -17
  16. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/LICENSE +0 -0
  17. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/README.md +0 -0
  18. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/__init__.py +0 -0
  19. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/body_schema.py +0 -0
  20. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/carrier.py +0 -0
  21. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/constants.py +0 -0
  22. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/errors.py +0 -0
  23. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/factory.py +0 -0
  24. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/importers/__init__.py +0 -0
  25. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/importers/curl.py +0 -0
  26. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/importers/har.py +0 -0
  27. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/__init__.py +0 -0
  28. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/equality.py +0 -0
  29. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/exceptions.py +0 -0
  30. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/jsonc.py +0 -0
  31. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/loader.py +0 -0
  32. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/plumbing/__init__.py +0 -0
  33. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/plumbing/circular.py +0 -0
  34. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/jsonref/plumbing/reference.py +0 -0
  35. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/models/__init__.py +0 -0
  36. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/models/types.py +0 -0
  37. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/parallel_stats.py +0 -0
  38. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/plugin.py +0 -0
  39. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/py.typed +0 -0
  40. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/redaction.py +0 -0
  41. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/request_builder.py +0 -0
  42. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/response_steps.py +0 -0
  43. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/schema.py +0 -0
  44. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/templates/__init__.py +0 -0
  45. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/templates/exceptions.py +0 -0
  46. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/templates/expressions.py +0 -0
  47. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/templates/functions.py +0 -0
  48. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/utils.py +0 -0
  49. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/validation/__init__.py +0 -0
  50. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/validation/diagnostics.py +0 -0
  51. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/validation/discovery.py +0 -0
  52. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/validation/loader.py +0 -0
  53. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/src/pytest_httpchain/validation/validate.py +0 -0
  54. {pytest_httpchain-0.16.1 → pytest_httpchain-0.17.1}/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.16.1
3
+ Version: 0.17.1
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytest-httpchain"
3
- version = "0.16.1"
3
+ version = "0.17.1"
4
4
  description = "pytest plugin for HTTP testing using JSON files"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -173,7 +173,8 @@ layers = [
173
173
  "carrier : dataflow : schema : importers",
174
174
  "validation : har_writer : report_formatter : request_builder : response_steps : parallel_stats",
175
175
  "body_schema",
176
- "utils : scoping : redaction",
176
+ "scoping",
177
+ "utils : redaction",
177
178
  "userfunc",
178
179
  "models",
179
180
  "templates : jsonref",
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytest-httpchain"
3
- version = "0.16.1"
3
+ version = "0.17.1"
4
4
  description = "pytest plugin for HTTP testing using JSON files"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -217,7 +217,9 @@ layers = [
217
217
  "carrier : dataflow : schema : importers",
218
218
  "validation : har_writer : report_formatter : request_builder : response_steps : parallel_stats",
219
219
  "body_schema",
220
- "utils : scoping : redaction",
220
+ # scoping reads stage marks with utils.make_marker (scoping.SkipCause).
221
+ "scoping",
222
+ "utils : redaction",
221
223
  "userfunc",
222
224
  "models",
223
225
  "templates : jsonref",
@@ -216,7 +216,7 @@ def _load_for_inspection(path: Path, depth: int, root_path: Path | None = None)
216
216
 
217
217
  def _render_show_text(path: Path, scenario: Scenario, flow: DataFlow) -> list[str]:
218
218
  # Listed nearest first: a name has several producers when the nearer ones
219
- # have a skip_if (analyze_dataflow), each read only when the nearer skipped.
219
+ # may skip (analyze_dataflow), each read only when the nearer skipped.
220
220
  producers_of: dict[tuple[int, str], list[int]] = {}
221
221
  for edge in flow.edges:
222
222
  for var_name in edge.vars:
@@ -285,9 +285,9 @@ def _to_mermaid(flow: DataFlow, direction: str = "TD") -> str:
285
285
  label = f"{s.index + 1} · {s.name}" if s.name else f"{s.index + 1}"
286
286
  lines.append(f' S{s.index}["{_mermaid_label(label)}"]')
287
287
  for edge in flow.edges:
288
- # Dotted from a stage that may skip (skip_if): the values may come from
289
- # an earlier producer instead (its own edge), or never.
290
- arrow = "-->" if flow.stages[edge.producer].skip_if is False else "-.->"
288
+ # Dotted from a stage that may skip (skip_if, or a skip or xfail mark):
289
+ # the values may come from an earlier producer instead (its own edge), or never.
290
+ arrow = "-.->" if flow.stages[edge.producer].may_skip else "-->"
291
291
  lines.append(f" S{edge.producer} {arrow}|{', '.join(edge.vars)}| S{edge.consumer}")
292
292
  return "\n".join(lines)
293
293
 
@@ -13,9 +13,8 @@ from pytest_httpchain.scoping import (
13
13
  RESPONSE_META_NAME,
14
14
  defined_names,
15
15
  extract_template_variables,
16
- raw_list_entries,
17
16
  raw_stages,
18
- saved_in_step,
17
+ response_step_templates,
19
18
  stage_scopes,
20
19
  substitution_names,
21
20
  substitution_step_templates,
@@ -31,8 +30,8 @@ def _consumed(refs: set[str], earlier_saves: frozenset[str], shadows: frozenset[
31
30
  class DataFlowEdge(BaseModel):
32
31
  """A data dependency: ``vars`` saved by stage ``producer`` are referenced by
33
32
  stage ``consumer``. A name has more than one producer when its last writer
34
- before the consumer has a ``skip_if``: one edge from each writer back to the
35
- nearest that never skips (`analyze_dataflow`)."""
33
+ before the consumer may skip: one edge from each writer back to the nearest
34
+ that never skips (`analyze_dataflow`)."""
36
35
 
37
36
  producer: int
38
37
  consumer: int
@@ -40,9 +39,12 @@ class DataFlowEdge(BaseModel):
40
39
 
41
40
 
42
41
  class StageFlow(BaseModel):
43
- """Per-stage data-flow summary. ``skip_if`` is the stage's as declared:
44
- unless it is ``false``, the stage may skip, and a later stage then reads
45
- the value an earlier stage saved under the same name, or finds none."""
42
+ """Per-stage data-flow summary. ``skip_if`` is the stage's as declared.
43
+ ``may_skip`` says whether the stage may end without its saves while the
44
+ chain goes on: a ``skip_if`` other than ``false``, or a ``skip``,
45
+ ``skipif`` or ``xfail`` mark of its own (`scoping.SkipCause`). A later
46
+ stage then reads the value an earlier stage saved under the same name, or
47
+ finds none."""
46
48
 
47
49
  index: int
48
50
  name: str
@@ -51,6 +53,7 @@ class StageFlow(BaseModel):
51
53
  fixtures: list[str]
52
54
  marks: list[str]
53
55
  skip_if: bool | str
56
+ may_skip: bool
54
57
  saves: list[str]
55
58
  consumes: list[str]
56
59
 
@@ -67,13 +70,13 @@ class DataFlow(BaseModel):
67
70
  def _producers(writers: list[int], stages: list[StageFlow]) -> list[int]:
68
71
  """The stages a consumer may read a name from, given its earlier writers in
69
72
  stage order: the last writer, as a later save shadows an earlier one — and
70
- while that writer has a ``skip_if``, the writer before it too, since a
71
- skipped stage leaves the chain running on the earlier value. The walk stops
72
- at the nearest writer that never skips; nearest first."""
73
+ while that writer may skip, the writer before it too, since a skipped
74
+ stage leaves the chain running on the earlier value. The walk stops at the
75
+ nearest writer that never skips; nearest first."""
73
76
  producers: list[int] = []
74
77
  for index in reversed(writers):
75
78
  producers.append(index)
76
- if stages[index].skip_if is False:
79
+ if not stages[index].may_skip:
77
80
  break
78
81
  return producers
79
82
 
@@ -89,10 +92,10 @@ def analyze_dataflow(scenario: Scenario, test_data: dict[str, Any]) -> DataFlow:
89
92
  never saved values.
90
93
 
91
94
  A consumed name comes from its last writer before the consumer. When that
92
- writer has a ``skip_if`` it may have skipped with the chain going on, and
93
- the consumer then reads the writer before it: so the edges run from each
94
- writer back to, and including, the nearest one that never skips — ``graph``
95
- draws those from a stage with a ``skip_if`` dotted.
95
+ writer may skip (a ``skip_if``, or a skip or xfail mark) it may have skipped
96
+ with the chain going on, and the consumer then reads the writer before it:
97
+ so the edges run from each writer back to, and including, the nearest one
98
+ that never skips — ``graph`` draws those from a stage that may skip dotted.
96
99
  """
97
100
  raws = raw_stages(test_data)
98
101
  scopes = stage_scopes(scenario)
@@ -119,22 +122,12 @@ def analyze_dataflow(scenario: Scenario, test_data: dict[str, Any]) -> DataFlow:
119
122
  consumes |= _consumed(extract_template_variables(raw.get("parallel"), defined=defined), scope.earlier_saves, scope.pre_iteration_shadows)
120
123
  consumes |= _consumed(extract_template_variables(raw.get("retry"), defined=defined), scope.earlier_saves, scope.pre_iteration_shadows)
121
124
  consumes |= _consumed(extract_template_variables(raw.get("request"), defined=defined), scope.earlier_saves, scope.request_shadows)
122
- # Response steps resolve in order, each save layering its names over the
123
- # context (the runtime's per-step with_saves): once a step re-saves a
124
- # name, later steps read this stage's fresh value, not the earlier
125
- # stage's — so accumulated own saves join the shadow set step by step.
126
- # The `response` namespace likewise shadows a same-named save.
127
- own_saves: frozenset[str] = frozenset()
128
- # raw_list_entries, not an isinstance(list) guard: the name-keyed mapping
129
- # form of `response` is first-class, and discarding it left every step's
130
- # raw text unread — so show/graph reported a consuming stage as
131
- # consuming nothing and dropped the dependency edge entirely.
132
- raw_response = raw_list_entries(raw.get("response"))
133
- for k, step in enumerate(stage.response):
134
- step_raw = raw_response[k] if k < len(raw_response) else None
135
- step_refs = extract_template_variables(step_raw, defined=defined) - {RESPONSE_META_NAME}
125
+ # The same order-aware iterator the validator uses also sees prior
126
+ # entries inside a substitutions-save step. Those entries resolve in
127
+ # sequence, and only their rendered values can consume an earlier save.
128
+ for templates, own_saves in response_step_templates(stage, raw.get("response")):
129
+ step_refs = extract_template_variables(templates, defined=defined) - {RESPONSE_META_NAME}
136
130
  consumes |= _consumed(step_refs, scope.earlier_saves, scope.request_shadows | own_saves)
137
- own_saves |= frozenset(saved_in_step(step))
138
131
  consumes |= _consumed(extract_template_variables(raw.get("always_run"), defined=defined), scope.earlier_saves, scope.always_run_shadows)
139
132
 
140
133
  by_producer: dict[int, list[str]] = {}
@@ -153,6 +146,7 @@ def analyze_dataflow(scenario: Scenario, test_data: dict[str, Any]) -> DataFlow:
153
146
  fixtures=sorted(stage.fixtures),
154
147
  marks=list(stage.marks),
155
148
  skip_if=stage.skip_if,
149
+ may_skip=scope.skip_cause is not None,
156
150
  saves=sorted(scope.saves),
157
151
  consumes=sorted(consumes),
158
152
  )
@@ -10,7 +10,7 @@ import hashlib
10
10
  import json
11
11
  import re
12
12
  from datetime import UTC, datetime
13
- from importlib.metadata import version
13
+ from importlib.metadata import PackageNotFoundError, version
14
14
  from pathlib import Path
15
15
  from typing import Any
16
16
  from urllib.parse import parse_qsl, urlparse
@@ -31,7 +31,7 @@ def _get_version() -> str:
31
31
  change in-process."""
32
32
  try:
33
33
  return version("pytest-httpchain")
34
- except Exception:
34
+ except PackageNotFoundError:
35
35
  return "unknown"
36
36
 
37
37
 
@@ -103,7 +103,7 @@ def _format_post_data(request: httpx.Request) -> dict[str, Any] | None:
103
103
  body_text = _body_text(content)
104
104
  post_data: dict[str, Any] = {"mimeType": _mime_type(content_type), **body_text}
105
105
 
106
- if "application/x-www-form-urlencoded" in content_type and "encoding" not in body_text:
106
+ if "application/x-www-form-urlencoded" in content_type.lower() and "encoding" not in body_text:
107
107
  # HAR params are repeated scalar name/value records, not one record with
108
108
  # an array value. parse_qsl also preserves the body's original ordering.
109
109
  post_data["params"] = [{"name": name, "value": value} for name, value in parse_qsl(body_text["text"], keep_blank_values=True)]
@@ -741,8 +741,9 @@ class _Builder:
741
741
  # as a host: absolute, that one URL ignores base_url.
742
742
  target = path if base_url is not None and not path.startswith("//") else f"{_origin(url.scheme, url.netloc)}{path}"
743
743
  params, query = self.query(url.query, stage)
744
+ empty_query = not url.query and recorded.url.partition("#")[0].endswith("?")
744
745
  # Closed before a query holding a placeholder.
745
- request["url"] = escape(target, closed=query is not None and contains_template(query)) + (f"?{query}" if query is not None else "")
746
+ request["url"] = escape(target, closed=query is not None and contains_template(query)) + (f"?{query or ''}" if query is not None or empty_query else "")
746
747
  if params:
747
748
  request["params"] = params
748
749
 
@@ -821,7 +822,12 @@ class _Builder:
821
822
  holds a secret, since ``params`` sends a value rendered to null
822
823
  empty, where the URL's placeholder fails the stage unset
823
824
  (`fields_text`). A piece without ``=`` is sent as an empty value."""
824
- pairs = _decoded_pairs([piece for piece in query.split("&") if piece])
825
+ if not query:
826
+ return None, None
827
+ pieces = query.split("&")
828
+ # An empty component (a leading, repeated or trailing ampersand) is
829
+ # lost when a query is rewritten as params. Keep such queries intact.
830
+ pairs = _decoded_pairs(pieces) if all(pieces) else None
825
831
  if pairs is not None and _mappable([name for name, _ in pairs]) and not self.any_secret(pairs):
826
832
  return _grouped([(name, escape(value)) for name, value in pairs]), None
827
833
  return None, self.fields_text(query, "query parameter", stage)
@@ -1,5 +1,6 @@
1
1
  """Reference path and JSON pointer helpers for reference resolution."""
2
2
 
3
+ import re
3
4
  import warnings
4
5
  from pathlib import Path, PurePosixPath, PureWindowsPath
5
6
 
@@ -90,4 +91,9 @@ def parse_json_pointer(pointer: str) -> list[str]:
90
91
  if not pointer.startswith("/"):
91
92
  raise ReferenceResolverError(f"Invalid JSON pointer: {pointer} (must start with '/')")
92
93
 
94
+ # RFC 6901 reserves ``~`` for the two escapes below. Leaving any other
95
+ # sequence literal would silently select a key the pointer does not name.
96
+ if re.search(r"~(?![01])", pointer):
97
+ raise ReferenceResolverError(f"Invalid JSON pointer: {pointer} (invalid '~' escape)")
98
+
93
99
  return [part.replace("~1", "/").replace("~0", "~") for part in pointer[1:].split("/")]
@@ -1086,7 +1086,7 @@ class IndividualParameter(StrictModel):
1086
1086
 
1087
1087
  @model_validator(mode="after")
1088
1088
  def validate_ids_match_values(self) -> Self:
1089
- if self.ids and self.individual:
1089
+ if self.ids is not None:
1090
1090
  values = next(iter(self.individual.values()))
1091
1091
  if isinstance(values, str): # template form: count unknown until runtime
1092
1092
  return self
@@ -1118,9 +1118,8 @@ class CombinationsParameter(StrictModel):
1118
1118
  if combo_keys != first_keys:
1119
1119
  raise ValueError(f"Combination {i} has different parameters than combination 0")
1120
1120
 
1121
- if self.ids and self.combinations:
1122
- if len(self.ids) != len(self.combinations):
1123
- raise ValueError(f"Number of ids ({len(self.ids)}) must match number of combinations ({len(self.combinations)})")
1121
+ if self.ids is not None and len(self.ids) != len(self.combinations):
1122
+ raise ValueError(f"Number of ids ({len(self.ids)}) must match number of combinations ({len(self.combinations)})")
1124
1123
  return self
1125
1124
 
1126
1125
 
@@ -53,7 +53,7 @@ def format_request(request: httpx.Request, redaction: Redaction = DEFAULT_REDACT
53
53
  body = f"<Binary content: {len(content)} bytes>"
54
54
  else:
55
55
  body = _format_body_text(decoded)
56
- if "application/json" in content_type:
56
+ if "application/json" in content_type.lower():
57
57
  try:
58
58
  body = _format_json(json.loads(decoded))
59
59
  except JSON_PARSE_ERRORS:
@@ -137,7 +137,7 @@ def format_response(response: httpx.Response, redaction: Redaction = DEFAULT_RED
137
137
  body = None
138
138
  if response.content:
139
139
  content_type = response.headers.get("Content-Type", "")
140
- if "application/json" in content_type:
140
+ if "application/json" in content_type.lower():
141
141
  try:
142
142
  body = _format_json(response.json())
143
143
  except JSON_PARSE_ERRORS:
@@ -255,7 +255,7 @@ def format_curl(request: httpx.Request, redaction: Redaction = DEFAULT_REDACTION
255
255
  if lowered == "authorization" and value[: len(_DIGEST_SCHEME)].lower() == _DIGEST_SCHEME:
256
256
  notes.append("The Digest Authorization answered one challenge and is left out: add --digest -u 'user:password' to answer a new one.")
257
257
  continue
258
- if lowered == "content-type" and content is None and value.startswith("multipart/"):
258
+ if lowered == "content-type" and content is None and value.lower().startswith("multipart/"):
259
259
  # Its boundary is the uncaptured body's: -F writes its own.
260
260
  continue
261
261
  shown = redaction.header(name, value)
@@ -265,7 +265,7 @@ def format_curl(request: httpx.Request, redaction: Redaction = DEFAULT_REDACTION
265
265
 
266
266
  data: str | None = None
267
267
  if content is None:
268
- if content_type is not None and content_type.startswith("multipart/"):
268
+ if content_type is not None and content_type.lower().startswith("multipart/"):
269
269
  notes.append("The multipart body was not captured: add each part with -F 'name=@file'.")
270
270
  else:
271
271
  notes.append("The streamed body was not captured: add it with --data-binary @file.")
@@ -32,9 +32,11 @@ time against scenario substitutions only, which is why `StageScopes` exposes
32
32
 
33
33
  An earlier stage's saves are in scope because it passed: one that failed
34
34
  aborted the chain, so only an ``always_run`` stage runs without them. One
35
- that skipped (``skip_if``) leaves the chain healthy, so every later stage runs
36
- without them; `StageScopes.skippable_saves` holds the names only such stages
37
- save, and `StageScopes.when_skipped` the scope without them.
35
+ that skipped leaves the chain healthy, so every later stage runs without them:
36
+ a ``skip_if``, or a ``skip``, ``skipif`` or ``xfail`` mark of the stage's own
37
+ (a `SkipCause`; an expected failure is reported skipped too).
38
+ `StageScopes.skippable_saves` holds the names only such stages save, and
39
+ `StageScopes.when_skipped` the scope without them.
38
40
 
39
41
  The template built-ins (``now()``, ``len()``, ``true``, ...) are in scope in
40
42
  every phase, beneath the user's names: a user name shadows a built-in of the
@@ -43,12 +45,15 @@ built-in (see `extract_template_variables` and `extract_builtin_stand_ins`).
43
45
  """
44
46
 
45
47
  import ast
48
+ import warnings
46
49
  from collections import ChainMap
47
50
  from collections.abc import Iterable, Iterator, Mapping
48
51
  from collections.abc import Set as AbstractSet
49
52
  from dataclasses import dataclass, replace
50
53
  from typing import Any, NamedTuple
51
54
 
55
+ import pytest
56
+
52
57
  from pytest_httpchain.models import (
53
58
  CombinationsParameter,
54
59
  FunctionsSubstitution,
@@ -68,6 +73,7 @@ from pytest_httpchain.models import (
68
73
  normalize_list_input,
69
74
  )
70
75
  from pytest_httpchain.templates import CALL_ONLY_BUILTINS, CONTEXT_HELPERS, TEMPLATE_BUILTINS, TemplatesError, find_templates, parse_expression, template_form
76
+ from pytest_httpchain.utils import make_marker
71
77
 
72
78
  # The name under which response metadata is injected into response-step contexts.
73
79
  RESPONSE_META_NAME = "response"
@@ -121,20 +127,49 @@ class _TemplateNames(NamedTuple):
121
127
  self.to_methods.update(other.to_methods)
122
128
 
123
129
 
124
- def _receiver(node: ast.expr) -> str | None:
125
- """The name a method's object is reached from (``helper`` for
130
+ def _receiver(node: ast.expr) -> ast.Name | None:
131
+ """The name node a method's object is reached from (``helper`` for
126
132
  ``helper.api.ids``, ``helper().ids``, ``helper['x'].ids``), or None for an
127
133
  object written in place (``', '.join``)."""
128
134
  while True:
129
135
  match node:
130
136
  case ast.Attribute(value=inner) | ast.Subscript(value=inner) | ast.Call(func=inner):
131
137
  node = inner
132
- case ast.Name(id=name):
133
- return name
138
+ case ast.Name():
139
+ return node
134
140
  case _:
135
141
  return None
136
142
 
137
143
 
144
+ def _local_comprehension_reads(tree: ast.expr) -> set[int]:
145
+ """The name nodes read from comprehension targets, rather than context.
146
+
147
+ A generator's iterable is evaluated before its target is bound. The
148
+ target is visible in its filters, later generators and result, but not in
149
+ an expression outside the comprehension. Keep this walk iterative as the
150
+ other expression walks are: valid expressions can be deeply nested.
151
+ """
152
+ local_reads: set[int] = set()
153
+ pending: list[tuple[ast.AST, frozenset[str]]] = [(tree, frozenset())]
154
+ while pending:
155
+ node, bound = pending.pop()
156
+ if isinstance(node, ast.Name):
157
+ if isinstance(node.ctx, ast.Load) and node.id in bound:
158
+ local_reads.add(id(node))
159
+ elif isinstance(node, ast.ListComp | ast.GeneratorExp | ast.DictComp):
160
+ for generator in node.generators:
161
+ pending.append((generator.iter, bound))
162
+ bound |= frozenset(name.id for name in ast.walk(generator.target) if isinstance(name, ast.Name))
163
+ pending.extend((condition, bound) for condition in generator.ifs)
164
+ if isinstance(node, ast.DictComp):
165
+ pending.extend(((node.key, bound), (node.value, bound)))
166
+ else:
167
+ pending.append((node.elt, bound))
168
+ else:
169
+ pending.extend((child, bound) for child in ast.iter_child_nodes(node))
170
+ return local_reads
171
+
172
+
138
173
  def _extract_names_from_expr(expr: str) -> _TemplateNames:
139
174
  """Free identifiers a Python expression reads, and those it calls.
140
175
 
@@ -164,16 +199,16 @@ def _extract_names_from_expr(expr: str) -> _TemplateNames:
164
199
  except TemplatesError:
165
200
  return names
166
201
 
167
- bound: set[str] = set()
168
- callees: set[int] = set()
202
+ local_reads = _local_comprehension_reads(tree)
203
+ # simpleeval calls a bare name through its function table, even where a
204
+ # comprehension target of that name is bound as a value.
205
+ callees = {id(node.func) for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)}
169
206
  # What each argument that may be a function is handed to, by node.
170
207
  keys: set[int] = set()
171
208
  to_functions: set[int] = set()
172
209
  to_methods: dict[int, str] = {}
173
210
  for node in ast.walk(tree):
174
- if isinstance(node, ast.comprehension):
175
- bound |= {n.id for n in ast.walk(node.target) if isinstance(n, ast.Name)}
176
- elif isinstance(node, ast.Call):
211
+ if isinstance(node, ast.Call):
177
212
  key = [keyword.value for keyword in node.keywords if keyword.arg == "key"]
178
213
  others = [*node.args, *(keyword.value for keyword in node.keywords if keyword.arg != "key")]
179
214
  match node.func:
@@ -183,22 +218,22 @@ def _extract_names_from_expr(expr: str) -> _TemplateNames:
183
218
  keys.update(id(argument) for argument in key)
184
219
  case ast.Attribute(value=value):
185
220
  keys.update(id(argument) for argument in key)
186
- if (receiver := _receiver(value)) is not None:
187
- to_methods.update(dict.fromkeys(map(id, others), receiver))
188
- if isinstance(node.func, ast.Name):
189
- callees.add(id(node.func))
221
+ if (receiver := _receiver(value)) is not None and (id(receiver) not in local_reads or id(receiver) in callees):
222
+ to_methods.update(dict.fromkeys(map(id, others), receiver.id))
190
223
 
191
224
  for node in ast.walk(tree):
192
- if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and node.id not in bound:
225
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
193
226
  if id(node) in callees:
194
227
  names.called.add(node.id)
195
228
  continue
229
+ if id(node) in local_reads:
230
+ continue
196
231
  names.read.add(node.id)
197
232
  if id(node) in keys:
198
233
  names.keys.add(node.id)
199
234
  elif id(node) in to_functions:
200
235
  names.to_functions.add(node.id)
201
- elif (receiver := to_methods.get(id(node))) is not None and receiver not in bound:
236
+ elif (receiver := to_methods.get(id(node))) is not None:
202
237
  names.to_methods.add((receiver, node.id))
203
238
  else:
204
239
  names.loose.add(node.id)
@@ -567,6 +602,137 @@ def response_step_templates(stage: Stage, raw_response: Any) -> Iterator[tuple[A
567
602
  opaque_save_seen = True
568
603
 
569
604
 
605
+ # --------------------------------------------------------------------------- #
606
+ # Skip causes: which stages may end without their saves while the chain goes on.
607
+ # --------------------------------------------------------------------------- #
608
+
609
+
610
+ @dataclass(frozen=True, slots=True)
611
+ class SkipCause:
612
+ """Why a stage may end without committing its saves while the stages after
613
+ it still run: its ``skip_if``, or a ``skip``, ``skipif`` or ``xfail`` mark of
614
+ its own. pytest reports all of them skipped (an expected failure is a skip
615
+ carrying ``wasxfail``), which `plugin.pytest_runtest_makereport` leaves
616
+ chain-healthy."""
617
+
618
+ mark: str | None
619
+ """The mark as written; ``None`` for the stage's ``skip_if``."""
620
+ fails_as_expected: bool = False
621
+ """An ``xfail`` that runs the stage: its saves are lost when it fails as
622
+ expected, where the others' are lost when it skips."""
623
+ never_called: bool = False
624
+ """pytest never calls the stage: a skip at setup, or an ``xfail(run=False)``
625
+ (unless pytest runs with ``--runxfail``, which ignores xfail marks)."""
626
+
627
+
628
+ # The marks pytest's skipping plugin turns into an outcome.
629
+ _OUTCOME_MARKS = ("skip", "skipif", "xfail")
630
+
631
+
632
+ def _outcome_marks(marks: Iterable[str]) -> list[tuple[str, pytest.Mark]]:
633
+ """The ``skip``, ``skipif`` and ``xfail`` marks among ``marks``, in order,
634
+ each with the mark as written. A mark that does not parse is HTTPCHAIN019's
635
+ to report, and left out."""
636
+ parsed: list[tuple[str, pytest.Mark]] = []
637
+ for mark_str in marks:
638
+ try:
639
+ # Constructing an unregistered mark warns; only the parse matters here.
640
+ with warnings.catch_warnings():
641
+ warnings.simplefilter("ignore")
642
+ mark = make_marker(mark_str).mark
643
+ except Exception:
644
+ continue
645
+ if mark.name in _OUTCOME_MARKS:
646
+ parsed.append((mark_str, mark))
647
+ return parsed
648
+
649
+
650
+ def _conditions_apply(mark: pytest.Mark) -> bool | None:
651
+ """Whether a ``skipif``/``xfail`` mark applies, read as pytest's skipping
652
+ plugin reads it: with no condition it always does, otherwise when a
653
+ condition is true, tried in order. ``None`` is pytest's to decide at run
654
+ time: a string condition is an expression it evaluates, unless the string
655
+ is a literal. A non-string condition needs ``reason=``: without it pytest
656
+ fails the stage, true or not, and a failure aborts the chain, so from there
657
+ on the mark never skips it."""
658
+ conditions = (mark.kwargs["condition"],) if "condition" in mark.kwargs else mark.args
659
+ if not conditions:
660
+ return True
661
+ verdict: bool | None = False
662
+ for condition in conditions:
663
+ if isinstance(condition, str):
664
+ try:
665
+ condition = ast.literal_eval(condition)
666
+ except Exception:
667
+ # Broad on purpose: whatever literal_eval rejects is an
668
+ # expression only pytest can evaluate.
669
+ verdict = None
670
+ continue
671
+ elif mark.kwargs.get("reason") is None:
672
+ return verdict
673
+ if condition:
674
+ return True
675
+ return verdict
676
+
677
+
678
+ def marks_skip_cause(marks: Iterable[str]) -> SkipCause | None:
679
+ """The skip cause the marks on a stage give it, if any, read in the order
680
+ pytest's skipping plugin reads them.
681
+
682
+ At setup every ``skipif`` and ``skip`` is looked at before any ``xfail``:
683
+ one that certainly applies means pytest never calls the stage. Of the
684
+ ``xfail`` marks, the first that applies decides: with ``run=False`` pytest
685
+ never calls the stage, otherwise it runs, and an expected failure discards
686
+ its saves. One with ``raises=`` never fails as expected: a mark can give it
687
+ only a literal, never an exception type, so pytest reports every failure as
688
+ a real one. One pytest never calls is named first, then a ``skip``/``skipif``
689
+ that may apply, then the first ``xfail`` that may end the stage.
690
+ """
691
+ outcome_marks = _outcome_marks(marks)
692
+ may_skip: list[str] = []
693
+ for mark_str, mark in outcome_marks:
694
+ if mark.name == "xfail":
695
+ continue
696
+ applies = True if mark.name == "skip" else _conditions_apply(mark)
697
+ if applies:
698
+ return SkipCause(mark=mark_str, never_called=True)
699
+ if applies is None:
700
+ may_skip.append(mark_str)
701
+ xfail: SkipCause | None = None
702
+ for mark_str, mark in outcome_marks:
703
+ if mark.name != "xfail":
704
+ continue
705
+ applies = _conditions_apply(mark)
706
+ if applies is False:
707
+ continue
708
+ runs = bool(mark.kwargs.get("run", True))
709
+ if xfail is None and (not runs or mark.kwargs.get("raises") is None):
710
+ xfail = SkipCause(mark=mark_str, fails_as_expected=runs, never_called=applies is True and not runs)
711
+ if applies:
712
+ break # this one decides; pytest looks at none after it
713
+ if xfail is not None and xfail.never_called:
714
+ return xfail
715
+ return SkipCause(mark=may_skip[0]) if may_skip else xfail
716
+
717
+
718
+ def _stage_skip_cause(stage: Stage) -> SkipCause | None:
719
+ """Why ``stage`` may end without its saves, or ``None`` when it never does:
720
+ a mark that keeps pytest from calling it, else its ``skip_if``, else a mark
721
+ that may skip it (`marks_skip_cause`).
722
+
723
+ Scenario-level ``marks`` are not read. They apply to every stage, the one
724
+ that reads a save as much as the one that saves it: a scenario-wide
725
+ ``skipif`` skips both or neither, and under a scenario-wide ``xfail`` the
726
+ reader's failure is an expected one too.
727
+ """
728
+ cause = marks_skip_cause(stage.marks)
729
+ if cause is not None and cause.never_called:
730
+ return cause
731
+ if stage.skip_if is not False:
732
+ return SkipCause(mark=None)
733
+ return cause
734
+
735
+
570
736
  # --------------------------------------------------------------------------- #
571
737
  # Static scope model: per-stage, per-phase name availability.
572
738
  # --------------------------------------------------------------------------- #
@@ -635,12 +801,17 @@ class StageScopes:
635
801
  saves: frozenset[str]
636
802
  earlier_saves: frozenset[str]
637
803
  skippable_saves: frozenset[str]
638
- """The ``earlier_saves`` that only stages with a ``skip_if`` save: none
804
+ """The ``earlier_saves`` that only stages with a `SkipCause` save: none
639
805
  is there when those stages skipped."""
806
+ skip_cause: SkipCause | None
807
+ """This stage's own, if it may skip."""
808
+ never_called: bool
809
+ """pytest never calls this stage, by its own marks or the scenario's, which
810
+ apply to every stage (`marks_skip_cause`): it reads nothing."""
640
811
 
641
812
  @property
642
813
  def when_skipped(self) -> "StageScopes":
643
- """This scope as it is when every earlier stage with a ``skip_if``
814
+ """This scope as it is when every earlier stage with a `SkipCause`
644
815
  skipped: without `skippable_saves`. A name in a phase's scope here but
645
816
  not in the same phase of ``when_skipped`` is defined only when such a
646
817
  stage ran."""
@@ -703,7 +874,7 @@ class StageScopes:
703
874
  def stage_scopes(scenario: Scenario) -> list[StageScopes]:
704
875
  """Per-stage scopes in execution order. ``earlier_saves`` accumulates stage
705
876
  by stage, mirroring the runtime commit of saves after a stage passes, and
706
- ``skippable_saves`` holds those of them no stage without a ``skip_if``
877
+ ``skippable_saves`` holds those of them no stage without a `SkipCause`
707
878
  saves (``skip_if: false`` never skips)."""
708
879
  scenario_substitutions = frozenset(substitution_names(scenario.substitutions))
709
880
  scenario_fixtures = frozenset(scenario.fixtures)
@@ -713,6 +884,7 @@ def stage_scopes(scenario: Scenario) -> list[StageScopes]:
713
884
  unskippable_saves: frozenset[str] = frozenset()
714
885
  for stage in scenario.stages:
715
886
  saves = frozenset(saved_in_stage(stage))
887
+ skip_cause = _stage_skip_cause(stage)
716
888
  scopes.append(
717
889
  StageScopes(
718
890
  scenario_substitutions=scenario_substitutions,
@@ -724,10 +896,12 @@ def stage_scopes(scenario: Scenario) -> list[StageScopes]:
724
896
  saves=saves,
725
897
  earlier_saves=earlier_saves,
726
898
  skippable_saves=earlier_saves - unskippable_saves,
899
+ skip_cause=skip_cause,
900
+ never_called=(reader := marks_skip_cause([*stage.marks, *scenario.marks])) is not None and reader.never_called,
727
901
  )
728
902
  )
729
903
  earlier_saves |= saves
730
- if stage.skip_if is False:
904
+ if skip_cause is None:
731
905
  unskippable_saves |= saves
732
906
  return scopes
733
907
 
@@ -133,7 +133,7 @@ class _KeyDoesNotExist(InvalidExpression):
133
133
 
134
134
  def __init__(self, key: object, expression: str):
135
135
  self.message = f"Key {key!r} does not exist in expression '{expression}'"
136
- super(InvalidExpression, self).__init__(self.message)
136
+ super().__init__(self.message)
137
137
 
138
138
 
139
139
  class _MethodNotCalled(AttributeDoesNotExist):
@@ -462,11 +462,20 @@ def _any_string(obj: Any, predicate: Callable[[str], bool]) -> bool:
462
462
  """True when ``predicate`` holds for any string anywhere in the structure.
463
463
 
464
464
  Iterative on purpose: a recursive walk spent two stack frames per level of
465
- nesting, so a value a few hundred levels deep overflowed it.
465
+ nesting, so a value a few hundred levels deep overflowed it. Track objects
466
+ already visited so a fixture's cyclic container cannot loop forever.
466
467
  """
467
468
  pending = [obj]
469
+ # Keep the objects alive while scanning: a set of IDs alone could confuse
470
+ # a newly dumped model with an earlier object whose ID was reused.
471
+ seen: dict[int, Any] = {}
468
472
  while pending:
469
- match pending.pop():
473
+ current = pending.pop()
474
+ if isinstance(current, dict | list | tuple | BaseModel | SimpleNamespace):
475
+ if id(current) in seen:
476
+ continue
477
+ seen[id(current)] = current
478
+ match current:
470
479
  case str() as text:
471
480
  if predicate(text):
472
481
  return True
@@ -46,10 +46,10 @@ def import_function(name: str, *, quoted: bool = True) -> Callable[..., Any]:
46
46
  raise UserFunctionError(f"importing its module raised {type(e).__name__}") from None
47
47
  raise UserFunctionError(f"Failed to import module '{module_path}': {e}") from e
48
48
 
49
- if not hasattr(module, function_name):
50
- raise UserFunctionError(f"Function '{function_name}' not found in module '{module_path}'" if quoted else "its module has no function of that name")
51
-
52
- func = getattr(module, function_name)
49
+ try:
50
+ func = getattr(module, function_name)
51
+ except AttributeError:
52
+ raise UserFunctionError(f"Function '{function_name}' not found in module '{module_path}'" if quoted else "its module has no function of that name") from None
53
53
  if not callable(func):
54
54
  raise UserFunctionError(f"'{module_path}:{function_name}' is not callable" if quoted else "what it names is not callable")
55
55
 
@@ -186,12 +186,16 @@ def _signature_problems(func: Any, provided: set[str]) -> Iterator[tuple[Diagnos
186
186
 
187
187
  params = list(signature.parameters.values())
188
188
  keyword_acceptable = {p.name for p in params if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)}
189
- required = {p.name for p in params if p.default is p.empty and p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY, p.POSITIONAL_ONLY)}
189
+ required_keywords = {p.name for p in params if p.default is p.empty and p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)}
190
+ required_positionals = {p.name for p in params if p.default is p.empty and p.kind is p.POSITIONAL_ONLY}
190
191
 
191
192
  if not any(p.kind is p.VAR_KEYWORD for p in params):
192
193
  for name in sorted(provided - keyword_acceptable):
193
194
  yield DiagnosticCode.UNKNOWN_ARG, f"unexpected argument '{name}'"
194
- for name in sorted(required - provided):
195
+ # A keyword with the same name cannot fill a positional-only parameter.
196
+ # With **kwargs it is accepted into kwargs, but the positional argument is
197
+ # still missing when the function is called.
198
+ for name in sorted(required_positionals | (required_keywords - provided)):
195
199
  yield DiagnosticCode.MISSING_ARG, f"missing required argument '{name}'"
196
200
 
197
201
 
@@ -34,6 +34,8 @@ from pytest_httpchain.scoping import (
34
34
  SCENARIO_TEMPLATE_FIELDS,
35
35
  DefinedNames,
36
36
  NameUnion,
37
+ SkipCause,
38
+ StageScopes,
37
39
  defined_names,
38
40
  extract_builtin_stand_ins,
39
41
  extract_defined_variables,
@@ -44,7 +46,6 @@ from pytest_httpchain.scoping import (
44
46
  raw_stages,
45
47
  response_step_templates,
46
48
  saved_in_response,
47
- saved_in_stage,
48
49
  stage_scopes,
49
50
  stats_name,
50
51
  substitution_names,
@@ -350,16 +351,23 @@ def _parametrize_rendered_values(raw_parametrize: Any) -> Any:
350
351
  return raw_parametrize
351
352
 
352
353
 
353
- def _skippable_save_diagnostic(scenario: Scenario, i: int, where: str, name: str, location: str) -> Diagnostic:
354
+ def _skip_cause_text(cause: SkipCause) -> str:
355
+ return "skip_if" if cause.mark is None else f"the mark {cause.mark!r}"
356
+
357
+
358
+ def _skippable_save_diagnostic(scenario: Scenario, scopes: list[StageScopes], i: int, where: str, name: str, location: str) -> Diagnostic:
354
359
  """HTTPCHAIN003 for a reference to ``name`` that only earlier stages with a
355
- ``skip_if`` save (`scoping.StageScopes.skippable_saves`): a skip leaves the
356
- chain healthy, so stage ``i`` runs, and finds the name undefined, whenever
357
- those stages skipped. ``where`` is the phase that reads it."""
358
- savers = [f"'{stage.name}'" for stage in scenario.stages[:i] if name in saved_in_stage(stage)]
360
+ `scoping.SkipCause` save (`scoping.StageScopes.skippable_saves`): a skip
361
+ leaves the chain healthy, so stage ``i`` runs, and finds the name undefined,
362
+ whenever those stages skipped. Each saver is named with its cause, its
363
+ ``skip_if`` or the mark as written. ``where`` is the phase that reads it."""
364
+ savers = [(scenario.stages[j].name, cause) for j in range(i) if name in scopes[j].saves and (cause := scopes[j].skip_cause)]
359
365
  if len(savers) == 1:
360
- saved = f"which only stage {savers[0]} saves, and it has skip_if: when it skips"
366
+ [(saver, cause)] = savers
367
+ saved = f"which only stage '{saver}' saves, and it has {_skip_cause_text(cause)}: when it {'fails as expected' if cause.fails_as_expected else 'skips'}"
361
368
  else:
362
- saved = f"which only stages {', '.join(savers)} save, and each has skip_if: when they all skip"
369
+ listed = ", ".join(f"'{saver}' ({_skip_cause_text(cause)})" for saver, cause in savers)
370
+ saved = f"which only stages {listed} save: when none of them saves it"
363
371
  return diag(
364
372
  DiagnosticCode.UNDEFINED_VAR,
365
373
  f"Stage '{scenario.stages[i].name}': {where} references '{name}', {saved}, '{name}' is undefined here — read it with get('{name}', <default>){_builtin_fallback({name})}",
@@ -374,9 +382,12 @@ def _dataflow_diagnostics(scenario: Scenario, test_data: dict[str, Any], defined
374
382
  ``scoping.stage_scopes``. An unavailable reference is a FORWARD_REF when the
375
383
  name is saved later (by a later stage, or by a later step of this stage's
376
384
  own response) or defined by a later substitution step, else an UNDEFINED_VAR.
377
- An available one is an UNDEFINED_VAR too where only earlier stages with a
378
- ``skip_if`` save it, and nothing else of that name is in scope: a skipped
379
- stage, unlike a failed one, does not stop the stages after it. A built-in's
385
+ An available one is an UNDEFINED_VAR too where only earlier stages that may
386
+ skip (a ``skip_if``, or a ``skip``, ``skipif`` or ``xfail`` mark) save it,
387
+ and nothing else of that name is in scope: a skipped stage, unlike a failed
388
+ one, does not stop the stages after it. Not in a stage a mark keeps pytest
389
+ from ever calling, which reads nothing, nor past the always_run of one whose
390
+ skip_if is true. A built-in's
380
391
  name the scenario defines too, called or passed as a function where that
381
392
  definition is not in scope, gets the built-in instead: a BUILTIN_STANDS_IN.
382
393
  """
@@ -394,8 +405,14 @@ def _dataflow_diagnostics(scenario: Scenario, test_data: dict[str, Any], defined
394
405
  for i, stage in enumerate(scenario.stages):
395
406
  scope = scopes[i]
396
407
  phases = scope.phases()
397
- # The same phases, as they are when every earlier stage with a skip_if skipped.
398
- skipped = phases if scope.when_skipped is scope else scope.when_skipped.phases()
408
+ # The same phases, as they are when every earlier stage that may skip
409
+ # skipped. Unchanged where the stage reads nothing: pytest never calls
410
+ # it, or, past always_run, its skip_if is true (the carrier skips it
411
+ # right after always_run, before anything else renders).
412
+ skipped = phases if scope.when_skipped is scope or scope.never_called else scope.when_skipped.phases()
413
+ skipped_always_run = skipped.always_run
414
+ if stage.skip_if is True:
415
+ skipped = phases
399
416
  raw = raws[i] if i < len(raws) and isinstance(raws[i], dict) else {}
400
417
 
401
418
  parametrize_refs, parametrize_stand_ins = _template_refs(_parametrize_rendered_values(raw.get("parametrize")), defined)
@@ -419,8 +436,8 @@ def _dataflow_diagnostics(scenario: Scenario, test_data: dict[str, Any], defined
419
436
  always_run_refs, always_run_stand_ins = _template_refs(raw.get("always_run"), defined)
420
437
  for name in sorted(always_run_refs):
421
438
  if name in phases.always_run:
422
- if name not in skipped.always_run:
423
- yield _skippable_save_diagnostic(scenario, i, "always_run", name, f"stages[{i}].always_run")
439
+ if name not in skipped_always_run:
440
+ yield _skippable_save_diagnostic(scenario, scopes, i, "always_run", name, f"stages[{i}].always_run")
424
441
  continue
425
442
  if name in all_saved:
426
443
  j = first_save_stage[name]
@@ -441,7 +458,7 @@ def _dataflow_diagnostics(scenario: Scenario, test_data: dict[str, Any], defined
441
458
  yield _stand_in_diagnostic(f"Stage '{stage.name}': always_run", always_run_stand_ins, f"stages[{i}].always_run")
442
459
 
443
460
  # (phase, template text, names available to it, and those of them
444
- # still available when every earlier stage with a skip_if skipped).
461
+ # still available when every earlier stage that may skip skipped).
445
462
  # Each substitution and response step is checked against its own
446
463
  # scope, not the whole stage's: checking cumulatively is what catches
447
464
  # intra-list forward references. A name referenced by several steps is
@@ -474,7 +491,7 @@ def _dataflow_diagnostics(scenario: Scenario, test_data: dict[str, Any], defined
474
491
  for name in sorted(refs):
475
492
  if name in available:
476
493
  if name not in available_when_skipped:
477
- yield _skippable_save_diagnostic(scenario, i, phase, name, f"stages[{i}].{phase}")
494
+ yield _skippable_save_diagnostic(scenario, scopes, i, phase, name, f"stages[{i}].{phase}")
478
495
  continue
479
496
  if name in scope.stage_substitutions:
480
497
  yield diag(