schemathesis 3.39.16__py3-none-any.whl → 4.0.0__py3-none-any.whl

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 (255) hide show
  1. schemathesis/__init__.py +41 -79
  2. schemathesis/auths.py +111 -122
  3. schemathesis/checks.py +169 -60
  4. schemathesis/cli/__init__.py +15 -2117
  5. schemathesis/cli/commands/__init__.py +85 -0
  6. schemathesis/cli/commands/data.py +10 -0
  7. schemathesis/cli/commands/run/__init__.py +590 -0
  8. schemathesis/cli/commands/run/context.py +204 -0
  9. schemathesis/cli/commands/run/events.py +60 -0
  10. schemathesis/cli/commands/run/executor.py +157 -0
  11. schemathesis/cli/commands/run/filters.py +53 -0
  12. schemathesis/cli/commands/run/handlers/__init__.py +46 -0
  13. schemathesis/cli/commands/run/handlers/base.py +18 -0
  14. schemathesis/cli/commands/run/handlers/cassettes.py +474 -0
  15. schemathesis/cli/commands/run/handlers/junitxml.py +55 -0
  16. schemathesis/cli/commands/run/handlers/output.py +1628 -0
  17. schemathesis/cli/commands/run/loaders.py +114 -0
  18. schemathesis/cli/commands/run/validation.py +246 -0
  19. schemathesis/cli/constants.py +5 -58
  20. schemathesis/cli/core.py +19 -0
  21. schemathesis/cli/ext/fs.py +16 -0
  22. schemathesis/cli/ext/groups.py +84 -0
  23. schemathesis/cli/{options.py → ext/options.py} +36 -34
  24. schemathesis/config/__init__.py +189 -0
  25. schemathesis/config/_auth.py +51 -0
  26. schemathesis/config/_checks.py +268 -0
  27. schemathesis/config/_diff_base.py +99 -0
  28. schemathesis/config/_env.py +21 -0
  29. schemathesis/config/_error.py +156 -0
  30. schemathesis/config/_generation.py +149 -0
  31. schemathesis/config/_health_check.py +24 -0
  32. schemathesis/config/_operations.py +327 -0
  33. schemathesis/config/_output.py +171 -0
  34. schemathesis/config/_parameters.py +19 -0
  35. schemathesis/config/_phases.py +187 -0
  36. schemathesis/config/_projects.py +527 -0
  37. schemathesis/config/_rate_limit.py +17 -0
  38. schemathesis/config/_report.py +120 -0
  39. schemathesis/config/_validator.py +9 -0
  40. schemathesis/config/_warnings.py +25 -0
  41. schemathesis/config/schema.json +885 -0
  42. schemathesis/core/__init__.py +67 -0
  43. schemathesis/core/compat.py +32 -0
  44. schemathesis/core/control.py +2 -0
  45. schemathesis/core/curl.py +58 -0
  46. schemathesis/core/deserialization.py +65 -0
  47. schemathesis/core/errors.py +459 -0
  48. schemathesis/core/failures.py +315 -0
  49. schemathesis/core/fs.py +19 -0
  50. schemathesis/core/hooks.py +20 -0
  51. schemathesis/core/loaders.py +104 -0
  52. schemathesis/core/marks.py +66 -0
  53. schemathesis/{transports/content_types.py → core/media_types.py} +14 -12
  54. schemathesis/core/output/__init__.py +46 -0
  55. schemathesis/core/output/sanitization.py +54 -0
  56. schemathesis/{throttling.py → core/rate_limit.py} +16 -17
  57. schemathesis/core/registries.py +31 -0
  58. schemathesis/core/transforms.py +113 -0
  59. schemathesis/core/transport.py +223 -0
  60. schemathesis/core/validation.py +54 -0
  61. schemathesis/core/version.py +7 -0
  62. schemathesis/engine/__init__.py +28 -0
  63. schemathesis/engine/context.py +118 -0
  64. schemathesis/engine/control.py +36 -0
  65. schemathesis/engine/core.py +169 -0
  66. schemathesis/engine/errors.py +464 -0
  67. schemathesis/engine/events.py +258 -0
  68. schemathesis/engine/phases/__init__.py +88 -0
  69. schemathesis/{runner → engine/phases}/probes.py +52 -68
  70. schemathesis/engine/phases/stateful/__init__.py +68 -0
  71. schemathesis/engine/phases/stateful/_executor.py +356 -0
  72. schemathesis/engine/phases/stateful/context.py +85 -0
  73. schemathesis/engine/phases/unit/__init__.py +212 -0
  74. schemathesis/engine/phases/unit/_executor.py +416 -0
  75. schemathesis/engine/phases/unit/_pool.py +82 -0
  76. schemathesis/engine/recorder.py +247 -0
  77. schemathesis/errors.py +43 -0
  78. schemathesis/filters.py +17 -98
  79. schemathesis/generation/__init__.py +5 -33
  80. schemathesis/generation/case.py +317 -0
  81. schemathesis/generation/coverage.py +282 -175
  82. schemathesis/generation/hypothesis/__init__.py +36 -0
  83. schemathesis/generation/hypothesis/builder.py +800 -0
  84. schemathesis/generation/{_hypothesis.py → hypothesis/examples.py} +2 -11
  85. schemathesis/generation/hypothesis/given.py +66 -0
  86. schemathesis/generation/hypothesis/reporting.py +14 -0
  87. schemathesis/generation/hypothesis/strategies.py +16 -0
  88. schemathesis/generation/meta.py +115 -0
  89. schemathesis/generation/metrics.py +93 -0
  90. schemathesis/generation/modes.py +20 -0
  91. schemathesis/generation/overrides.py +116 -0
  92. schemathesis/generation/stateful/__init__.py +37 -0
  93. schemathesis/generation/stateful/state_machine.py +278 -0
  94. schemathesis/graphql/__init__.py +15 -0
  95. schemathesis/graphql/checks.py +109 -0
  96. schemathesis/graphql/loaders.py +284 -0
  97. schemathesis/hooks.py +80 -101
  98. schemathesis/openapi/__init__.py +13 -0
  99. schemathesis/openapi/checks.py +455 -0
  100. schemathesis/openapi/generation/__init__.py +0 -0
  101. schemathesis/openapi/generation/filters.py +72 -0
  102. schemathesis/openapi/loaders.py +313 -0
  103. schemathesis/pytest/__init__.py +5 -0
  104. schemathesis/pytest/control_flow.py +7 -0
  105. schemathesis/pytest/lazy.py +281 -0
  106. schemathesis/pytest/loaders.py +36 -0
  107. schemathesis/{extra/pytest_plugin.py → pytest/plugin.py} +128 -108
  108. schemathesis/python/__init__.py +0 -0
  109. schemathesis/python/asgi.py +12 -0
  110. schemathesis/python/wsgi.py +12 -0
  111. schemathesis/schemas.py +537 -273
  112. schemathesis/specs/graphql/__init__.py +0 -1
  113. schemathesis/specs/graphql/_cache.py +1 -2
  114. schemathesis/specs/graphql/scalars.py +42 -6
  115. schemathesis/specs/graphql/schemas.py +141 -137
  116. schemathesis/specs/graphql/validation.py +11 -17
  117. schemathesis/specs/openapi/__init__.py +6 -1
  118. schemathesis/specs/openapi/_cache.py +1 -2
  119. schemathesis/specs/openapi/_hypothesis.py +142 -156
  120. schemathesis/specs/openapi/checks.py +368 -257
  121. schemathesis/specs/openapi/converter.py +4 -4
  122. schemathesis/specs/openapi/definitions.py +1 -1
  123. schemathesis/specs/openapi/examples.py +23 -21
  124. schemathesis/specs/openapi/expressions/__init__.py +31 -19
  125. schemathesis/specs/openapi/expressions/extractors.py +1 -4
  126. schemathesis/specs/openapi/expressions/lexer.py +1 -1
  127. schemathesis/specs/openapi/expressions/nodes.py +36 -41
  128. schemathesis/specs/openapi/expressions/parser.py +1 -1
  129. schemathesis/specs/openapi/formats.py +35 -7
  130. schemathesis/specs/openapi/media_types.py +53 -12
  131. schemathesis/specs/openapi/negative/__init__.py +7 -4
  132. schemathesis/specs/openapi/negative/mutations.py +6 -5
  133. schemathesis/specs/openapi/parameters.py +7 -10
  134. schemathesis/specs/openapi/patterns.py +94 -31
  135. schemathesis/specs/openapi/references.py +12 -53
  136. schemathesis/specs/openapi/schemas.py +233 -307
  137. schemathesis/specs/openapi/security.py +1 -1
  138. schemathesis/specs/openapi/serialization.py +12 -6
  139. schemathesis/specs/openapi/stateful/__init__.py +268 -133
  140. schemathesis/specs/openapi/stateful/control.py +87 -0
  141. schemathesis/specs/openapi/stateful/links.py +209 -0
  142. schemathesis/transport/__init__.py +142 -0
  143. schemathesis/transport/asgi.py +26 -0
  144. schemathesis/transport/prepare.py +124 -0
  145. schemathesis/transport/requests.py +244 -0
  146. schemathesis/{_xml.py → transport/serialization.py} +69 -11
  147. schemathesis/transport/wsgi.py +171 -0
  148. schemathesis-4.0.0.dist-info/METADATA +204 -0
  149. schemathesis-4.0.0.dist-info/RECORD +164 -0
  150. {schemathesis-3.39.16.dist-info → schemathesis-4.0.0.dist-info}/entry_points.txt +1 -1
  151. {schemathesis-3.39.16.dist-info → schemathesis-4.0.0.dist-info}/licenses/LICENSE +1 -1
  152. schemathesis/_compat.py +0 -74
  153. schemathesis/_dependency_versions.py +0 -19
  154. schemathesis/_hypothesis.py +0 -717
  155. schemathesis/_override.py +0 -50
  156. schemathesis/_patches.py +0 -21
  157. schemathesis/_rate_limiter.py +0 -7
  158. schemathesis/cli/callbacks.py +0 -466
  159. schemathesis/cli/cassettes.py +0 -561
  160. schemathesis/cli/context.py +0 -75
  161. schemathesis/cli/debug.py +0 -27
  162. schemathesis/cli/handlers.py +0 -19
  163. schemathesis/cli/junitxml.py +0 -124
  164. schemathesis/cli/output/__init__.py +0 -1
  165. schemathesis/cli/output/default.py +0 -920
  166. schemathesis/cli/output/short.py +0 -59
  167. schemathesis/cli/reporting.py +0 -79
  168. schemathesis/cli/sanitization.py +0 -26
  169. schemathesis/code_samples.py +0 -151
  170. schemathesis/constants.py +0 -54
  171. schemathesis/contrib/__init__.py +0 -11
  172. schemathesis/contrib/openapi/__init__.py +0 -11
  173. schemathesis/contrib/openapi/fill_missing_examples.py +0 -24
  174. schemathesis/contrib/openapi/formats/__init__.py +0 -9
  175. schemathesis/contrib/openapi/formats/uuid.py +0 -16
  176. schemathesis/contrib/unique_data.py +0 -41
  177. schemathesis/exceptions.py +0 -571
  178. schemathesis/experimental/__init__.py +0 -109
  179. schemathesis/extra/_aiohttp.py +0 -28
  180. schemathesis/extra/_flask.py +0 -13
  181. schemathesis/extra/_server.py +0 -18
  182. schemathesis/failures.py +0 -284
  183. schemathesis/fixups/__init__.py +0 -37
  184. schemathesis/fixups/fast_api.py +0 -41
  185. schemathesis/fixups/utf8_bom.py +0 -28
  186. schemathesis/generation/_methods.py +0 -44
  187. schemathesis/graphql.py +0 -3
  188. schemathesis/internal/__init__.py +0 -7
  189. schemathesis/internal/checks.py +0 -86
  190. schemathesis/internal/copy.py +0 -32
  191. schemathesis/internal/datetime.py +0 -5
  192. schemathesis/internal/deprecation.py +0 -37
  193. schemathesis/internal/diff.py +0 -15
  194. schemathesis/internal/extensions.py +0 -27
  195. schemathesis/internal/jsonschema.py +0 -36
  196. schemathesis/internal/output.py +0 -68
  197. schemathesis/internal/transformation.py +0 -26
  198. schemathesis/internal/validation.py +0 -34
  199. schemathesis/lazy.py +0 -474
  200. schemathesis/loaders.py +0 -122
  201. schemathesis/models.py +0 -1341
  202. schemathesis/parameters.py +0 -90
  203. schemathesis/runner/__init__.py +0 -605
  204. schemathesis/runner/events.py +0 -389
  205. schemathesis/runner/impl/__init__.py +0 -3
  206. schemathesis/runner/impl/context.py +0 -88
  207. schemathesis/runner/impl/core.py +0 -1280
  208. schemathesis/runner/impl/solo.py +0 -80
  209. schemathesis/runner/impl/threadpool.py +0 -391
  210. schemathesis/runner/serialization.py +0 -544
  211. schemathesis/sanitization.py +0 -252
  212. schemathesis/serializers.py +0 -328
  213. schemathesis/service/__init__.py +0 -18
  214. schemathesis/service/auth.py +0 -11
  215. schemathesis/service/ci.py +0 -202
  216. schemathesis/service/client.py +0 -133
  217. schemathesis/service/constants.py +0 -38
  218. schemathesis/service/events.py +0 -61
  219. schemathesis/service/extensions.py +0 -224
  220. schemathesis/service/hosts.py +0 -111
  221. schemathesis/service/metadata.py +0 -71
  222. schemathesis/service/models.py +0 -258
  223. schemathesis/service/report.py +0 -255
  224. schemathesis/service/serialization.py +0 -173
  225. schemathesis/service/usage.py +0 -66
  226. schemathesis/specs/graphql/loaders.py +0 -364
  227. schemathesis/specs/openapi/expressions/context.py +0 -16
  228. schemathesis/specs/openapi/links.py +0 -389
  229. schemathesis/specs/openapi/loaders.py +0 -707
  230. schemathesis/specs/openapi/stateful/statistic.py +0 -198
  231. schemathesis/specs/openapi/stateful/types.py +0 -14
  232. schemathesis/specs/openapi/validation.py +0 -26
  233. schemathesis/stateful/__init__.py +0 -147
  234. schemathesis/stateful/config.py +0 -97
  235. schemathesis/stateful/context.py +0 -135
  236. schemathesis/stateful/events.py +0 -274
  237. schemathesis/stateful/runner.py +0 -309
  238. schemathesis/stateful/sink.py +0 -68
  239. schemathesis/stateful/state_machine.py +0 -328
  240. schemathesis/stateful/statistic.py +0 -22
  241. schemathesis/stateful/validation.py +0 -100
  242. schemathesis/targets.py +0 -77
  243. schemathesis/transports/__init__.py +0 -369
  244. schemathesis/transports/asgi.py +0 -7
  245. schemathesis/transports/auth.py +0 -38
  246. schemathesis/transports/headers.py +0 -36
  247. schemathesis/transports/responses.py +0 -57
  248. schemathesis/types.py +0 -44
  249. schemathesis/utils.py +0 -164
  250. schemathesis-3.39.16.dist-info/METADATA +0 -293
  251. schemathesis-3.39.16.dist-info/RECORD +0 -160
  252. /schemathesis/{extra → cli/ext}/__init__.py +0 -0
  253. /schemathesis/{_lazy_import.py → core/lazy_import.py} +0 -0
  254. /schemathesis/{internal → core}/result.py +0 -0
  255. {schemathesis-3.39.16.dist-info → schemathesis-4.0.0.dist-info}/WHEEL +0 -0
