pytest-httpchain 0.19.0__tar.gz → 0.20.0__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 (56) hide show
  1. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/PKG-INFO +2 -2
  2. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/pyproject.toml +5 -4
  3. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/pyproject.toml.orig +16 -4
  4. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/carrier.py +1 -1
  5. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/cli.py +109 -8
  6. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/factory.py +3 -3
  7. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/importers/builder.py +48 -1
  8. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/models/entities.py +26 -2
  9. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/models/types.py +191 -1
  10. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/request_builder.py +3 -1
  11. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/LICENSE +0 -0
  12. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/README.md +0 -0
  13. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/__init__.py +0 -0
  14. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/body_schema.py +0 -0
  15. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/connections.py +0 -0
  16. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/constants.py +0 -0
  17. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/dataflow.py +0 -0
  18. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/errors.py +0 -0
  19. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/har_writer.py +0 -0
  20. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/importers/__init__.py +0 -0
  21. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/importers/curl.py +0 -0
  22. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/importers/har.py +0 -0
  23. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/__init__.py +0 -0
  24. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/equality.py +0 -0
  25. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/exceptions.py +0 -0
  26. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/jsonc.py +0 -0
  27. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/loader.py +0 -0
  28. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/plumbing/__init__.py +0 -0
  29. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/plumbing/circular.py +0 -0
  30. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/plumbing/path.py +0 -0
  31. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/jsonref/plumbing/reference.py +0 -0
  32. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/models/__init__.py +0 -0
  33. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/parallel_stats.py +0 -0
  34. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/plugin.py +0 -0
  35. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/py.typed +0 -0
  36. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/redaction.py +0 -0
  37. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/report_formatter.py +0 -0
  38. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/response_steps.py +0 -0
  39. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/schema.py +0 -0
  40. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/scoping.py +0 -0
  41. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/templates/__init__.py +0 -0
  42. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/templates/exceptions.py +0 -0
  43. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/templates/expressions.py +0 -0
  44. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/templates/functions.py +0 -0
  45. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/templates/substitution.py +0 -0
  46. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/userfunc.py +0 -0
  47. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/utils.py +0 -0
  48. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/validation/__init__.py +0 -0
  49. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/validation/deep.py +0 -0
  50. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/validation/diagnostics.py +0 -0
  51. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/validation/discovery.py +0 -0
  52. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/validation/loader.py +0 -0
  53. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/validation/semantic.py +0 -0
  54. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/validation/validate.py +0 -0
  55. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/warnings.py +0 -0
  56. {pytest_httpchain-0.19.0 → pytest_httpchain-0.20.0}/src/pytest_httpchain/wire_codec.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-httpchain
3
- Version: 0.19.0
3
+ Version: 0.20.0
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
@@ -17,7 +17,7 @@ Classifier: Topic :: Software Development :: Testing
17
17
  Classifier: Typing :: Typed
18
18
  Requires-Dist: attrs>=22.2.0
19
19
  Requires-Dist: deepmerge>=2.0
20
- Requires-Dist: graphql-core>=3.0.0
20
+ Requires-Dist: graphql-core>=3.2.10
21
21
  Requires-Dist: httpx[http2]>=0.28.0
22
22
  Requires-Dist: iniconfig>=1.0.1
23
23
  Requires-Dist: jmespath>=1.0.0
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "pytest-httpchain"
3
- version = "0.19.0"
3
+ version = "0.20.0"
4
4
  description = "pytest plugin for HTTP testing using JSON files"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