@@ -0,0 +1,156 @@
1
+ from __future__ import annotations
2
+
3
+ import difflib
4
+ from typing import TYPE_CHECKING
5
+
6
+ from schemathesis.core.errors import SchemathesisError
7
+
8
+ if TYPE_CHECKING:
9
+ from jsonschema import ValidationError
10
+
11
+
12
+ class ConfigError(SchemathesisError):
13
+ """Invalid configuration."""
14
+
15
+ @classmethod
16
+ def from_validation_error(cls, error: ValidationError) -> ConfigError:
17
+ message = error.message
18
+ if error.validator == "enum":
19
+ message = _format_enum_error(error)
20
+ elif error.validator == "minimum":
21
+ message = _format_minimum_error(error)
22
+ elif error.validator == "required":
23
+ message = _format_required_error(error)
24
+ elif error.validator == "type":
25
+ message = _format_type_error(error)
26
+ elif error.validator == "additionalProperties":
27
+ message = _format_additional_properties_error(error)
28
+ elif error.validator == "anyOf":
29
+ message = _format_anyof_error(error)
30
+ return cls(message)
31
+
32
+
33
+ def _format_minimum_error(error: ValidationError) -> str:
34
+ assert isinstance(error.validator_value, (int, float))
35
+ section = path_to_section_name(list(error.path)[:-1] if error.path else [])
36
+ assert error.path
37
+
38
+ prop_name = error.path[-1]
39
+ min_value = error.validator_value
40
+ actual_value = error.instance
41
+
42
+ return (
43
+ f"Error in {section} section:\n Value too low:\n\n"
44
+ f" - '{prop_name}' → Must be at least {min_value}, but got {actual_value}."
45
+ )
46
+
47
+
48
+ def _format_required_error(error: ValidationError) -> str:
49
+ assert isinstance(error.validator_value, list)
50
+ missing_keys = sorted(set(error.validator_value) - set(error.instance))
51
+
52
+ section = path_to_section_name(list(error.path))
53
+
54
+ details = "\n".join(f" - '{key}'" for key in missing_keys)
55
+ return f"Error in {section} section:\n Missing required properties:\n\n{details}\n\n"
56
+
57
+
58
+ def _format_enum_error(error: ValidationError) -> str:
59
+ assert isinstance(error.validator_value, list)
60
+ valid_values = sorted(error.validator_value)
61
+
62
+ path = list(error.path)
63
+
64
+ if path and isinstance(path[-1], int):
65
+ idx = path[-1]
66
+ prop_name = path[-2]
67
+ section_path = path[:-2]
68
+ description = f"Item #{idx} in the '{prop_name}' array"
69
+ else:
70
+ prop_name = path[-1] if path else "value"
71
+ section_path = path[:-1]
72
+ description = f"'{prop_name}'"
73
+
74
+ suggestion = ""
75
+ if isinstance(error.instance, str) and all(isinstance(v, str) for v in valid_values):
76
+ match = _find_closest_match(error.instance, valid_values)
77
+ if match:
78
+ suggestion = f" Did you mean '{match}'?"
79
+
80
+ section = path_to_section_name(section_path)
81
+ valid_values_str = ", ".join(repr(v) for v in valid_values)
82
+ return (
83
+ f"Error in {section} section:\n Invalid value:\n\n"
84
+ f" - {description} → '{error.instance}' is not a valid value.{suggestion}\n\n"
85
+ f"Valid values are: {valid_values_str}."
86
+ )
87
+
88
+
89
+ def _format_type_error(error: ValidationError) -> str:
90
+ expected = error.validator_value
91
+ assert isinstance(expected, (str, list))
92
+ section = path_to_section_name(list(error.path)[:-1] if error.path else [])
93
+ assert error.path
94
+
95
+ type_phrases = {
96
+ "object": "an object",
97
+ "array": "an array",
98
+ "number": "a number",
99
+ "boolean": "a boolean",
100
+ "string": "a string",
101
+ "integer": "an integer",
102
+ "null": "null",
103
+ }
104
+ message = f"Error in {section} section:\n Type error:\n\n - '{error.path[-1]}' → Must be "
105
+
106
+ if isinstance(expected, list):
107
+ message += f"one of: {' or '.join(expected)}"
108
+ else:
109
+ message += type_phrases[expected]
110
+ actual = type(error.instance).__name__
111
+ message += f", but got {actual}: {error.instance}"
112
+ return message
113
+
114
+
115
+ def _format_additional_properties_error(error: ValidationError) -> str:
116
+ valid = list(error.schema.get("properties", {}))
117
+ unknown = sorted(set(error.instance) - set(valid))
118
+ valid_list = ", ".join(f"'{prop}'" for prop in valid)
119
+ section = path_to_section_name(list(error.path))
120
+
121
+ details = []
122
+ for prop in unknown:
123
+ match = _find_closest_match(prop, valid)
124
+ if match:
125
+ details.append(f"- '{prop}' → Did you mean '{match}'?")
126
+ else:
127
+ details.append(f"- '{prop}'")
128
+
129
+ return (
130
+ f"Error in {section} section:\n Unknown properties:\n\n"
131
+ + "\n".join(f" {detail}" for detail in details)
132
+ + f"\n\nValid properties for {section} are: {valid_list}."
133
+ )
134
+
135
+
136
+ def _format_anyof_error(error: ValidationError) -> str:
137
+ if list(error.schema_path) == ["properties", "operations", "items", "anyOf"]:
138
+ section = path_to_section_name(list(error.path))
139
+ return (
140
+ f"Error in {section} section:\n At least one filter is required when defining [[operations]].\n\n"
141
+ "Please specify at least one include or exclude filter property (e.g., include-path, exclude-tag, etc.)."
142
+ )
143
+ return error.message
144
+
145
+
146
+ def path_to_section_name(path: list[int | str]) -> str:
147
+ """Convert a JSON path to a TOML-like section name."""
148
+ if not path:
149
+ return "root"
150
+
151
+ return f"[{'.'.join(str(p) for p in path)}]"
152
+
153
+
154
+ def _find_closest_match(value: str, variants: list[str]) -> str | None:
155
+ matches = difflib.get_close_matches(value, variants, n=1, cutoff=0.6)
156
+ return matches[0] if matches else None
@@ -0,0 +1,149 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ from schemathesis.config._diff_base import DiffBase
7
+ from schemathesis.generation.modes import GenerationMode
8
+
9
+ if TYPE_CHECKING:
10
+ from schemathesis.generation.metrics import MetricFunction
11
+
12
+
13
+ @dataclass(repr=False)
14
+ class GenerationConfig(DiffBase):
15
+ modes: list[GenerationMode]
16
+ max_examples: int | None
17
+ no_shrink: bool
18
+ deterministic: bool
19
+ # Allow generating `\x00` bytes in strings
20
+ allow_x00: bool
21
+ # Generate strings using the given codec
22
+ codec: str | None
23
+ maximize: list[MetricFunction]
24
+ # Whether to generate security parameters
25
+ with_security_parameters: bool
26
+ # Allowing using `null` for optional arguments in GraphQL queries
27
+ graphql_allow_null: bool
28
+ database: str | None
29
+ unique_inputs: bool
30
+ exclude_header_characters: str | None
31
+
32
+ __slots__ = (
33
+ "modes",
34
+ "max_examples",
35
+ "no_shrink",
36
+ "deterministic",
37
+ "allow_x00",
38
+ "codec",
39
+ "maximize",
40
+ "with_security_parameters",
41
+ "graphql_allow_null",
42
+ "database",
43
+ "unique_inputs",
44
+ "exclude_header_characters",
45
+ )
46
+
47
+ def __init__(
48
+ self,
49
+ *,
50
+ modes: list[GenerationMode] | None = None,
51
+ max_examples: int | None = None,
52
+ no_shrink: bool = False,
53
+ deterministic: bool = False,
54
+ allow_x00: bool = True,
55
+ codec: str | None = "utf-8",
56
+ maximize: list[MetricFunction] | None = None,
57
+ with_security_parameters: bool = True,
58
+ graphql_allow_null: bool = True,
59
+ database: str | None = None,
60
+ unique_inputs: bool = False,
61
+ exclude_header_characters: str | None = None,
62
+ ) -> None:
63
+ from schemathesis.generation import GenerationMode
64
+
65
+ self.modes = modes or list(GenerationMode)
66
+ self.max_examples = max_examples
67
+ self.no_shrink = no_shrink
68
+ self.deterministic = deterministic
69
+ self.allow_x00 = allow_x00
70
+ self.codec = codec
71
+ self.maximize = maximize or []
72
+ self.with_security_parameters = with_security_parameters
73
+ self.graphql_allow_null = graphql_allow_null
74
+ self.database = database
75
+ self.unique_inputs = unique_inputs
76
+ self.exclude_header_characters = exclude_header_characters
77
+
78
+ @classmethod
79
+ def from_dict(cls, data: dict[str, Any]) -> GenerationConfig:
80
+ mode_raw = data.get("mode")
81
+ if mode_raw == "all":
82
+ modes = list(GenerationMode)
83
+ elif mode_raw is not None:
84
+ modes = [GenerationMode(mode_raw)]
85
+ else:
86
+ modes = None
87
+ maximize = _get_maximize(data.get("maximize"))
88
+ return cls(
89
+ modes=modes,
90
+ max_examples=data.get("max-examples"),
91
+ no_shrink=data.get("no-shrink", False),
92
+ deterministic=data.get("deterministic", False),
93
+ allow_x00=data.get("allow-x00", True),
94
+ codec=data.get("codec", "utf-8"),
95
+ maximize=maximize,
96
+ with_security_parameters=data.get("with-security-parameters", True),
97
+ graphql_allow_null=data.get("graphql-allow-null", True),
98
+ database=data.get("database"),
99
+ unique_inputs=data.get("unique-inputs", False),
100
+ exclude_header_characters=data.get("exclude-header-characters"),
101
+ )
102
+
103
+ def update(
104
+ self,
105
+ *,
106
+ modes: list[GenerationMode] | None = None,
107
+ max_examples: int | None = None,
108
+ no_shrink: bool = False,
109
+ deterministic: bool | None = None,
110
+ allow_x00: bool = True,
111
+ codec: str | None = None,
112
+ maximize: list[MetricFunction] | None = None,
113
+ with_security_parameters: bool | None = None,
114
+ graphql_allow_null: bool = True,
115
+ database: str | None = None,
116
+ unique_inputs: bool = False,
117
+ exclude_header_characters: str | None = None,
118
+ ) -> None:
119
+ if modes is not None:
120
+ self.modes = modes
121
+ if max_examples is not None:
122
+ self.max_examples = max_examples
123
+ self.no_shrink = no_shrink
124
+ self.deterministic = deterministic or False
125
+ self.allow_x00 = allow_x00
126
+ if codec is not None:
127
+ self.codec = codec
128
+ if maximize is not None:
129
+ self.maximize = maximize
130
+ if with_security_parameters is not None:
131
+ self.with_security_parameters = with_security_parameters
132
+ self.graphql_allow_null = graphql_allow_null
133
+ if database is not None:
134
+ self.database = database
135
+ self.unique_inputs = unique_inputs
136
+ if exclude_header_characters is not None:
137
+ self.exclude_header_characters = exclude_header_characters
138
+
139
+
140
+ def _get_maximize(value: Any) -> list[MetricFunction]:
141
+ from schemathesis.generation.metrics import METRICS
142
+
143
+ if isinstance(value, list):
144
+ metrics = value
145
+ elif isinstance(value, str):
146
+ metrics = [value]
147
+ else:
148
+ metrics = []
149
+ return METRICS.get_by_names(metrics)
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ from enum import Enum, unique
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ import hypothesis
8
+
9
+
10
+ @unique
11
+ class HealthCheck(str, Enum):
12
+ data_too_large = "data_too_large"
13
+ filter_too_much = "filter_too_much"
14
+ too_slow = "too_slow"
15
+ large_base_example = "large_base_example"
16
+ all = "all"
17
+
18
+ def as_hypothesis(self) -> list[hypothesis.HealthCheck]:
19
+ from hypothesis import HealthCheck
20
+
21
+ if self.name == "all":
22
+ return list(HealthCheck)
23
+
24
+ return [HealthCheck[self.name]]
@@ -0,0 +1,327 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from contextlib import contextmanager
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Any, Callable, Generator
7
+
8
+ from schemathesis.config._auth import AuthConfig
9
+ from schemathesis.config._checks import ChecksConfig
10
+ from schemathesis.config._diff_base import DiffBase
11
+ from schemathesis.config._env import resolve
12
+ from schemathesis.config._error import ConfigError
13
+ from schemathesis.config._generation import GenerationConfig
14
+ from schemathesis.config._parameters import load_parameters
15
+ from schemathesis.config._phases import PhasesConfig
16
+ from schemathesis.config._rate_limit import build_limiter
17
+ from schemathesis.config._warnings import SchemathesisWarning, resolve_warnings
18
+ from schemathesis.core.errors import IncorrectUsage
19
+ from schemathesis.filters import FilterSet, HasAPIOperation, expression_to_filter_function, is_deprecated
20
+
21
+ if TYPE_CHECKING:
22
+ from pyrate_limiter import Limiter
23
+
24
+ from schemathesis.schemas import APIOperation
25
+
26
+ FILTER_ATTRIBUTES = [
27
+ ("name", "name"),
28
+ ("method", "method"),
29
+ ("path", "path"),
30
+ ("tag", "tag"),
31
+ ("operation-id", "operation_id"),
32
+ ]
33
+
34
+
35
+ @contextmanager
36
+ def reraise_filter_error(attr: str) -> Generator:
37
+ try:
38
+ yield
39
+ except IncorrectUsage as exc:
40
+ if str(exc) == "Filter already exists":
41
+ raise ConfigError(
42
+ f"Filter for '{attr}' already exists. You can't simultaneously include and exclude the same thing."
43
+ ) from None
44
+ raise
45
+ except re.error as exc:
46
+ raise ConfigError(
47
+ f"Filter for '{attr}' contains an invalid regular expression: {exc.pattern!r}\n\n {exc}"
48
+ ) from None
49
+
50
+
51
+ @dataclass
52
+ class OperationsConfig(DiffBase):
53
+ operations: list[OperationConfig]
54
+
55
+ __slots__ = ("operations",)
56
+
57
+ def __init__(self, *, operations: list[OperationConfig] | None = None):
58
+ self.operations = operations or []
59
+
60
+ def __repr__(self) -> str:
61
+ if self.operations:
62
+ return f"[{', '.join(DiffBase.__repr__(cfg) for cfg in self.operations)}]"
63
+ return "[]"
64
+
65
+ @classmethod
66
+ def from_hierarchy(cls, configs: list[OperationsConfig]) -> OperationsConfig: # type: ignore
67
+ return cls(operations=sum([config.operations for config in reversed(configs)], []))
68
+
69
+ def get_for_operation(self, operation: APIOperation) -> OperationConfig:
70
+ configs = [config for config in self.operations if config._filter_set.applies_to(operation)]
71
+ return OperationConfig.from_hierarchy(configs)
72
+
73
+ def create_filter_set(
74
+ self,
75
+ *,
76
+ include_path: tuple[str, ...],
77
+ include_method: tuple[str, ...],
78
+ include_name: tuple[str, ...],
79
+ include_tag: tuple[str, ...],
80
+ include_operation_id: tuple[str, ...],
81
+ include_path_regex: str | None,
82
+ include_method_regex: str | None,
83
+ include_name_regex: str | None,
84
+ include_tag_regex: str | None,
85
+ include_operation_id_regex: str | None,
86
+ exclude_path: tuple[str, ...],
87
+ exclude_method: tuple[str, ...],
88
+ exclude_name: tuple[str, ...],
89
+ exclude_tag: tuple[str, ...],
90
+ exclude_operation_id: tuple[str, ...],
91
+ exclude_path_regex: str | None,
92
+ exclude_method_regex: str | None,
93
+ exclude_name_regex: str | None,
94
+ exclude_tag_regex: str | None,
95
+ exclude_operation_id_regex: str | None,
96
+ include_by: Callable | None,
97
+ exclude_by: Callable | None,
98
+ exclude_deprecated: bool,
99
+ ) -> FilterSet:
100
+ # Build explicit include filters
101
+ include_set = FilterSet()
102
+ if include_by:
103
+ include_set.include(include_by)
104
+ for name_ in include_name:
105
+ include_set.include(name=name_)
106
+ for method in include_method:
107
+ include_set.include(method=method)
108
+ for path in include_path:
109
+ include_set.include(path=path)
110
+ for tag in include_tag:
111
+ include_set.include(tag=tag)
112
+ for operation_id in include_operation_id:
113
+ include_set.include(operation_id=operation_id)
114
+ if (
115
+ include_name_regex
116
+ or include_method_regex
117
+ or include_path_regex
118
+ or include_tag_regex
119
+ or include_operation_id_regex
120
+ ):
121
+ include_set.include(
122
+ name_regex=include_name_regex,
123
+ method_regex=include_method_regex,
124
+ path_regex=include_path_regex,
125
+ tag_regex=include_tag_regex,
126
+ operation_id_regex=include_operation_id_regex,
127
+ )
128
+
129
+ # Build explicit exclude filters
130
+ exclude_set = FilterSet()
131
+ if exclude_by:
132
+ exclude_set.include(exclude_by)
133
+ for name_ in exclude_name:
134
+ exclude_set.include(name=name_)
135
+ for method in exclude_method:
136
+ exclude_set.include(method=method)
137
+ for path in exclude_path:
138
+ exclude_set.include(path=path)
139
+ for tag in exclude_tag:
140
+ exclude_set.include(tag=tag)
141
+ for operation_id in exclude_operation_id:
142
+ exclude_set.include(operation_id=operation_id)
143
+ if (
144
+ exclude_name_regex
145
+ or exclude_method_regex
146
+ or exclude_path_regex
147
+ or exclude_tag_regex
148
+ or exclude_operation_id_regex
149
+ ):
150
+ exclude_set.include(
151
+ name_regex=exclude_name_regex,
152
+ method_regex=exclude_method_regex,
153
+ path_regex=exclude_path_regex,
154
+ tag_regex=exclude_tag_regex,
155
+ operation_id_regex=exclude_operation_id_regex,
156
+ )
157
+
158
+ # Add deprecated operations to exclude filters if requested
159
+ if exclude_deprecated:
160
+ exclude_set.include(is_deprecated)
161
+
162
+ # Also update operations list for consistency with config structure
163
+ if not include_set.is_empty():
164
+ self.operations.insert(0, OperationConfig(filter_set=include_set, enabled=True))
165
+ if not exclude_set.is_empty():
166
+ self.operations.insert(0, OperationConfig(filter_set=exclude_set, enabled=False))
167
+
168
+ final = FilterSet()
169
+
170
+ # Get a stable reference to operations
171
+ operations = list(self.operations)
172
+
173
+ # Define a closure that implements our priority logic
174
+ def priority_filter(ctx: HasAPIOperation) -> bool:
175
+ """Filter operations according to CLI and config priority."""
176
+ # 1. CLI includes override everything if present
177
+ if not include_set.is_empty():
178
+ return include_set.match(ctx)
179
+
180
+ # 2. CLI excludes take precedence over config
181
+ if not exclude_set.is_empty() and exclude_set.match(ctx):
182
+ return False
183
+
184
+ # 3. Check config operations in priority order (first match wins)
185
+ for op_config in operations:
186
+ if op_config._filter_set.match(ctx):
187
+ return op_config.enabled
188
+
189
+ # 4. Default to include if no rule matches
190
+ return True
191
+
192
+ # Add our priority function as the filter
193
+ final.include(priority_filter)
194
+
195
+ return final
196
+
197
+
198
+ @dataclass
199
+ class OperationConfig(DiffBase):
200
+ _filter_set: FilterSet
201
+ enabled: bool
202
+ headers: dict | None
203
+ proxy: str | None
204
+ continue_on_failure: bool | None
205
+ tls_verify: bool | str | None
206
+ rate_limit: Limiter | None
207
+ request_timeout: float | int | None
208
+ request_cert: str | None
209
+ request_cert_key: str | None
210
+ parameters: dict[str, Any]
211
+ warnings: list[SchemathesisWarning] | None
212
+ auth: AuthConfig
213
+ checks: ChecksConfig
214
+ phases: PhasesConfig
215
+ generation: GenerationConfig
216
+
217
+ __slots__ = (
218
+ "_filter_set",
219
+ "enabled",
220
+ "headers",
221
+ "proxy",
222
+ "continue_on_failure",
223
+ "tls_verify",
224
+ "rate_limit",
225
+ "_rate_limit",
226
+ "request_timeout",
227
+ "request_cert",
228
+ "request_cert_key",
229
+ "parameters",
230
+ "warnings",
231
+ "auth",
232
+ "checks",
233
+ "phases",
234
+ "generation",
235
+ )
236
+
237
+ def __init__(
238
+ self,
239
+ *,
240
+ filter_set: FilterSet | None = None,
241
+ enabled: bool = True,
242
+ headers: dict | None = None,
243
+ proxy: str | None = None,
244
+ continue_on_failure: bool | None = None,
245
+ tls_verify: bool | str | None = None,
246
+ rate_limit: str | None = None,
247
+ request_timeout: float | int | None = None,
248
+ request_cert: str | None = None,
249
+ request_cert_key: str | None = None,
250
+ parameters: dict[str, Any] | None = None,
251
+ warnings: bool | list[SchemathesisWarning] | None = None,
252
+ auth: AuthConfig | None = None,
253
+ checks: ChecksConfig | None = None,
254
+ phases: PhasesConfig | None = None,
255
+ generation: GenerationConfig | None = None,
256
+ ) -> None:
257
+ self._filter_set = filter_set or FilterSet()
258
+ self.enabled = enabled
259
+ self.headers = headers
260
+ self.proxy = proxy
261
+ self.continue_on_failure = continue_on_failure
262
+ self.tls_verify = tls_verify
263
+ if rate_limit is not None:
264
+ self.rate_limit = build_limiter(rate_limit)
265
+ else:
266
+ self.rate_limit = rate_limit
267
+ self._rate_limit = rate_limit
268
+ self.request_timeout = request_timeout
269
+ self.request_cert = request_cert
270
+ self.request_cert_key = request_cert_key
271
+ self.parameters = parameters or {}
272
+ self._set_warnings(warnings)
273
+ self.auth = auth or AuthConfig()
274
+ self.checks = checks or ChecksConfig()
275
+ self.phases = phases or PhasesConfig()
276
+ self.generation = generation or GenerationConfig()
277
+
278
+ @classmethod
279
+ def from_dict(cls, data: dict[str, Any]) -> OperationConfig:
280
+ filter_set = FilterSet()
281
+ for key_suffix, arg_suffix in (("", ""), ("-regex", "_regex")):
282
+ for attr, arg_name in FILTER_ATTRIBUTES:
283
+ key = f"include-{attr}{key_suffix}"
284
+ if key in data:
285
+ with reraise_filter_error(attr):
286
+ filter_set.include(**{f"{arg_name}{arg_suffix}": data[key]})
287
+ key = f"exclude-{attr}{key_suffix}"
288
+ if key in data:
289
+ with reraise_filter_error(attr):
290
+ filter_set.exclude(**{f"{arg_name}{arg_suffix}": data[key]})
291
+ for key, method in (("include-by", filter_set.include), ("exclude-by", filter_set.exclude)):
292
+ if key in data:
293
+ expression = data[key]
294
+ try:
295
+ func = expression_to_filter_function(expression)
296
+ method(func)
297
+ except ValueError:
298
+ raise ConfigError(f"Invalid filter expression: '{expression}'") from None
299
+
300
+ return cls(
301
+ filter_set=filter_set,
302
+ enabled=data.get("enabled", True),
303
+ headers={resolve(key): resolve(value) for key, value in data.get("headers", {}).items()}
304
+ if "headers" in data
305
+ else None,
306
+ proxy=resolve(data.get("proxy")),
307
+ continue_on_failure=data.get("continue-on-failure", None),
308
+ tls_verify=resolve(data.get("tls-verify")),
309
+ rate_limit=resolve(data.get("rate-limit")),
310
+ request_timeout=data.get("request-timeout"),
311
+ request_cert=resolve(data.get("request-cert")),
312
+ request_cert_key=resolve(data.get("request-cert-key")),
313
+ parameters=load_parameters(data),
314
+ warnings=resolve_warnings(data.get("warnings")),
315
+ auth=AuthConfig.from_dict(data.get("auth", {})),
316
+ checks=ChecksConfig.from_dict(data.get("checks", {})),
317
+ phases=PhasesConfig.from_dict(data.get("phases", {})),
318
+ generation=GenerationConfig.from_dict(data.get("generation", {})),
319
+ )
320
+
321
+ def _set_warnings(self, warnings: bool | list[SchemathesisWarning] | None) -> None:
322
+ if warnings is False:
323
+ self.warnings = []
324
+ elif warnings is True:
325
+ self.warnings = list(SchemathesisWarning)
326
+ else:
327
+ self.warnings = warnings