7
7
  dependencies = [
8
8
  "attrs>=22.2.0",
9
9
  "deepmerge>=2.0",
10
- "graphql-core>=3.0.0",
10
+ "graphql-core>=3.2.10",
11
11
  "httpx[http2]>=0.28.0",
12
12
  "iniconfig>=1.0.1",
13
13
  "jmespath>=1.0.0",
@@ -63,7 +63,7 @@ dev = [
63
63
  "flask-httpauth>=4.8.0",
64
64
  "import-linter>=2.0",
65
65
  "ruff>=0.12.1",
66
- "ty>=0.0.84",
66
+ "ty>=0.0.100",
67
67
  "coverage[toml]>=7.10",
68
68
  "pytest-datadir>=1.7.2",
69
69
  "pytest-order>=1.3.0",
@@ -125,7 +125,8 @@ include = ["tests/**"]
125
125
  [tool.ty.overrides.rules]
126
126
  invalid-argument-type = "ignore"
127
127
  unknown-argument = "ignore"
128
- unresolved-attribute = "ignore"
128
+ missing-attribute = "ignore"
129
+ missing-union-attribute = "ignore"
129
130
  not-subscriptable = "ignore"
130
131
  missing-argument = "ignore"
131
132
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytest-httpchain"
3
- version = "0.19.0"
3
+ version = "0.20.0"
4
4
  description = "pytest plugin for HTTP testing using JSON files"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -10,7 +10,13 @@ dependencies = [
10
10
  # (body_schema): the floor jsonschema 4.18.0 itself requires.
11
11
  "attrs>=22.2.0",
12
12
  "deepmerge>=2.0",
13
- "graphql-core>=3.0.0",
13
+ # 3.2.10 is the first release that parses a description on an operation,
14
+ # a fragment or a variable, as every final release after it does: below
15
+ # it, a query holding one loads or not by the version installed. (The
16
+ # 3.3.0 pre-releases before 3.3.0a13, which `>=` admits once pre-releases
17
+ # are allowed, do not.) Not 3.3: graphene, graphql-relay and sgqlc require
18
+ # a graphql-core below it.
19
+ "graphql-core>=3.2.10",
14
20
  # 0.28.0 is the first release that takes a socks5h:// proxy, which
15
21
  # client.proxy accepts. (0.27.0 also percent-encoded a `\` in a URL path,
16
22
  # `/a%5Cb`, so a URL the plugin sends as written did not reach the server
@@ -65,7 +71,12 @@ dev = [
65
71
  "flask-httpauth>=4.8.0",
66
72
  "import-linter>=2.0",
67
73
  "ruff>=0.12.1",
68
- "ty>=0.0.84",
74
+ # 0.0.100 renamed the rules that [tool.ty.overrides.rules] and the
75
+ # `ty: ignore[...]` comments in src/ name: unresolved-attribute became
76
+ # missing-attribute (its union case split out as missing-union-attribute)
77
+ # and invalid-{method,attribute}-override became incompatible-...-override.
78
+ # An older ty does not know the new names, so `ty check` fails on it.
79
+ "ty>=0.0.100",
69
80
  "coverage[toml]>=7.10", # `patch = ["subprocess"]` needs 7.10
70
81
 
71
82
  "pytest-datadir>=1.7.2",
@@ -144,7 +155,8 @@ include = ["tests/**"]
144
155
  [tool.ty.overrides.rules]
145
156
  invalid-argument-type = "ignore"
146
157
  unknown-argument = "ignore"
147
- unresolved-attribute = "ignore"
158
+ missing-attribute = "ignore"
159
+ missing-union-attribute = "ignore"
148
160
  not-subscriptable = "ignore"
149
161
  missing-argument = "ignore"
150
162
 
@@ -246,7 +246,7 @@ def _error_request(e: Exception) -> httpx.Request | None:
246
246
  getattr with a default.
247
247
  """
248
248
  try:
249
- request = e.request # ty: ignore[unresolved-attribute]
249
+ request = e.request # ty: ignore[missing-attribute]
250
250
  except (AttributeError, RuntimeError):
251
251
  return None
252
252
  return request if isinstance(request, httpx.Request) else None
@@ -24,7 +24,75 @@ from pytest_httpchain.models import Scenario
24
24
  from pytest_httpchain.schema import build_schema
25
25
  from pytest_httpchain.validation import DiagnosticCode, DiscoveryError, ValidateResult, load_scenario, load_scenario_json, validate_paths
26
26
 
27
- app = typer.Typer(no_args_is_help=True)
27
+
28
+ def _hide_flag_value_types(command: typer.core.TyperCommand | typer.core.TyperGroup, ctx: typer.Context) -> None:
29
+ """Have the command's help list its flags with no value type beside them.
30
+
31
+ typer 0.29.0 and 0.29.1 (the newest when this was written) list a value
32
+ type beside every option, a flag included: ``--force <bool>``, even
33
+ ``--help <bool>``. A flag takes no value (``--force true`` reads ``true``
34
+ as the next argument), and typer up to 0.28 listed none. What 0.29 lists
35
+ is an option's metavar when it has one, so each flag without one is given
36
+ an empty one; typer up to 0.28 shows a flag's metavar nowhere. The flags
37
+ are the command's own and the ones typer adds (--help, the completion
38
+ options), which no declaration here reaches. Only help reads a flag's
39
+ metavar (an error names an option by its names), so a command whose help
40
+ was drawn parses as it did before.
41
+
42
+ Delete this, the classes below and `_Typer`, making the apps plain
43
+ ``typer.Typer`` again (_OwnOptionsFirst then derives from
44
+ typer.core.TyperCommand), once no typer the ``typer>=`` requirement admits
45
+ lists a type for a flag; the CLI's test of every command's help goes red
46
+ on one that does.
47
+ """
48
+ for param in command.get_params(ctx):
49
+ if getattr(param, "is_flag", False) and param.metavar is None:
50
+ param.metavar = ""
51
+
52
+
53
+ # The classes every command and group of this CLI is made with, for the help
54
+ # they draw. typer.Context is the context typer makes; the base names the
55
+ # click Context typer vendors privately.
56
+ class _Command(typer.core.TyperCommand):
57
+ def get_help(self, ctx: typer.Context) -> str: # ty: ignore[incompatible-method-override]
58
+ _hide_flag_value_types(self, ctx)
59
+ return super().get_help(ctx)
60
+
61
+ def parse_args(self, ctx: typer.Context, args: list[str]) -> list[str]: # ty: ignore[incompatible-method-override]
62
+ """A value an option refuses is reported in the same words on every
63
+ typer. typer 0.29 converts values through pydantic, which puts
64
+ "Value error, " before what a check that raised ValueError said:
65
+ ``--format xml`` was "Value error, 'xml' is not one of 'text',
66
+ 'json'.", where typer up to 0.28 says the check's words alone, as
67
+ click does. The CLI's options that take a value are all on its
68
+ commands."""
69
+ try:
70
+ return super().parse_args(ctx, args)
71
+ except typer.BadParameter as e:
72
+ e.message = e.message.removeprefix("Value error, ")
73
+ raise
74
+
75
+
76
+ class _Group(typer.core.TyperGroup):
77
+ def get_help(self, ctx: typer.Context) -> str: # ty: ignore[incompatible-method-override]
78
+ _hide_flag_value_types(self, ctx)
79
+ return super().get_help(ctx)
80
+
81
+
82
+ class _Typer(typer.Typer):
83
+ """An app whose group and commands are made with the classes above unless
84
+ a ``cls=`` says otherwise: typer has no setting for an app's default
85
+ classes, and a command made with typer's own would list `<bool>` again on
86
+ typer 0.29."""
87
+
88
+ def __init__(self, *, cls: type[typer.core.TyperGroup] | None = _Group, **kwargs) -> None:
89
+ super().__init__(cls=cls, **kwargs)
90
+
91
+ def command(self, name: str | None = None, *, cls: type[typer.core.TyperCommand] | None = _Command, **kwargs):
92
+ return super().command(name, cls=cls, **kwargs)
93
+
94
+
95
+ app = _Typer(no_args_is_help=True)
28
96
 
29
97
 
30
98
  class OutputFormat(StrEnum):
@@ -37,7 +105,32 @@ class GraphDirection(StrEnum):
37
105
  LR = "LR"
38
106
 
39
107
 
40
- RefParentTraversalDepth = Annotated[int, typer.Option(help="Maximum $ref parent directory traversal depth.")]
108
+ def _depth_option(value: str | int) -> int:
109
+ """The depth as Python's ``int()`` reads it, as pytest reads the
110
+ ``httpchain_ref_parent_traversal_depth`` ini option and typer did up to
111
+ 0.28, with the CLI's own error. typer 0.29 converts an ``int`` through
112
+ pydantic, which takes ``3.0`` and refuses ``3``; a parser is given the
113
+ word as typed (and the default, 3) on every typer, and the error it
114
+ raises, not being a ValueError, reaches click unchanged.
115
+
116
+ A depth below 0 is refused, as the ini option's is ("must be
117
+ non-negative"): it counts parent directories, and with one the resolver
118
+ refused every file reference, even one beside the scenario, as
119
+ "exceeds maximum parent traversal depth of -1"."""
120
+ try:
121
+ depth = int(value)
122
+ except ValueError:
123
+ raise typer.BadParameter(f"{value!r} is not a valid integer.") from None
124
+ if depth < 0:
125
+ raise typer.BadParameter(f"{value!r} must be non-negative.")
126
+ return depth
127
+
128
+
129
+ # What --help names the type after up to typer 0.28 (0.29 names the
130
+ # annotation): <int> on 0.27 and 0.28 as before, INT where 0.26 wrote INTEGER.
131
+ _depth_option.__name__ = "int"
132
+
133
+ RefParentTraversalDepth = Annotated[int, typer.Option(help="Maximum $ref parent directory traversal depth.", parser=_depth_option)]
41
134
  RootPath = Annotated[Path | None, typer.Option("--root-path", help="Directory that constrains $ref resolution (default: the rootdir pytest would use).")]
42
135
  OutputFormatOption = Annotated[OutputFormat, typer.Option("--format", help="Output format: human-readable text or machine-readable JSON.")]
43
136
 
@@ -311,11 +404,11 @@ def graph(
311
404
  typer.echo(_to_mermaid(flow, direction.value))
312
405
 
313
406
 
314
- import_app = typer.Typer(no_args_is_help=True, help="Write a starter scenario from recorded traffic: a HAR file or curl commands.")
407
+ import_app = _Typer(no_args_is_help=True, help="Write a starter scenario from recorded traffic: a HAR file or curl commands.")
315
408
  app.add_typer(import_app, name="import")
316
409
 
317
410
 
318
- class _OwnOptionsFirst(typer.core.TyperCommand):
411
+ class _OwnOptionsFirst(_Command):
319
412
  """A command whose own options come first: from the first word that is
320
413
  none of them on, every word is its argument's, as after a ``--``. For
321
414
  ``import curl``, whose argument is a curl command: told to leave options
@@ -323,9 +416,7 @@ class _OwnOptionsFirst(typer.core.TyperCommand):
323
416
  (``-sSL -o page.html https://...``) as the import's own, and write the
324
417
  scenario where curl was to write its answer."""
325
418
 
326
- # typer.Context is the context typer makes; the base names the click
327
- # Context typer vendors privately.
328
- def parse_args(self, ctx: typer.Context, args: list[str]) -> list[str]: # ty: ignore[invalid-method-override]
419
+ def parse_args(self, ctx: typer.Context, args: list[str]) -> list[str]:
329
420
  own = {name: param for param in self.get_params(ctx) if param.param_type_name == "option" for name in (*param.opts, *param.secondary_opts)}
330
421
  index = 0
331
422
  while index < len(args) and args[index] != "--":
@@ -348,7 +439,17 @@ class _OwnOptionsFirst(typer.core.TyperCommand):
348
439
  return super().parse_args(ctx, args)
349
440
 
350
441
 
351
- OutputPathOption = Annotated[Path | None, typer.Option("--output", "-o", help="Write the scenario to this file instead of stdout.", dir_okay=False)]
442
+ def _output_option(value: Path | None) -> Path | None:
443
+ """An empty --output is a usage error on every typer: 0.29 refuses it as
444
+ the directory ``.`` it reads it as, and up to 0.28 it reached the import
445
+ as that directory, to fail there. (A ``.`` typed never gets here: typer
446
+ refuses a directory.)"""
447
+ if value == Path():
448
+ raise typer.BadParameter("an empty path names no file")
449
+ return value
450
+
451
+
452
+ OutputPathOption = Annotated[Path | None, typer.Option("--output", "-o", help="Write the scenario to this file instead of stdout.", dir_okay=False, callback=_output_option)]
352
453
  ForceOption = Annotated[bool, typer.Option("--force", help="Overwrite the --output file if it exists.")]
353
454
 
354
455
 
@@ -143,17 +143,17 @@ def create_test_class(
143
143
  stage_method = pytest.mark.parametrize(",".join(param_names), param_values, ids=step.ids or None)(stage_method)
144
144
 
145
145
  all_fixtures = ["self", *dict.fromkeys(all_param_names + stage.fixtures + scenario.fixtures)]
146
- stage_method.__signature__ = inspect.Signature([inspect.Parameter(name, inspect.Parameter.POSITIONAL_OR_KEYWORD) for name in all_fixtures]) # ty: ignore[unresolved-attribute]
146
+ stage_method.__signature__ = inspect.Signature([inspect.Parameter(name, inspect.Parameter.POSITIONAL_OR_KEYWORD) for name in all_fixtures]) # ty: ignore[missing-attribute]
147
147
 
148
148
  # Read by the chain-contiguity hook to restore stage order.
149
- stage_method._httpchain_stage_index = i # ty: ignore[unresolved-attribute]
149
+ stage_method._httpchain_stage_index = i # ty: ignore[missing-attribute]
150
150
 
151
151
  # The generated name ("test NN - <stage>") satisfies pytest's default
152
152
  # `python_functions` only via its bare "test" prefix rule — the space
153
153
  # defeats every glob form, so a narrowed `python_functions = test_*`
154
154
  # would collect ZERO stages and leave CI green. __test__ is honored by
155
155
  # pytest's istestfunction regardless of the name filter.
156
- stage_method.__test__ = True # ty: ignore[unresolved-attribute]
156
+ stage_method.__test__ = True # ty: ignore[missing-attribute]
157
157
 
158
158
  for mark_str in stage.marks:
159
159
  try:
@@ -15,7 +15,10 @@ them in the scenario dialect, one stage each, in order:
15
15
  - a body becomes the form its Content-Type names: ``json``, ``form``,
16
16
  ``multipart``, else the raw ``text`` (``base64`` or ``binary`` where the
17
17
  source gave bytes or a file); a JSON or form body a mapping would not send
18
- as it was sent is ``text`` too;
18
+ as it was sent is ``text`` too; a JSON body that is a GraphQL request, one
19
+ a ``graphql`` body sends as it was sent and whose query that body's check
20
+ passes, is a ``graphql`` body, so the query is checked as the scenario
21
+ loads (`_Builder.graphql`);
19
22
  - Basic and Bearer credentials become the ``basic`` and ``bearer`` auth
20
23
  shorthands, the scenario's ``auth`` when every request carries the same.
21
24
 
@@ -56,8 +59,12 @@ from pathlib import Path
56
59
  from typing import Any
57
60
  from urllib.parse import parse_qsl, unquote, unquote_plus, urlsplit
58
61
 
62
+ from pydantic import ValidationError
63
+
59
64
  from pytest_httpchain.errors import HttpChainError
60
65
  from pytest_httpchain.jsonref import REF_KEYS
66
+ from pytest_httpchain.models import GraphQLBody
67
+ from pytest_httpchain.models.types import GraphQLOperationError
61
68
  from pytest_httpchain.redaction import DEFAULT_REDACTION, REDACTED, Redaction
62
69
  from pytest_httpchain.templates import TEMPLATE_BUILTINS, contains_template, escape, unescape
63
70
  from pytest_httpchain.validation import ValidateResult, validate_scenario
@@ -596,6 +603,43 @@ class _Builder:
596
603
 
597
604
  return self._json(value, escape, secret)
598
605
 
606
+ def graphql(self, value: Any, stage: str) -> dict[str, Any] | None:
607
+ """A JSON body that is a GraphQL request as a ``graphql`` body, else
608
+ None, for a ``json`` one.
609
+
610
+ Only a body a ``graphql`` body sends as it was sent: text under
611
+ ``query``, an object under ``variables``, text under
612
+ ``operationName`` if any, and nothing else, which are what one sends
613
+ (``variables`` always, ``operationName`` when declared). Any other, a
614
+ request without ``variables`` or with a null, ``extensions``, a batch,
615
+ stays the ``json`` body it was, and so does one the ``graphql`` body's
616
+ check refuses: a ``query`` that is no GraphQL (an API of its own may
617
+ name a field so) or none it takes, sent as recorded. Where it refuses
618
+ the operations (several and none named, a name naming none, an
619
+ anonymous one beside another, two of one name: `GraphQLOperationError`,
620
+ which a server refuses too, whatever its version), a note says why. The
621
+ variables are what a ``json`` body's would be, their secrets
622
+ placeholders."""
623
+ if not (isinstance(value, dict) and set(value) <= {"query", "variables", "operationName"}):
624
+ return None
625
+ query, variables, name = value.get("query"), value.get("variables"), value.get("operationName", "")
626
+ if not (isinstance(query, str) and isinstance(variables, dict) and isinstance(name, str)):
627
+ return None
628
+ body: dict[str, Any] = {"query": escape(query)}
629
+ if "operationName" in value:
630
+ body["operation_name"] = escape(name)
631
+ try:
632
+ # Checked before the variables make placeholders: a json body
633
+ # would make them again.
634
+ GraphQLBody.model_validate({"graphql": body})
635
+ except ValidationError as e:
636
+ error = e.errors()[0]
637
+ if isinstance(error.get("ctx", {}).get("error"), GraphQLOperationError):
638
+ reason = error["msg"].removeprefix("Value error, ")
639
+ self.notes.append(f"Stage {stage!r}: its GraphQL request is written as a json body, sent as recorded: as a graphql body it would not load: {reason}")
640
+ return None
641
+ return {"query": body["query"], "variables": self.json_value(variables, stage)} | ({"operation_name": body["operation_name"]} if "operation_name" in body else {})
642
+
599
643
  def json_text(self, text: str, value: Any, stage: str) -> str:
600
644
  """A JSON body as ``text``, for one a ``json`` body cannot hold (a
601
645
  member named ``$ref``): the text as recorded, or, with secrets in it,
@@ -708,6 +752,9 @@ class _Builder:
708
752
  depth, reference = _json_shape(value)
709
753
  if depth <= _MAX_JSON_DEPTH:
710
754
  if reference is None:
755
+ # A graphql body sends JSON, as a json one does.
756
+ if (graphql := self.graphql(value, stage)) is not None:
757
+ return {"graphql": graphql}, exact == _JSON
711
758
  return {"json": self.json_value(value, stage)}, exact == _JSON
712
759
  self.notes.append(
713
760
  f"Stage {stage!r}: its JSON body is written as text: a json body could not hold its member {reference!r},"
@@ -50,6 +50,7 @@ from pytest_httpchain.models.types import (
50
50
  Base64String,
51
51
  BaseUrlStr,
52
52
  FunctionImportName,
53
+ GraphQLName,
53
54
  GraphQLQuery,
54
55
  HttpMethodToken,
55
56
  HttpUrlReferenceStr,
@@ -82,8 +83,10 @@ from pytest_httpchain.models.types import (
82
83
  VariableName,
83
84
  XMLString,
84
85
  as_rendered,
86
+ check_graphql_operation,
85
87
  convert_namespace_items_to_dict,
86
88
  convert_namespace_to_dict,
89
+ parses_as_graphql,
87
90
  refuse_escaped_braces,
88
91
  regex_group,
89
92
  validate_function_import_name,
@@ -449,7 +452,7 @@ with _suppress_field_shadow_warning("json"):
449
452
  class JsonBody(StrictModel):
450
453
  # "json" is the domain's name for the field, as the suppressed pydantic
451
454
  # warning says: it shadows BaseModel's deprecated json() method.
452
- json: Annotated[JsonValue, BeforeValidator(convert_namespace_to_dict)] = Field(description="JSON data to send.") # ty: ignore[invalid-attribute-override]
455
+ json: Annotated[JsonValue, BeforeValidator(convert_namespace_to_dict)] = Field(description="JSON data to send.") # ty: ignore[incompatible-attribute-override]
453
456
 
454
457
 
455
458
  class XmlBody(StrictModel):
@@ -602,6 +605,27 @@ class MultipartBody(StrictModel):
602
605
  class GraphQL(StrictModel):
603
606
  query: GraphQLQuery | PartialTemplateStr = Field(description="GraphQL query string.", examples=["query { user { id name } }", "{{ graphql_query }}"])
604
607
  variables: NamespaceOrDict | PartialTemplateStr = Field(default_factory=dict, description="GraphQL query variables.")
608
+ operation_name: GraphQLName | PartialTemplateStr | None = Field(
609
+ default=None,
610
+ description="The operation of the query to execute, sent as operationName: required when the query defines several, optional when it defines one.",
611
+ examples=["GetUser", "{{ operation }}"],
612
+ )
613
+
614
+ @model_validator(mode="after")
615
+ def _operation_is_in_the_query(self, info: ValidationInfo) -> Self:
616
+ """A query of several operations names the one to execute, and a
617
+ name names one of them, as a server requires: checked at load for a
618
+ literal query and name, the query's escapes rendered (`as_rendered`),
619
+ and once rendered when a template writes either. Rendered text is
620
+ final, braces an escape left in it included, so it is checked then
621
+ unless it is no GraphQL at all (text the template branch took)."""
622
+ if info.context is RENDERED:
623
+ if not parses_as_graphql(self.query):
624
+ return self
625
+ elif contains_template([self.query, self.operation_name]):
626
+ return self
627
+ check_graphql_operation(as_rendered(self.query, info), self.operation_name)
628
+ return self
605
629
 
606
630
 
607
631
  class GraphQLBody(StrictModel):
@@ -821,7 +845,7 @@ with _suppress_field_shadow_warning("schema"):
821
845
  # stands for the dict it was declared as: converted all the way down, as
822
846
  # a schema is plain JSON. Ahead of the union, keeping its member tags in
823
847
  # pydantic's error locations.
824
- schema: Annotated[ # ty: ignore[invalid-attribute-override] (shadows BaseModel.schema(), deprecated: the domain's name)
848
+ schema: Annotated[ # ty: ignore[incompatible-attribute-override] (shadows BaseModel.schema(), deprecated: the domain's name)
825
849
  JSONSchemaInline | SchemaFileRefStr | PartialTemplateStr | None,
826
850
  BeforeValidator(convert_namespace_to_dict),
827
851
  BeforeValidator(refuse_escaped_braces("A schema file reference")),
@@ -5,6 +5,7 @@ objects readable by attribute and by key in templates and JSON-serializable in
5
5
  bodies."""
6
6
 
7
7
  import base64
8
+ import functools
8
9
  import keyword
9
10
  import re
10
11
  import threading
@@ -238,7 +239,184 @@ def regex_group(pattern: re.Pattern[str], group: int | str | None) -> int | str:
238
239
 
239
240
  validate_xml = create_string_validator(xml.etree.ElementTree.fromstring, "Invalid XML")
240
241
 
241
- validate_graphql_query = create_string_validator(graphql.parse, "Invalid GraphQL query")
242
+
243
+ class GraphQLOperationError(ValueError):
244
+ """A GraphQL request's operations as no server executes them, whichever
245
+ is named: an anonymous one beside another, two of one name, several and
246
+ none named, a name naming none. GraphQL all the same, unlike a syntax
247
+ error or a type definition: `import har|curl` tells the user so when it
248
+ keeps such a recorded request a json body."""
249
+
250
+
251
+ # How deep graphql-core 3.2.14 and 3.3.2 let a document nest: they count
252
+ # selection sets, list and object values and list types together, and refuse
253
+ # a document where that count passes 200 (graphql.language.parser's
254
+ # MAX_NESTING_DEPTH, absent before them).
255
+ _GRAPHQL_NESTING = (graphql.language.SelectionSetNode, graphql.language.ListValueNode, graphql.language.ObjectValueNode, graphql.language.ListTypeNode)
256
+ _GRAPHQL_MAX_NESTING = 200
257
+
258
+
259
+ @functools.cache
260
+ def _graphql_child_keys(node_type: type[graphql.language.Node]) -> tuple[str, ...]:
261
+ """The fields of a GraphQL AST node type that may hold nodes: its
262
+ ``keys`` but the location."""
263
+ return tuple(key for key in node_type.keys if key != "loc")
264
+
265
+
266
+ def _graphql_children(node: Any) -> Iterator[Any]:
267
+ """The nodes ``node`` holds, directly or in a list, but names: a name
268
+ holds nothing, and a third of a document's nodes are names."""
269
+ for key in _graphql_child_keys(type(node)):
270
+ child = getattr(node, key, None)
271
+ for item in child if isinstance(child, list | tuple) else (child,):
272
+ if isinstance(item, graphql.language.Node) and not isinstance(item, graphql.language.NameNode):
273
+ yield item
274
+
275
+
276
+ def _parse_graphql_query(text: str) -> None:
277
+ """Parse a GraphQL request's document, or raise why it is not one. One
278
+ grammar, whichever graphql-core is installed: the document holds
279
+ operations and fragments, at least one operation; a selection set
280
+ selects something; and the document nests at most 200 levels deep.
281
+
282
+ A request is executed, so its document is what a server executes, and
283
+ what every server refuses in one is refused here, in the server's words:
284
+ an anonymous operation beside another, two operations of one name, a
285
+ type-system definition (``type``, ``schema``, ``directive``...) in it is
286
+ refused by every server ("... is not executable"), and so is a document
287
+ of fragments alone, which holds no operation to execute (graphql-core's
288
+ validation: "Fragment 'F' is never used."). Refusing them here
289
+ also keeps out the type-system syntax graphql-core 3.3 parses and 3.2
290
+ does not (``directive @d @e on FIELD``).
291
+
292
+ A selection set with nothing in it (``{ user { } }``, ``query Q { }``)
293
+ is a syntax error to graphql-core up to 3.3.1, and to a server built on
294
+ any of them. From 3.3.2 ``graphql.parse`` takes it by default,
295
+ after a proposed change to the specification (graphql-spec pull request
296
+ 1227), so the same scenario would load or not by the version installed:
297
+ it is refused here, from what was parsed. The parser's own switch
298
+ (``allow_empty_selection_sets=False``) is not the way: versions before
299
+ 3.3.2 do not have it, and it is deprecated, to be removed. An input
300
+ object or a list with nothing in it (``f(arg: {})``, ``[]``) is a value,
301
+ not a selection set, and stays valid.
302
+
303
+ Nesting the other way round: 3.2.14 and 3.3.2 refuse a document nested
304
+ more than 200 levels deep (`_GRAPHQL_NESTING`), where 3.3.1 and older
305
+ parse one until the interpreter's recursion limit, some 240 levels of
306
+ selection sets. So it is counted here as those versions count it, and
307
+ refused on every version past 200. Only the parser can refuse one deeper
308
+ still, by that limit or its own.
309
+
310
+ Both are read from the whole document: each node is followed into every
311
+ node it holds (`_graphql_children`, by its ``keys``, the same on every
312
+ version), with how many of the nesting kinds hold it. The nodes wait on a
313
+ list, not on the call stack, so nesting the parser got through costs no
314
+ frames here.
315
+ """
316
+ document = graphql.parse(text)
317
+ # The grammar's own refusals first (what some versions' parser refuses
318
+ # itself), then the definitions, then the operations: a document failing
319
+ # several is refused for the same one on every version.
320
+ pending: list[tuple[Any, int]] = [(document, 0)]
321
+ while pending:
322
+ node, depth = pending.pop()
323
+ if isinstance(node, _GRAPHQL_NESTING):
324
+ depth += 1
325
+ if depth > _GRAPHQL_MAX_NESTING:
326
+ raise graphql.GraphQLSyntaxError(node.loc.source, node.loc.start, f"Document is nested more than {_GRAPHQL_MAX_NESTING} levels deep.")
327
+ if isinstance(node, graphql.language.SelectionSetNode) and not node.selections:
328
+ raise graphql.GraphQLSyntaxError(node.loc.source, node.loc.start, "A selection set must not be empty.")
329
+ pending.extend((child, depth) for child in _graphql_children(node))
330
+ for definition in document.definitions:
331
+ if not isinstance(definition, graphql.language.OperationDefinitionNode | graphql.language.FragmentDefinitionNode):
332
+ raise graphql.GraphQLError(f"The {definition.kind} is not executable: a request holds operations and fragments.", definition)
333
+ operations = [definition for definition in document.definitions if isinstance(definition, graphql.language.OperationDefinitionNode)]
334
+ if not operations:
335
+ raise graphql.GraphQLError("A request holds at least one operation: fragments alone execute nothing.")
336
+ _tell_operations_apart(operations)
337
+
338
+
339
+ def _tell_operations_apart(operations: list[Any]) -> None:
340
+ """A `GraphQLOperationError` where a server cannot tell the operations
341
+ apart, whatever a request names: an anonymous one beside another, two of
342
+ one name (graphql's LoneAnonymousOperation and UniqueOperationNames)."""
343
+ named: set[str] = set()
344
+ for operation in operations:
345
+ if operation.name is None:
346
+ if len(operations) > 1:
347
+ raise GraphQLOperationError("This anonymous operation must be the only defined operation.")
348
+ elif operation.name.value in named:
349
+ raise GraphQLOperationError(f"There can be only one operation named {operation.name.value!r}.")
350
+ else:
351
+ named.add(operation.name.value)
352
+
353
+
354
+ def _printable(text: str) -> str:
355
+ """``text`` as an error message may hold it: a lone surrogate, which a
356
+ parser's message can quote from the query, escaped, as pydantic cannot
357
+ encode one."""
358
+ return text.encode("utf-8", "backslashreplace").decode("utf-8")
359
+
360
+
361
+ def validate_graphql_query(v: str, info: ValidationInfo) -> str:
362
+ """A GraphQL request's query, judged as the text it is used as
363
+ (`as_rendered`) and kept as written, or a ValueError naming why it is
364
+ none after "Invalid GraphQL query: ", in the parser's or the rule's
365
+ words. Only an error's ``message``, never the error printed: graphql-core
366
+ before 3.2.14 and 3.3.2 fails printing the location of one after a line
367
+ separator Python counts and its printer does not (U+2028, a form feed)."""
368
+ try:
369
+ _parse_graphql_query(as_rendered(v, info))
370
+ except GraphQLOperationError as e:
371
+ raise GraphQLOperationError(f"Invalid GraphQL query: {e}") from e
372
+ except graphql.GraphQLError as e:
373
+ raise ValueError(f"Invalid GraphQL query: {_printable(e.message)}") from e
374
+ except RecursionError as e:
375
+ raise ValueError("Invalid GraphQL query: Document is nested too deeply to parse.") from e
376
+ except Exception as e:
377
+ # graphql-core 3.2.10 to 3.2.13's lexer runs off the text it reads
378
+ # on some inputs (a string ending in a lone backslash): an
379
+ # IndexError, which is no GraphQL either.
380
+ raise ValueError("Invalid GraphQL query: the parser could not read it") from e
381
+ return v
382
+
383
+
384
+ # A GraphQL name, which an operation's is (graphql-spec, Names).
385
+ _GRAPHQL_NAME = re.compile(r"[_A-Za-z][_0-9A-Za-z]*")
386
+
387
+
388
+ def validate_graphql_name(v: str) -> str:
389
+ """An operation's name, or a `GraphQLOperationError`: one no operation
390
+ can have names none, which a server refuses as it refuses any unknown."""
391
+ if not _GRAPHQL_NAME.fullmatch(v):
392
+ raise GraphQLOperationError(f"Invalid GraphQL operation name {v!r}: a name is ASCII letters, digits and underscores, not starting with a digit")
393
+ return v
394
+
395
+
396
+ def check_graphql_operation(query: str, operation_name: str | None) -> None:
397
+ """Whether a server finds an operation to execute in ``query``, a
398
+ document `validate_graphql_query` passed, given ``operation_name``, as
399
+ GraphQL's GetOperation finds it, or a ValueError saying why it finds
400
+ none: a query of several operations names the one to execute, and the
401
+ name given is one of them.
402
+
403
+ Shared by the GraphQL body's model, which checks a literal query and
404
+ name at load and again once a template rendered either. Rendered text
405
+ the query's own check did not read (braces an escape left in it) is
406
+ held to its operation rules here too."""
407
+ operations = [definition for definition in graphql.parse(query).definitions if isinstance(definition, graphql.language.OperationDefinitionNode)]
408
+ try:
409
+ _tell_operations_apart(operations)
410
+ except GraphQLOperationError as e:
411
+ raise GraphQLOperationError(f"Invalid GraphQL query: {e}") from e
412
+ names = [operation.name.value for operation in operations if operation.name is not None]
413
+ defined = ", ".join(repr(operation.name.value) if operation.name is not None else "an anonymous one" for operation in operations) or "none"
414
+ if operation_name is None:
415
+ if len(operations) > 1:
416
+ raise GraphQLOperationError(f"the query defines several operations ({defined}): name the one to execute in operation_name")
417
+ elif operation_name not in names:
418
+ raise GraphQLOperationError(f"operation_name {operation_name!r} names no operation in the query (it defines {defined})")
419
+
242
420
 
243
421
  validate_base64 = create_string_validator(lambda v: base64.b64decode(v, validate=True), "Invalid base64 encoding")
244
422
 
@@ -587,6 +765,18 @@ RegexGroupNumber = Annotated[StrictInt, Field(ge=0)]
587
765
  RegexGroupName = Annotated[str, AfterValidator(validate_regex_group_name)]
588
766
  XMLString = Annotated[str, AfterValidator(validate_xml)]
589
767
  GraphQLQuery = Annotated[str, AfterValidator(validate_graphql_query)]
768
+
769
+
770
+ def parses_as_graphql(text: str) -> bool:
771
+ """Whether graphql-core parses ``text`` at all."""
772
+ try:
773
+ graphql.parse(text)
774
+ except Exception: # graphql-core 3.2.10 to 3.2.13 raise IndexError on some
775
+ return False
776
+ return True
777
+
778
+
779
+ GraphQLName = Annotated[str, AfterValidator(validate_graphql_name)]
590
780
  TemplateExpression = Annotated[str, AfterValidator(validate_template_expression)]
591
781
  PartialTemplateStr = Annotated[str, AfterValidator(validate_partial_template_str)]
592
782
  # The template branch beside `BaseUrlStr` and `ProxyUrlStr`: a URL they refuse
@@ -680,7 +680,9 @@ def build_request_kwargs(
680
680
  body_content_type = "application/msgpack"
681
681
 
682
682
  case GraphQLBody(graphql=gql):
683
- request_kwargs["json"] = {"query": gql.query, "variables": gql.variables}
683
+ # operationName only when declared: a scenario without one sends
684
+ # what it always has.
685
+ request_kwargs["json"] = {"query": gql.query, "variables": gql.variables} | ({} if gql.operation_name is None else {"operationName": gql.operation_name})
684
686
 
685
687
  case FormBody(form=data):
686
688
  encoded = _encoded_binary_form(data)