schemathesis 3.39.7__py3-none-any.whl → 4.0.0a2__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 (229) hide show
  1. schemathesis/__init__.py +27 -65
  2. schemathesis/auths.py +26 -68
  3. schemathesis/checks.py +130 -60
  4. schemathesis/cli/__init__.py +5 -2105
  5. schemathesis/cli/commands/__init__.py +37 -0
  6. schemathesis/cli/commands/run/__init__.py +662 -0
  7. schemathesis/cli/commands/run/checks.py +80 -0
  8. schemathesis/cli/commands/run/context.py +117 -0
  9. schemathesis/cli/commands/run/events.py +30 -0
  10. schemathesis/cli/commands/run/executor.py +141 -0
  11. schemathesis/cli/commands/run/filters.py +202 -0
  12. schemathesis/cli/commands/run/handlers/__init__.py +46 -0
  13. schemathesis/cli/commands/run/handlers/base.py +18 -0
  14. schemathesis/cli/{cassettes.py → commands/run/handlers/cassettes.py} +178 -247
  15. schemathesis/cli/commands/run/handlers/junitxml.py +54 -0
  16. schemathesis/cli/commands/run/handlers/output.py +1368 -0
  17. schemathesis/cli/commands/run/hypothesis.py +105 -0
  18. schemathesis/cli/commands/run/loaders.py +129 -0
  19. schemathesis/cli/{callbacks.py → commands/run/validation.py} +59 -175
  20. schemathesis/cli/constants.py +5 -58
  21. schemathesis/cli/core.py +17 -0
  22. schemathesis/cli/ext/fs.py +14 -0
  23. schemathesis/cli/ext/groups.py +55 -0
  24. schemathesis/cli/{options.py → ext/options.py} +37 -16
  25. schemathesis/cli/hooks.py +36 -0
  26. schemathesis/contrib/__init__.py +1 -3
  27. schemathesis/contrib/openapi/__init__.py +1 -3
  28. schemathesis/contrib/openapi/fill_missing_examples.py +3 -7
  29. schemathesis/core/__init__.py +58 -0
  30. schemathesis/core/compat.py +25 -0
  31. schemathesis/core/control.py +2 -0
  32. schemathesis/core/curl.py +58 -0
  33. schemathesis/core/deserialization.py +65 -0
  34. schemathesis/core/errors.py +370 -0
  35. schemathesis/core/failures.py +315 -0
  36. schemathesis/core/fs.py +19 -0
  37. schemathesis/core/loaders.py +104 -0
  38. schemathesis/core/marks.py +66 -0
  39. schemathesis/{transports/content_types.py → core/media_types.py} +14 -12
  40. schemathesis/{internal/output.py → core/output/__init__.py} +1 -0
  41. schemathesis/core/output/sanitization.py +197 -0
  42. schemathesis/{throttling.py → core/rate_limit.py} +16 -17
  43. schemathesis/core/registries.py +31 -0
  44. schemathesis/core/transforms.py +113 -0
  45. schemathesis/core/transport.py +108 -0
  46. schemathesis/core/validation.py +38 -0
  47. schemathesis/core/version.py +7 -0
  48. schemathesis/engine/__init__.py +30 -0
  49. schemathesis/engine/config.py +59 -0
  50. schemathesis/engine/context.py +119 -0
  51. schemathesis/engine/control.py +36 -0
  52. schemathesis/engine/core.py +157 -0
  53. schemathesis/engine/errors.py +394 -0
  54. schemathesis/engine/events.py +243 -0
  55. schemathesis/engine/phases/__init__.py +66 -0
  56. schemathesis/{runner → engine/phases}/probes.py +49 -68
  57. schemathesis/engine/phases/stateful/__init__.py +66 -0
  58. schemathesis/engine/phases/stateful/_executor.py +301 -0
  59. schemathesis/engine/phases/stateful/context.py +85 -0
  60. schemathesis/engine/phases/unit/__init__.py +175 -0
  61. schemathesis/engine/phases/unit/_executor.py +322 -0
  62. schemathesis/engine/phases/unit/_pool.py +74 -0
  63. schemathesis/engine/recorder.py +246 -0
  64. schemathesis/errors.py +31 -0
  65. schemathesis/experimental/__init__.py +9 -40
  66. schemathesis/filters.py +7 -95
  67. schemathesis/generation/__init__.py +3 -3
  68. schemathesis/generation/case.py +190 -0
  69. schemathesis/generation/coverage.py +22 -22
  70. schemathesis/{_patches.py → generation/hypothesis/__init__.py} +15 -6
  71. schemathesis/generation/hypothesis/builder.py +585 -0
  72. schemathesis/generation/{_hypothesis.py → hypothesis/examples.py} +2 -11
  73. schemathesis/generation/hypothesis/given.py +66 -0
  74. schemathesis/generation/hypothesis/reporting.py +14 -0
  75. schemathesis/generation/hypothesis/strategies.py +16 -0
  76. schemathesis/generation/meta.py +115 -0
  77. schemathesis/generation/modes.py +28 -0
  78. schemathesis/generation/overrides.py +96 -0
  79. schemathesis/generation/stateful/__init__.py +20 -0
  80. schemathesis/{stateful → generation/stateful}/state_machine.py +84 -109
  81. schemathesis/generation/targets.py +69 -0
  82. schemathesis/graphql/__init__.py +15 -0
  83. schemathesis/graphql/checks.py +109 -0
  84. schemathesis/graphql/loaders.py +131 -0
  85. schemathesis/hooks.py +17 -62
  86. schemathesis/openapi/__init__.py +13 -0
  87. schemathesis/openapi/checks.py +387 -0
  88. schemathesis/openapi/generation/__init__.py +0 -0
  89. schemathesis/openapi/generation/filters.py +63 -0
  90. schemathesis/openapi/loaders.py +178 -0
  91. schemathesis/pytest/__init__.py +5 -0
  92. schemathesis/pytest/control_flow.py +7 -0
  93. schemathesis/pytest/lazy.py +273 -0
  94. schemathesis/pytest/loaders.py +12 -0
  95. schemathesis/{extra/pytest_plugin.py → pytest/plugin.py} +94 -107
  96. schemathesis/python/__init__.py +0 -0
  97. schemathesis/python/asgi.py +12 -0
  98. schemathesis/python/wsgi.py +12 -0
  99. schemathesis/schemas.py +456 -228
  100. schemathesis/specs/graphql/__init__.py +0 -1
  101. schemathesis/specs/graphql/_cache.py +1 -2
  102. schemathesis/specs/graphql/scalars.py +5 -3
  103. schemathesis/specs/graphql/schemas.py +122 -123
  104. schemathesis/specs/graphql/validation.py +11 -17
  105. schemathesis/specs/openapi/__init__.py +6 -1
  106. schemathesis/specs/openapi/_cache.py +1 -2
  107. schemathesis/specs/openapi/_hypothesis.py +97 -134
  108. schemathesis/specs/openapi/checks.py +238 -219
  109. schemathesis/specs/openapi/converter.py +4 -4
  110. schemathesis/specs/openapi/definitions.py +1 -1
  111. schemathesis/specs/openapi/examples.py +22 -20
  112. schemathesis/specs/openapi/expressions/__init__.py +11 -15
  113. schemathesis/specs/openapi/expressions/extractors.py +1 -4
  114. schemathesis/specs/openapi/expressions/nodes.py +33 -32
  115. schemathesis/specs/openapi/formats.py +3 -2
  116. schemathesis/specs/openapi/links.py +123 -299
  117. schemathesis/specs/openapi/media_types.py +10 -12
  118. schemathesis/specs/openapi/negative/__init__.py +2 -1
  119. schemathesis/specs/openapi/negative/mutations.py +3 -2
  120. schemathesis/specs/openapi/parameters.py +8 -6
  121. schemathesis/specs/openapi/patterns.py +1 -1
  122. schemathesis/specs/openapi/references.py +11 -51
  123. schemathesis/specs/openapi/schemas.py +177 -191
  124. schemathesis/specs/openapi/security.py +1 -1
  125. schemathesis/specs/openapi/serialization.py +10 -6
  126. schemathesis/specs/openapi/stateful/__init__.py +97 -91
  127. schemathesis/transport/__init__.py +104 -0
  128. schemathesis/transport/asgi.py +26 -0
  129. schemathesis/transport/prepare.py +99 -0
  130. schemathesis/transport/requests.py +221 -0
  131. schemathesis/{_xml.py → transport/serialization.py} +69 -7
  132. schemathesis/transport/wsgi.py +165 -0
  133. {schemathesis-3.39.7.dist-info → schemathesis-4.0.0a2.dist-info}/METADATA +18 -14
  134. schemathesis-4.0.0a2.dist-info/RECORD +151 -0
  135. {schemathesis-3.39.7.dist-info → schemathesis-4.0.0a2.dist-info}/entry_points.txt +1 -1
  136. schemathesis/_compat.py +0 -74
  137. schemathesis/_dependency_versions.py +0 -19
  138. schemathesis/_hypothesis.py +0 -559
  139. schemathesis/_override.py +0 -50
  140. schemathesis/_rate_limiter.py +0 -7
  141. schemathesis/cli/context.py +0 -75
  142. schemathesis/cli/debug.py +0 -27
  143. schemathesis/cli/handlers.py +0 -19
  144. schemathesis/cli/junitxml.py +0 -124
  145. schemathesis/cli/output/__init__.py +0 -1
  146. schemathesis/cli/output/default.py +0 -936
  147. schemathesis/cli/output/short.py +0 -59
  148. schemathesis/cli/reporting.py +0 -79
  149. schemathesis/cli/sanitization.py +0 -26
  150. schemathesis/code_samples.py +0 -151
  151. schemathesis/constants.py +0 -56
  152. schemathesis/contrib/openapi/formats/__init__.py +0 -9
  153. schemathesis/contrib/openapi/formats/uuid.py +0 -16
  154. schemathesis/contrib/unique_data.py +0 -41
  155. schemathesis/exceptions.py +0 -571
  156. schemathesis/extra/_aiohttp.py +0 -28
  157. schemathesis/extra/_flask.py +0 -13
  158. schemathesis/extra/_server.py +0 -18
  159. schemathesis/failures.py +0 -277
  160. schemathesis/fixups/__init__.py +0 -37
  161. schemathesis/fixups/fast_api.py +0 -41
  162. schemathesis/fixups/utf8_bom.py +0 -28
  163. schemathesis/generation/_methods.py +0 -44
  164. schemathesis/graphql.py +0 -3
  165. schemathesis/internal/__init__.py +0 -7
  166. schemathesis/internal/checks.py +0 -84
  167. schemathesis/internal/copy.py +0 -32
  168. schemathesis/internal/datetime.py +0 -5
  169. schemathesis/internal/deprecation.py +0 -38
  170. schemathesis/internal/diff.py +0 -15
  171. schemathesis/internal/extensions.py +0 -27
  172. schemathesis/internal/jsonschema.py +0 -36
  173. schemathesis/internal/transformation.py +0 -26
  174. schemathesis/internal/validation.py +0 -34
  175. schemathesis/lazy.py +0 -474
  176. schemathesis/loaders.py +0 -122
  177. schemathesis/models.py +0 -1341
  178. schemathesis/parameters.py +0 -90
  179. schemathesis/runner/__init__.py +0 -605
  180. schemathesis/runner/events.py +0 -389
  181. schemathesis/runner/impl/__init__.py +0 -3
  182. schemathesis/runner/impl/context.py +0 -104
  183. schemathesis/runner/impl/core.py +0 -1246
  184. schemathesis/runner/impl/solo.py +0 -80
  185. schemathesis/runner/impl/threadpool.py +0 -391
  186. schemathesis/runner/serialization.py +0 -544
  187. schemathesis/sanitization.py +0 -252
  188. schemathesis/serializers.py +0 -328
  189. schemathesis/service/__init__.py +0 -18
  190. schemathesis/service/auth.py +0 -11
  191. schemathesis/service/ci.py +0 -202
  192. schemathesis/service/client.py +0 -133
  193. schemathesis/service/constants.py +0 -38
  194. schemathesis/service/events.py +0 -61
  195. schemathesis/service/extensions.py +0 -224
  196. schemathesis/service/hosts.py +0 -111
  197. schemathesis/service/metadata.py +0 -71
  198. schemathesis/service/models.py +0 -258
  199. schemathesis/service/report.py +0 -255
  200. schemathesis/service/serialization.py +0 -173
  201. schemathesis/service/usage.py +0 -66
  202. schemathesis/specs/graphql/loaders.py +0 -364
  203. schemathesis/specs/openapi/expressions/context.py +0 -16
  204. schemathesis/specs/openapi/loaders.py +0 -708
  205. schemathesis/specs/openapi/stateful/statistic.py +0 -198
  206. schemathesis/specs/openapi/stateful/types.py +0 -14
  207. schemathesis/specs/openapi/validation.py +0 -26
  208. schemathesis/stateful/__init__.py +0 -147
  209. schemathesis/stateful/config.py +0 -97
  210. schemathesis/stateful/context.py +0 -135
  211. schemathesis/stateful/events.py +0 -274
  212. schemathesis/stateful/runner.py +0 -309
  213. schemathesis/stateful/sink.py +0 -68
  214. schemathesis/stateful/statistic.py +0 -22
  215. schemathesis/stateful/validation.py +0 -100
  216. schemathesis/targets.py +0 -77
  217. schemathesis/transports/__init__.py +0 -359
  218. schemathesis/transports/asgi.py +0 -7
  219. schemathesis/transports/auth.py +0 -38
  220. schemathesis/transports/headers.py +0 -36
  221. schemathesis/transports/responses.py +0 -57
  222. schemathesis/types.py +0 -44
  223. schemathesis/utils.py +0 -164
  224. schemathesis-3.39.7.dist-info/RECORD +0 -160
  225. /schemathesis/{extra → cli/ext}/__init__.py +0 -0
  226. /schemathesis/{_lazy_import.py → core/lazy_import.py} +0 -0
  227. /schemathesis/{internal → core}/result.py +0 -0
  228. {schemathesis-3.39.7.dist-info → schemathesis-4.0.0a2.dist-info}/WHEEL +0 -0
  229. {schemathesis-3.39.7.dist-info → schemathesis-4.0.0a2.dist-info}/licenses/LICENSE +0 -0
@@ -1,1246 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import functools
4
- import logging
5
- import operator
6
- import re
7
- import threading
8
- import time
9
- import unittest
10
- import uuid
11
- import warnings
12
- from contextlib import contextmanager
13
- from dataclasses import dataclass, field
14
- from typing import TYPE_CHECKING, Any, Callable, Generator, Iterable, List, Literal, cast
15
- from warnings import WarningMessage, catch_warnings
16
-
17
- import hypothesis
18
- import requests
19
- from _pytest.logging import LogCaptureHandler, catching_logs
20
- from hypothesis.errors import HypothesisException, InvalidArgument
21
- from hypothesis_jsonschema._canonicalise import HypothesisRefResolutionError
22
- from jsonschema.exceptions import SchemaError as JsonSchemaError
23
- from jsonschema.exceptions import ValidationError
24
- from requests.structures import CaseInsensitiveDict
25
- from urllib3.exceptions import InsecureRequestWarning
26
-
27
- from ... import experimental, failures, hooks
28
- from ..._compat import MultipleFailures
29
- from ..._hypothesis import (
30
- get_invalid_example_headers_mark,
31
- get_invalid_regex_mark,
32
- get_non_serializable_mark,
33
- has_unsatisfied_example_mark,
34
- )
35
- from ...auths import unregister as unregister_auth
36
- from ...checks import _make_max_response_time_failure_message
37
- from ...constants import (
38
- DEFAULT_STATEFUL_RECURSION_LIMIT,
39
- RECURSIVE_REFERENCE_ERROR_MESSAGE,
40
- SERIALIZERS_SUGGESTION_MESSAGE,
41
- USER_AGENT,
42
- )
43
- from ...exceptions import (
44
- CheckFailed,
45
- DeadlineExceeded,
46
- InternalError,
47
- InvalidHeadersExample,
48
- InvalidRegularExpression,
49
- NonCheckError,
50
- OperationSchemaError,
51
- RecursiveReferenceError,
52
- SerializationNotPossible,
53
- SkipTest,
54
- format_exception,
55
- get_grouped_exception,
56
- maybe_set_assertion_message,
57
- )
58
- from ...generation import DataGenerationMethod, GenerationConfig
59
- from ...hooks import HookContext, get_all_by_name
60
- from ...internal.checks import CheckConfig, CheckContext
61
- from ...internal.datetime import current_datetime
62
- from ...internal.result import Err, Ok, Result
63
- from ...models import APIOperation, Case, Check, Status, TestResult
64
- from ...runner import events
65
- from ...service import extensions
66
- from ...service.models import AnalysisResult, AnalysisSuccess
67
- from ...specs.openapi import formats
68
- from ...stateful import Feedback, Stateful
69
- from ...stateful import events as stateful_events
70
- from ...stateful import runner as stateful_runner
71
- from ...targets import Target, TargetContext
72
- from ...transports import RequestConfig, RequestsTransport
73
- from ...transports.auth import get_requests_auth, prepare_wsgi_headers
74
- from ...utils import capture_hypothesis_output
75
- from .. import probes
76
- from ..serialization import SerializedTestResult
77
- from .context import RunnerContext
78
-
79
- if TYPE_CHECKING:
80
- from types import TracebackType
81
-
82
- from requests.auth import HTTPDigestAuth
83
-
84
- from ..._override import CaseOverride
85
- from ...internal.checks import CheckFunction
86
- from ...schemas import BaseSchema
87
- from ...service.client import ServiceClient
88
- from ...transports.responses import GenericResponse, WSGIResponse
89
- from ...types import RawAuth
90
-
91
-
92
- def _should_count_towards_stop(event: events.ExecutionEvent) -> bool:
93
- return isinstance(event, events.AfterExecution) and event.status in (Status.error, Status.failure)
94
-
95
-
96
- @dataclass
97
- class BaseRunner:
98
- schema: BaseSchema
99
- checks: Iterable[CheckFunction]
100
- max_response_time: int | None
101
- targets: Iterable[Target]
102
- hypothesis_settings: hypothesis.settings
103
- generation_config: GenerationConfig | None
104
- probe_config: probes.ProbeConfig
105
- checks_config: CheckConfig
106
- request_config: RequestConfig = field(default_factory=RequestConfig)
107
- override: CaseOverride | None = None
108
- auth: RawAuth | None = None
109
- auth_type: str | None = None
110
- headers: dict[str, Any] | None = None
111
- store_interactions: bool = False
112
- seed: int | None = None
113
- exit_first: bool = False
114
- no_failfast: bool = False
115
- max_failures: int | None = None
116
- started_at: str = field(default_factory=current_datetime)
117
- unique_data: bool = False
118
- dry_run: bool = False
119
- stateful: Stateful | None = None
120
- stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT
121
- count_operations: bool = True
122
- count_links: bool = True
123
- service_client: ServiceClient | None = None
124
- _failures_counter: int = 0
125
- _is_stopping_due_to_failure_limit: bool = False
126
-
127
- def execute(self) -> EventStream:
128
- """Common logic for all runners."""
129
- event = threading.Event()
130
- return EventStream(self._generate_events(event), event)
131
-
132
- def _generate_events(self, stop_event: threading.Event) -> Generator[events.ExecutionEvent, None, None]:
133
- # If auth is explicitly provided, then the global provider is ignored
134
- if self.auth is not None:
135
- unregister_auth()
136
- ctx = RunnerContext(
137
- auth=self.auth,
138
- seed=self.seed,
139
- stop_event=stop_event,
140
- unique_data=self.unique_data,
141
- checks_config=self.checks_config,
142
- override=self.override,
143
- no_failfast=self.no_failfast,
144
- )
145
- start_time = time.monotonic()
146
- initialized = None
147
- __probes = None
148
- __analysis: Result[AnalysisResult, Exception] | None = None
149
-
150
- def _initialize() -> events.Initialized:
151
- nonlocal initialized
152
- initialized = events.Initialized.from_schema(
153
- schema=self.schema,
154
- count_operations=self.count_operations,
155
- count_links=self.count_links,
156
- seed=ctx.seed,
157
- start_time=start_time,
158
- )
159
- return initialized
160
-
161
- def _finish() -> events.Finished:
162
- if ctx.has_all_not_found:
163
- ctx.add_warning(ALL_NOT_FOUND_WARNING_MESSAGE)
164
- return events.Finished.from_results(results=ctx.data, running_time=time.monotonic() - start_time)
165
-
166
- def _before_probes() -> events.BeforeProbing:
167
- return events.BeforeProbing()
168
-
169
- def _run_probes() -> None:
170
- if not self.dry_run:
171
- nonlocal __probes
172
-
173
- __probes = run_probes(self.schema, self.probe_config)
174
-
175
- def _after_probes() -> events.AfterProbing:
176
- _probes = cast(List[probes.ProbeRun], __probes)
177
- return events.AfterProbing(probes=_probes)
178
-
179
- def _before_analysis() -> events.BeforeAnalysis:
180
- return events.BeforeAnalysis()
181
-
182
- def _run_analysis() -> None:
183
- nonlocal __analysis, __probes
184
-
185
- if self.service_client is not None:
186
- try:
187
- _probes = cast(List[probes.ProbeRun], __probes)
188
- result = self.service_client.analyze_schema(_probes, self.schema.raw_schema)
189
- if isinstance(result, AnalysisSuccess):
190
- extensions.apply(result.extensions, self.schema)
191
- __analysis = Ok(result)
192
- except Exception as exc:
193
- __analysis = Err(exc)
194
-
195
- def _after_analysis() -> events.AfterAnalysis:
196
- return events.AfterAnalysis(analysis=__analysis)
197
-
198
- if ctx.is_stopped:
199
- yield _finish()
200
- return
201
-
202
- for event_factory in (
203
- _initialize,
204
- _before_probes,
205
- _run_probes,
206
- _after_probes,
207
- _before_analysis,
208
- _run_analysis,
209
- _after_analysis,
210
- ):
211
- event = event_factory()
212
- if event is not None:
213
- yield event
214
- if ctx.is_stopped:
215
- yield _finish() # type: ignore[unreachable]
216
- return
217
-
218
- try:
219
- warnings.simplefilter("ignore", InsecureRequestWarning)
220
- if not experimental.STATEFUL_ONLY.is_enabled:
221
- yield from self._execute(ctx)
222
- if not self._is_stopping_due_to_failure_limit:
223
- yield from self._run_stateful_tests(ctx)
224
- except KeyboardInterrupt:
225
- yield events.Interrupted()
226
-
227
- yield _finish()
228
-
229
- def _should_stop(self, event: events.ExecutionEvent) -> bool:
230
- result = self.__should_stop(event)
231
- if result:
232
- self._is_stopping_due_to_failure_limit = True
233
- return result
234
-
235
- def __should_stop(self, event: events.ExecutionEvent) -> bool:
236
- if _should_count_towards_stop(event):
237
- if self.exit_first:
238
- return True
239
- if self.max_failures is not None:
240
- self._failures_counter += 1
241
- return self._failures_counter >= self.max_failures
242
- return False
243
-
244
- def _execute(self, ctx: RunnerContext) -> Generator[events.ExecutionEvent, None, None]:
245
- raise NotImplementedError
246
-
247
- def _run_stateful_tests(self, ctx: RunnerContext) -> Generator[events.ExecutionEvent, None, None]:
248
- # Run new-style stateful tests
249
- if self.stateful is not None and experimental.STATEFUL_TEST_RUNNER.is_enabled and self.schema.links_count > 0:
250
- result = TestResult(
251
- method="",
252
- path="",
253
- verbose_name="Stateful tests",
254
- seed=ctx.seed,
255
- data_generation_method=self.schema.data_generation_methods,
256
- )
257
- headers = self.headers or {}
258
- if isinstance(self.schema.transport, RequestsTransport):
259
- auth = get_requests_auth(self.auth, self.auth_type)
260
- else:
261
- auth = None
262
- headers = prepare_wsgi_headers(headers, self.auth, self.auth_type)
263
- config = stateful_runner.StatefulTestRunnerConfig(
264
- checks=tuple(self.checks),
265
- headers=headers,
266
- hypothesis_settings=self.hypothesis_settings,
267
- exit_first=self.exit_first,
268
- max_failures=None if self.max_failures is None else self.max_failures - self._failures_counter,
269
- request=self.request_config,
270
- auth=auth,
271
- seed=ctx.seed,
272
- override=self.override,
273
- )
274
- state_machine = self.schema.as_state_machine()
275
- runner = state_machine.runner(config=config)
276
- status = Status.success
277
-
278
- def from_step_status(step_status: stateful_events.StepStatus) -> Status:
279
- return {
280
- stateful_events.StepStatus.SUCCESS: Status.success,
281
- stateful_events.StepStatus.FAILURE: Status.failure,
282
- stateful_events.StepStatus.ERROR: Status.error,
283
- stateful_events.StepStatus.INTERRUPTED: Status.error,
284
- }[step_status]
285
-
286
- if self.store_interactions:
287
- if isinstance(state_machine.schema.transport, RequestsTransport):
288
-
289
- def on_step_finished(event: stateful_events.StepFinished) -> None:
290
- if event.response is not None and event.status is not None:
291
- response = cast(requests.Response, event.response)
292
- result.store_requests_response(
293
- status=from_step_status(event.status),
294
- case=event.case,
295
- response=response,
296
- checks=event.checks,
297
- headers=headers,
298
- session=None,
299
- )
300
-
301
- else:
302
-
303
- def on_step_finished(event: stateful_events.StepFinished) -> None:
304
- from ...transports.responses import WSGIResponse
305
-
306
- if event.response is not None and event.status is not None:
307
- response = cast(WSGIResponse, event.response)
308
- result.store_wsgi_response(
309
- status=from_step_status(event.status),
310
- case=event.case,
311
- response=response,
312
- headers=headers,
313
- elapsed=response.elapsed.total_seconds(),
314
- checks=event.checks,
315
- )
316
- else:
317
-
318
- def on_step_finished(event: stateful_events.StepFinished) -> None:
319
- return None
320
-
321
- test_start_time: float | None = None
322
- test_elapsed_time: float | None = None
323
-
324
- for stateful_event in runner.execute():
325
- if isinstance(stateful_event, stateful_events.SuiteFinished):
326
- if stateful_event.failures and status != Status.error:
327
- status = Status.failure
328
- elif isinstance(stateful_event, stateful_events.RunStarted):
329
- test_start_time = stateful_event.timestamp
330
- elif isinstance(stateful_event, stateful_events.RunFinished):
331
- test_elapsed_time = stateful_event.timestamp - cast(float, test_start_time)
332
- elif isinstance(stateful_event, stateful_events.StepFinished):
333
- result.checks.extend(stateful_event.checks)
334
- on_step_finished(stateful_event)
335
- elif isinstance(stateful_event, stateful_events.Errored):
336
- status = Status.error
337
- result.add_error(stateful_event.exception)
338
- yield events.StatefulEvent(data=stateful_event)
339
- ctx.add_result(result)
340
- yield events.AfterStatefulExecution(
341
- status=status,
342
- result=SerializedTestResult.from_test_result(result),
343
- elapsed_time=cast(float, test_elapsed_time),
344
- data_generation_method=self.schema.data_generation_methods,
345
- )
346
-
347
- def _run_tests(
348
- self,
349
- maker: Callable,
350
- test_func: Callable,
351
- settings: hypothesis.settings,
352
- generation_config: GenerationConfig | None,
353
- ctx: RunnerContext,
354
- recursion_level: int = 0,
355
- headers: dict[str, Any] | None = None,
356
- **kwargs: Any,
357
- ) -> Generator[events.ExecutionEvent, None, None]:
358
- """Run tests and recursively run additional tests."""
359
- if recursion_level > self.stateful_recursion_limit:
360
- return
361
-
362
- def as_strategy_kwargs(_operation: APIOperation) -> dict[str, Any]:
363
- kw = {}
364
- if self.override is not None:
365
- for location, entry in self.override.for_operation(_operation).items():
366
- if entry:
367
- kw[location] = entry
368
- if headers:
369
- kw["headers"] = {key: value for key, value in headers.items() if key.lower() != "user-agent"}
370
- return kw
371
-
372
- for result in maker(
373
- test_func,
374
- settings=settings,
375
- generation_config=generation_config,
376
- seed=ctx.seed,
377
- as_strategy_kwargs=as_strategy_kwargs,
378
- ):
379
- if isinstance(result, Ok):
380
- operation, test = result.ok()
381
- if self.stateful is not None and not experimental.STATEFUL_TEST_RUNNER.is_enabled:
382
- feedback = Feedback(self.stateful, operation)
383
- else:
384
- feedback = None
385
- # Track whether `BeforeExecution` was already emitted.
386
- # Schema error may happen before / after `BeforeExecution`, but it should be emitted only once
387
- # and the `AfterExecution` event should have the same correlation id as previous `BeforeExecution`
388
- before_execution_correlation_id = None
389
- try:
390
- for event in run_test(
391
- operation,
392
- test,
393
- ctx=ctx,
394
- feedback=feedback,
395
- recursion_level=recursion_level,
396
- data_generation_methods=self.schema.data_generation_methods,
397
- headers=headers,
398
- **kwargs,
399
- ):
400
- yield event
401
- if isinstance(event, events.BeforeExecution):
402
- before_execution_correlation_id = event.correlation_id
403
- if isinstance(event, events.Interrupted):
404
- return
405
- # Additional tests, generated via the `feedback` instance
406
- if feedback is not None:
407
- yield from self._run_tests(
408
- feedback.get_stateful_tests,
409
- test_func,
410
- settings=settings,
411
- generation_config=generation_config,
412
- recursion_level=recursion_level + 1,
413
- ctx=ctx,
414
- headers=headers,
415
- **kwargs,
416
- )
417
- except OperationSchemaError as exc:
418
- yield from handle_schema_error(
419
- exc,
420
- ctx,
421
- self.schema.data_generation_methods,
422
- recursion_level,
423
- before_execution_correlation_id=before_execution_correlation_id,
424
- )
425
- else:
426
- # Schema errors
427
- yield from handle_schema_error(result.err(), ctx, self.schema.data_generation_methods, recursion_level)
428
-
429
-
430
- def run_probes(schema: BaseSchema, config: probes.ProbeConfig) -> list[probes.ProbeRun]:
431
- """Discover capabilities of the tested app."""
432
- results = probes.run(schema, config)
433
- for result in results:
434
- if isinstance(result.probe, probes.NullByteInHeader) and result.is_failure:
435
- from ...specs.openapi.formats import HEADER_FORMAT, header_values
436
-
437
- formats.register(HEADER_FORMAT, header_values(blacklist_characters="\n\r\x00"))
438
- return results
439
-
440
-
441
- @dataclass
442
- class EventStream:
443
- """Schemathesis event stream.
444
-
445
- Provides an API to control the execution flow.
446
- """
447
-
448
- generator: Generator[events.ExecutionEvent, None, None]
449
- stop_event: threading.Event
450
-
451
- def __next__(self) -> events.ExecutionEvent:
452
- return next(self.generator)
453
-
454
- def __iter__(self) -> Generator[events.ExecutionEvent, None, None]:
455
- return self.generator
456
-
457
- def stop(self) -> None:
458
- """Stop the event stream.
459
-
460
- Its next value will be the last one (Finished).
461
- """
462
- self.stop_event.set()
463
-
464
- def finish(self) -> events.ExecutionEvent:
465
- """Stop the event stream & return the last event."""
466
- self.stop()
467
- return next(self)
468
-
469
-
470
- def handle_schema_error(
471
- error: OperationSchemaError,
472
- ctx: RunnerContext,
473
- data_generation_methods: Iterable[DataGenerationMethod],
474
- recursion_level: int,
475
- *,
476
- before_execution_correlation_id: str | None = None,
477
- ) -> Generator[events.ExecutionEvent, None, None]:
478
- if error.method is not None:
479
- assert error.path is not None
480
- assert error.full_path is not None
481
- data_generation_methods = list(data_generation_methods)
482
- method = error.method.upper()
483
- verbose_name = f"{method} {error.full_path}"
484
- result = TestResult(
485
- method=method,
486
- path=error.full_path,
487
- verbose_name=verbose_name,
488
- data_generation_method=data_generation_methods,
489
- )
490
- result.add_error(error)
491
- # It might be already emitted - reuse its correlation id
492
- if before_execution_correlation_id is not None:
493
- correlation_id = before_execution_correlation_id
494
- else:
495
- correlation_id = uuid.uuid4().hex
496
- yield events.BeforeExecution(
497
- method=method,
498
- path=error.full_path,
499
- verbose_name=verbose_name,
500
- relative_path=error.path,
501
- recursion_level=recursion_level,
502
- data_generation_method=data_generation_methods,
503
- correlation_id=correlation_id,
504
- )
505
- yield events.AfterExecution(
506
- method=method,
507
- path=error.full_path,
508
- relative_path=error.path,
509
- verbose_name=verbose_name,
510
- status=Status.error,
511
- result=SerializedTestResult.from_test_result(result),
512
- data_generation_method=data_generation_methods,
513
- elapsed_time=0.0,
514
- hypothesis_output=[],
515
- correlation_id=correlation_id,
516
- )
517
- ctx.add_result(result)
518
- else:
519
- # When there is no `method`, then the schema error may cover multiple operations, and we can't display it in
520
- # the progress bar
521
- ctx.add_generic_error(error)
522
-
523
-
524
- def run_test(
525
- operation: APIOperation,
526
- test: Callable,
527
- checks: Iterable[CheckFunction],
528
- data_generation_methods: Iterable[DataGenerationMethod],
529
- targets: Iterable[Target],
530
- ctx: RunnerContext,
531
- headers: dict[str, Any] | None,
532
- recursion_level: int,
533
- **kwargs: Any,
534
- ) -> Generator[events.ExecutionEvent, None, None]:
535
- """A single test run with all error handling needed."""
536
- data_generation_methods = list(data_generation_methods)
537
- result = TestResult(
538
- method=operation.method.upper(),
539
- path=operation.full_path,
540
- verbose_name=operation.verbose_name,
541
- data_generation_method=data_generation_methods,
542
- )
543
- # To simplify connecting `before` and `after` events in external systems
544
- correlation_id = uuid.uuid4().hex
545
- yield events.BeforeExecution.from_operation(
546
- operation=operation,
547
- recursion_level=recursion_level,
548
- data_generation_method=data_generation_methods,
549
- correlation_id=correlation_id,
550
- )
551
- hypothesis_output: list[str] = []
552
- errors: list[Exception] = []
553
- test_start_time = time.monotonic()
554
- setup_hypothesis_database_key(test, operation)
555
-
556
- def _on_flaky(exc: Exception) -> Status:
557
- if isinstance(exc.__cause__, hypothesis.errors.DeadlineExceeded):
558
- status = Status.error
559
- result.add_error(DeadlineExceeded.from_exc(exc.__cause__))
560
- elif (
561
- hasattr(hypothesis.errors, "FlakyFailure")
562
- and isinstance(exc, hypothesis.errors.FlakyFailure)
563
- and any(isinstance(subexc, hypothesis.errors.DeadlineExceeded) for subexc in exc.exceptions)
564
- ):
565
- for sub_exc in exc.exceptions:
566
- if isinstance(sub_exc, hypothesis.errors.DeadlineExceeded):
567
- result.add_error(DeadlineExceeded.from_exc(sub_exc))
568
- status = Status.error
569
- elif errors:
570
- status = Status.error
571
- add_errors(result, errors)
572
- else:
573
- status = Status.failure
574
- result.mark_flaky()
575
- return status
576
-
577
- try:
578
- with catch_warnings(record=True) as warnings, capture_hypothesis_output() as hypothesis_output:
579
- test(
580
- ctx=ctx,
581
- checks=checks,
582
- targets=targets,
583
- result=result,
584
- errors=errors,
585
- headers=headers,
586
- data_generation_methods=data_generation_methods,
587
- **kwargs,
588
- )
589
- # Test body was not executed at all - Hypothesis did not generate any tests, but there is no error
590
- if not result.is_executed:
591
- status = Status.skip
592
- result.mark_skipped(None)
593
- else:
594
- status = Status.success
595
- except unittest.case.SkipTest as exc:
596
- # Newer Hypothesis versions raise this exception if no tests were executed
597
- status = Status.skip
598
- result.mark_skipped(exc)
599
- except CheckFailed:
600
- status = Status.failure
601
- except NonCheckError:
602
- # It could be an error in user-defined extensions, network errors or internal Schemathesis errors
603
- status = Status.error
604
- result.mark_errored()
605
- for error in deduplicate_errors(errors):
606
- result.add_error(error)
607
- except hypothesis.errors.Flaky as exc:
608
- status = _on_flaky(exc)
609
- except MultipleFailures:
610
- # Schemathesis may detect multiple errors that come from different check results
611
- # They raise different "grouped" exceptions
612
- if errors:
613
- status = Status.error
614
- add_errors(result, errors)
615
- else:
616
- status = Status.failure
617
- except hypothesis.errors.Unsatisfiable:
618
- # We need more clear error message here
619
- status = Status.error
620
- result.add_error(hypothesis.errors.Unsatisfiable("Failed to generate test cases for this API operation"))
621
- except KeyboardInterrupt:
622
- yield events.Interrupted()
623
- return
624
- except SkipTest as exc:
625
- status = Status.skip
626
- result.mark_skipped(exc)
627
- except AssertionError as exc: # May come from `hypothesis-jsonschema` or `hypothesis`
628
- status = Status.error
629
- try:
630
- operation.schema.validate()
631
- msg = "Unexpected error during testing of this API operation"
632
- exc_msg = str(exc)
633
- if exc_msg:
634
- msg += f": {exc_msg}"
635
- try:
636
- raise InternalError(msg) from exc
637
- except InternalError as exc:
638
- error = exc
639
- except ValidationError as exc:
640
- error = OperationSchemaError.from_jsonschema_error(
641
- exc,
642
- path=operation.path,
643
- method=operation.method,
644
- full_path=operation.schema.get_full_path(operation.path),
645
- )
646
- result.add_error(error)
647
- except HypothesisRefResolutionError:
648
- status = Status.error
649
- result.add_error(RecursiveReferenceError(RECURSIVE_REFERENCE_ERROR_MESSAGE))
650
- except InvalidArgument as error:
651
- status = Status.error
652
- message = get_invalid_regular_expression_message(warnings)
653
- if message:
654
- # `hypothesis-jsonschema` emits a warning on invalid regular expression syntax
655
- result.add_error(InvalidRegularExpression.from_hypothesis_jsonschema_message(message))
656
- else:
657
- result.add_error(error)
658
- except hypothesis.errors.DeadlineExceeded as error:
659
- status = Status.error
660
- result.add_error(DeadlineExceeded.from_exc(error))
661
- except JsonSchemaError as error:
662
- status = Status.error
663
- result.add_error(InvalidRegularExpression.from_schema_error(error, from_examples=False))
664
- except Exception as error:
665
- status = Status.error
666
- # Likely a YAML parsing issue. E.g. `00:00:00.00` (without quotes) is parsed as float `0.0`
667
- if str(error) == "first argument must be string or compiled pattern":
668
- result.add_error(
669
- InvalidRegularExpression(
670
- "Invalid `pattern` value: expected a string. "
671
- "If your schema is in YAML, ensure `pattern` values are quoted",
672
- is_valid_type=False,
673
- )
674
- )
675
- else:
676
- result.add_error(error)
677
- if status == Status.success and ctx.no_failfast and any(check.value == Status.failure for check in result.checks):
678
- status = Status.failure
679
- if has_unsatisfied_example_mark(test):
680
- status = Status.error
681
- result.add_error(
682
- hypothesis.errors.Unsatisfiable("Failed to generate test cases from examples for this API operation")
683
- )
684
- non_serializable = get_non_serializable_mark(test)
685
- if non_serializable is not None and status != Status.error:
686
- status = Status.error
687
- media_types = ", ".join(non_serializable.media_types)
688
- result.add_error(
689
- SerializationNotPossible(
690
- "Failed to generate test cases from examples for this API operation because of"
691
- f" unsupported payload media types: {media_types}\n{SERIALIZERS_SUGGESTION_MESSAGE}",
692
- media_types=non_serializable.media_types,
693
- )
694
- )
695
- invalid_regex = get_invalid_regex_mark(test)
696
- if invalid_regex is not None and status != Status.error:
697
- status = Status.error
698
- result.add_error(InvalidRegularExpression.from_schema_error(invalid_regex, from_examples=True))
699
- invalid_headers = get_invalid_example_headers_mark(test)
700
- if invalid_headers:
701
- status = Status.error
702
- result.add_error(InvalidHeadersExample.from_headers(invalid_headers))
703
- test_elapsed_time = time.monotonic() - test_start_time
704
- # DEPRECATED: Seed is the same per test run
705
- # Fetch seed value, hypothesis generates it during test execution
706
- # It may be `None` if the `derandomize` config option is set to `True`
707
- result.seed = getattr(test, "_hypothesis_internal_use_seed", None) or getattr(
708
- test, "_hypothesis_internal_use_generated_seed", None
709
- )
710
- ctx.add_result(result)
711
- for status_code in (401, 403):
712
- if has_too_many_responses_with_status(result, status_code):
713
- ctx.add_warning(TOO_MANY_RESPONSES_WARNING_TEMPLATE.format(f"`{operation.verbose_name}`", status_code))
714
- yield events.AfterExecution.from_result(
715
- result=result,
716
- status=status,
717
- elapsed_time=test_elapsed_time,
718
- hypothesis_output=hypothesis_output,
719
- operation=operation,
720
- data_generation_method=data_generation_methods,
721
- correlation_id=correlation_id,
722
- )
723
-
724
-
725
- TOO_MANY_RESPONSES_WARNING_TEMPLATE = (
726
- "Most of the responses from {} have a {} status code. Did you specify proper API credentials?"
727
- )
728
- TOO_MANY_RESPONSES_THRESHOLD = 0.9
729
-
730
-
731
- def has_too_many_responses_with_status(result: TestResult, status_code: int) -> bool:
732
- # It is faster than creating an intermediate list
733
- unauthorized_count = 0
734
- total = 0
735
- for check in result.checks:
736
- if check.response is not None:
737
- if check.response.status_code == status_code:
738
- unauthorized_count += 1
739
- total += 1
740
- if not total:
741
- return False
742
- return unauthorized_count / total >= TOO_MANY_RESPONSES_THRESHOLD
743
-
744
-
745
- ALL_NOT_FOUND_WARNING_MESSAGE = "All API responses have a 404 status code. Did you specify the proper API location?"
746
-
747
-
748
- def setup_hypothesis_database_key(test: Callable, operation: APIOperation) -> None:
749
- """Make Hypothesis use separate database entries for every API operation.
750
-
751
- It increases the effectiveness of the Hypothesis database in the CLI.
752
- """
753
- # Hypothesis's function digest depends on the test function signature. To reflect it for the web API case,
754
- # we use all API operation parameters in the digest.
755
- extra = operation.verbose_name.encode("utf8")
756
- for parameter in operation.iter_parameters():
757
- extra += parameter.serialize(operation).encode("utf8")
758
- test.hypothesis.inner_test._hypothesis_internal_add_digest = extra # type: ignore
759
-
760
-
761
- def get_invalid_regular_expression_message(warnings: list[WarningMessage]) -> str | None:
762
- for warning in warnings:
763
- message = str(warning.message)
764
- if "is not valid syntax for a Python regular expression" in message:
765
- return message
766
- return None
767
-
768
-
769
- MEMORY_ADDRESS_RE = re.compile("0x[0-9a-fA-F]+")
770
- URL_IN_ERROR_MESSAGE_RE = re.compile(r"Max retries exceeded with url: .*? \(Caused by")
771
-
772
-
773
- def add_errors(result: TestResult, errors: list[Exception]) -> None:
774
- group_errors(errors)
775
- for error in deduplicate_errors(errors):
776
- result.add_error(error)
777
-
778
-
779
- def group_errors(errors: list[Exception]) -> None:
780
- """Group errors of the same kind info a single one, avoiding duplicate error messages."""
781
- serialization_errors = [error for error in errors if isinstance(error, SerializationNotPossible)]
782
- if len(serialization_errors) > 1:
783
- errors[:] = [error for error in errors if not isinstance(error, SerializationNotPossible)]
784
- media_types: list[str] = functools.reduce(
785
- operator.iadd, (entry.media_types for entry in serialization_errors), []
786
- )
787
- errors.append(SerializationNotPossible.from_media_types(*media_types))
788
-
789
-
790
- def canonicalize_error_message(error: Exception, include_traceback: bool = True) -> str:
791
- message = format_exception(error, include_traceback)
792
- # Replace memory addresses with a fixed string
793
- message = MEMORY_ADDRESS_RE.sub("0xbaaaaaaaaaad", message)
794
- return URL_IN_ERROR_MESSAGE_RE.sub("", message)
795
-
796
-
797
- def deduplicate_errors(errors: list[Exception]) -> Generator[Exception, None, None]:
798
- """Deduplicate errors by their messages + tracebacks."""
799
- seen = set()
800
- for error in errors:
801
- message = canonicalize_error_message(error)
802
- if message in seen:
803
- continue
804
- seen.add(message)
805
- yield error
806
-
807
-
808
- def run_checks(
809
- *,
810
- case: Case,
811
- ctx: CheckContext,
812
- checks: Iterable[CheckFunction],
813
- check_results: list[Check],
814
- result: TestResult,
815
- response: GenericResponse,
816
- elapsed_time: float,
817
- max_response_time: int | None = None,
818
- no_failfast: bool,
819
- ) -> None:
820
- errors = []
821
-
822
- def add_single_failure(error: AssertionError) -> None:
823
- msg = maybe_set_assertion_message(error, check_name)
824
- errors.append(error)
825
- if isinstance(error, CheckFailed):
826
- context = error.context
827
- else:
828
- context = None
829
- check_results.append(result.add_failure(check_name, copied_case, response, elapsed_time, msg, context))
830
-
831
- for check in checks:
832
- check_name = check.__name__
833
- copied_case = case.partial_deepcopy()
834
- try:
835
- skip_check = check(ctx, response, copied_case)
836
- if not skip_check:
837
- check_result = result.add_success(check_name, copied_case, response, elapsed_time)
838
- check_results.append(check_result)
839
- except AssertionError as exc:
840
- add_single_failure(exc)
841
- except MultipleFailures as exc:
842
- for exception in exc.exceptions:
843
- add_single_failure(exception)
844
-
845
- if max_response_time:
846
- if elapsed_time > max_response_time:
847
- message = _make_max_response_time_failure_message(elapsed_time, max_response_time)
848
- errors.append(AssertionError(message))
849
- result.add_failure(
850
- "max_response_time",
851
- case,
852
- response,
853
- elapsed_time,
854
- message,
855
- failures.ResponseTimeExceeded(message=message, elapsed=elapsed_time, deadline=max_response_time),
856
- )
857
- else:
858
- result.add_success("max_response_time", case, response, elapsed_time)
859
-
860
- if errors and not no_failfast:
861
- raise get_grouped_exception(case.operation.verbose_name, *errors)(causes=tuple(errors))
862
-
863
-
864
- def run_targets(targets: Iterable[Callable], context: TargetContext) -> None:
865
- for target in targets:
866
- value = target(context)
867
- hypothesis.target(value, label=target.__name__)
868
-
869
-
870
- def add_cases(case: Case, response: GenericResponse, test: Callable, *args: Any) -> None:
871
- context = HookContext(case.operation)
872
- for case_hook in get_all_by_name("add_case"):
873
- _case = case_hook(context, case.partial_deepcopy(), response)
874
- # run additional test if _case is not an empty value
875
- if _case:
876
- test(_case, *args)
877
-
878
-
879
- @dataclass
880
- class ErrorCollector:
881
- """Collect exceptions that are not related to failed checks.
882
-
883
- Such exceptions may be considered as multiple failures or flakiness by Hypothesis. In both cases, Hypothesis hides
884
- exception information that, in our case, is helpful for the end-user. It either indicates errors in user-defined
885
- extensions, network-related errors, or internal Schemathesis errors. In all cases, this information is useful for
886
- debugging.
887
-
888
- To mitigate this, we gather all exceptions manually via this context manager to avoid interfering with the test
889
- function signatures, which are used by Hypothesis.
890
- """
891
-
892
- errors: list[Exception]
893
-
894
- def __enter__(self) -> ErrorCollector:
895
- return self
896
-
897
- def __exit__(
898
- self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
899
- ) -> Literal[False]:
900
- # Don't do anything special if:
901
- # - Tests are successful
902
- # - Checks failed
903
- # - The testing process is interrupted
904
- if not exc_type or issubclass(exc_type, CheckFailed) or not issubclass(exc_type, Exception):
905
- return False
906
- # These exceptions are needed for control flow on the Hypothesis side. E.g. rejecting unsatisfiable examples
907
- if isinstance(exc_val, HypothesisException):
908
- raise
909
- # Exception value is not `None` and is a subclass of `Exception` at this point
910
- exc_val = cast(Exception, exc_val)
911
- self.errors.append(exc_val.with_traceback(exc_tb))
912
- raise NonCheckError from None
913
-
914
-
915
- def _force_data_generation_method(values: list[DataGenerationMethod], case: Case) -> None:
916
- # Set data generation method to the one that actually used
917
- data_generation_method = cast(DataGenerationMethod, case.data_generation_method)
918
- values[:] = [data_generation_method]
919
-
920
-
921
- def cached_test_func(f: Callable) -> Callable:
922
- def wrapped(*, ctx: RunnerContext, case: Case, **kwargs: Any) -> None:
923
- if ctx.unique_data:
924
- cached = ctx.get_cached_outcome(case)
925
- if isinstance(cached, BaseException):
926
- raise cached
927
- elif cached is None:
928
- return None
929
- try:
930
- f(ctx=ctx, case=case, **kwargs)
931
- except BaseException as exc:
932
- ctx.cache_outcome(case, exc)
933
- raise
934
- else:
935
- ctx.cache_outcome(case, None)
936
- else:
937
- f(ctx=ctx, case=case, **kwargs)
938
-
939
- wrapped.__name__ = f.__name__
940
-
941
- return wrapped
942
-
943
-
944
- @cached_test_func
945
- def network_test(
946
- *,
947
- ctx: RunnerContext,
948
- case: Case,
949
- checks: Iterable[CheckFunction],
950
- targets: Iterable[Target],
951
- result: TestResult,
952
- session: requests.Session,
953
- request_config: RequestConfig,
954
- store_interactions: bool,
955
- headers: dict[str, Any] | None,
956
- feedback: Feedback | None,
957
- max_response_time: int | None,
958
- data_generation_methods: list[DataGenerationMethod],
959
- dry_run: bool,
960
- errors: list[Exception],
961
- ) -> None:
962
- """A single test body will be executed against the target."""
963
- with ErrorCollector(errors):
964
- _force_data_generation_method(data_generation_methods, case)
965
- result.mark_executed()
966
- headers = headers or {}
967
- if "user-agent" not in {header.lower() for header in headers}:
968
- headers["User-Agent"] = USER_AGENT
969
- if not dry_run:
970
- args = (
971
- ctx,
972
- checks,
973
- targets,
974
- result,
975
- session,
976
- request_config,
977
- store_interactions,
978
- headers,
979
- feedback,
980
- max_response_time,
981
- )
982
- response = _network_test(case, *args)
983
- add_cases(case, response, _network_test, *args)
984
- elif store_interactions:
985
- result.store_requests_response(case, None, Status.skip, [], headers=headers, session=session)
986
-
987
-
988
- def _network_test(
989
- case: Case,
990
- ctx: RunnerContext,
991
- checks: Iterable[CheckFunction],
992
- targets: Iterable[Target],
993
- result: TestResult,
994
- session: requests.Session,
995
- request_config: RequestConfig,
996
- store_interactions: bool,
997
- headers: dict[str, Any] | None,
998
- feedback: Feedback | None,
999
- max_response_time: int | None,
1000
- ) -> requests.Response:
1001
- check_results: list[Check] = []
1002
- hook_context = HookContext(operation=case.operation)
1003
- kwargs: dict[str, Any] = {
1004
- "session": session,
1005
- "headers": headers,
1006
- "timeout": request_config.prepared_timeout,
1007
- "verify": request_config.tls_verify,
1008
- "cert": request_config.cert,
1009
- }
1010
- if request_config.proxy is not None:
1011
- kwargs["proxies"] = {"all": request_config.proxy}
1012
- hooks.dispatch("process_call_kwargs", hook_context, case, kwargs)
1013
- try:
1014
- response = case.call(**kwargs)
1015
- except CheckFailed as exc:
1016
- check_name = "request_timeout"
1017
- requests_kwargs = RequestsTransport().serialize_case(case, base_url=case.get_full_base_url(), headers=headers)
1018
- request = requests.Request(**requests_kwargs).prepare()
1019
- elapsed = cast(
1020
- float, request_config.prepared_timeout
1021
- ) # It is defined and not empty, since the exception happened
1022
- check_result = result.add_failure(
1023
- check_name, case, None, elapsed, f"Response timed out after {1000 * elapsed:.2f}ms", exc.context, request
1024
- )
1025
- check_results.append(check_result)
1026
- if store_interactions:
1027
- result.store_requests_response(case, None, Status.failure, [check_result], headers=headers, session=session)
1028
- raise exc
1029
- context = TargetContext(case=case, response=response, response_time=response.elapsed.total_seconds())
1030
- run_targets(targets, context)
1031
- status = Status.success
1032
-
1033
- check_ctx = CheckContext(
1034
- override=ctx.override,
1035
- auth=ctx.auth,
1036
- headers=CaseInsensitiveDict(headers) if headers else None,
1037
- config=ctx.checks_config,
1038
- transport_kwargs=kwargs,
1039
- )
1040
- try:
1041
- run_checks(
1042
- case=case,
1043
- ctx=check_ctx,
1044
- checks=checks,
1045
- check_results=check_results,
1046
- result=result,
1047
- response=response,
1048
- elapsed_time=context.response_time * 1000,
1049
- max_response_time=max_response_time,
1050
- no_failfast=ctx.no_failfast,
1051
- )
1052
- except CheckFailed:
1053
- status = Status.failure
1054
- raise
1055
- finally:
1056
- if feedback is not None:
1057
- feedback.add_test_case(case, response)
1058
- if store_interactions:
1059
- result.store_requests_response(case, response, status, check_results, headers=headers, session=session)
1060
- return response
1061
-
1062
-
1063
- @contextmanager
1064
- def get_session(auth: HTTPDigestAuth | RawAuth | None = None) -> Generator[requests.Session, None, None]:
1065
- with requests.Session() as session:
1066
- if auth is not None:
1067
- session.auth = auth
1068
- yield session
1069
-
1070
-
1071
- @cached_test_func
1072
- def wsgi_test(
1073
- ctx: RunnerContext,
1074
- case: Case,
1075
- checks: Iterable[CheckFunction],
1076
- targets: Iterable[Target],
1077
- result: TestResult,
1078
- auth: RawAuth | None,
1079
- auth_type: str | None,
1080
- headers: dict[str, Any] | None,
1081
- store_interactions: bool,
1082
- feedback: Feedback | None,
1083
- max_response_time: int | None,
1084
- data_generation_methods: list[DataGenerationMethod],
1085
- dry_run: bool,
1086
- errors: list[Exception],
1087
- ) -> None:
1088
- with ErrorCollector(errors):
1089
- _force_data_generation_method(data_generation_methods, case)
1090
- result.mark_executed()
1091
- headers = prepare_wsgi_headers(headers, auth, auth_type)
1092
- if not dry_run:
1093
- args = (
1094
- ctx,
1095
- checks,
1096
- targets,
1097
- result,
1098
- headers,
1099
- store_interactions,
1100
- feedback,
1101
- max_response_time,
1102
- )
1103
- response = _wsgi_test(case, *args)
1104
- add_cases(case, response, _wsgi_test, *args)
1105
- elif store_interactions:
1106
- result.store_wsgi_response(case, None, headers, None, Status.skip, [])
1107
-
1108
-
1109
- def _wsgi_test(
1110
- case: Case,
1111
- ctx: RunnerContext,
1112
- checks: Iterable[CheckFunction],
1113
- targets: Iterable[Target],
1114
- result: TestResult,
1115
- headers: dict[str, Any],
1116
- store_interactions: bool,
1117
- feedback: Feedback | None,
1118
- max_response_time: int | None,
1119
- ) -> WSGIResponse:
1120
- from ...transports.responses import WSGIResponse
1121
-
1122
- with catching_logs(LogCaptureHandler(), level=logging.DEBUG) as recorded:
1123
- hook_context = HookContext(operation=case.operation)
1124
- kwargs: dict[str, Any] = {"headers": headers}
1125
- hooks.dispatch("process_call_kwargs", hook_context, case, kwargs)
1126
- response = cast(WSGIResponse, case.call(**kwargs))
1127
- context = TargetContext(case=case, response=response, response_time=response.elapsed.total_seconds())
1128
- run_targets(targets, context)
1129
- result.logs.extend(recorded.records)
1130
- status = Status.success
1131
- check_results: list[Check] = []
1132
- check_ctx = CheckContext(
1133
- override=ctx.override,
1134
- auth=ctx.auth,
1135
- headers=CaseInsensitiveDict(headers) if headers else None,
1136
- config=ctx.checks_config,
1137
- transport_kwargs=kwargs,
1138
- )
1139
- try:
1140
- run_checks(
1141
- case=case,
1142
- ctx=check_ctx,
1143
- checks=checks,
1144
- check_results=check_results,
1145
- result=result,
1146
- response=response,
1147
- elapsed_time=context.response_time * 1000,
1148
- max_response_time=max_response_time,
1149
- no_failfast=ctx.no_failfast,
1150
- )
1151
- except CheckFailed:
1152
- status = Status.failure
1153
- raise
1154
- finally:
1155
- if feedback is not None:
1156
- feedback.add_test_case(case, response)
1157
- if store_interactions:
1158
- result.store_wsgi_response(case, response, headers, response.elapsed.total_seconds(), status, check_results)
1159
- return response
1160
-
1161
-
1162
- @cached_test_func
1163
- def asgi_test(
1164
- ctx: RunnerContext,
1165
- case: Case,
1166
- checks: Iterable[CheckFunction],
1167
- targets: Iterable[Target],
1168
- result: TestResult,
1169
- store_interactions: bool,
1170
- headers: dict[str, Any] | None,
1171
- feedback: Feedback | None,
1172
- max_response_time: int | None,
1173
- data_generation_methods: list[DataGenerationMethod],
1174
- dry_run: bool,
1175
- errors: list[Exception],
1176
- ) -> None:
1177
- """A single test body will be executed against the target."""
1178
- with ErrorCollector(errors):
1179
- _force_data_generation_method(data_generation_methods, case)
1180
- result.mark_executed()
1181
- headers = headers or {}
1182
-
1183
- if not dry_run:
1184
- args = (
1185
- ctx,
1186
- checks,
1187
- targets,
1188
- result,
1189
- store_interactions,
1190
- headers,
1191
- feedback,
1192
- max_response_time,
1193
- )
1194
- response = _asgi_test(case, *args)
1195
- add_cases(case, response, _asgi_test, *args)
1196
- elif store_interactions:
1197
- result.store_requests_response(case, None, Status.skip, [], headers=headers, session=None)
1198
-
1199
-
1200
- def _asgi_test(
1201
- case: Case,
1202
- ctx: RunnerContext,
1203
- checks: Iterable[CheckFunction],
1204
- targets: Iterable[Target],
1205
- result: TestResult,
1206
- store_interactions: bool,
1207
- headers: dict[str, Any] | None,
1208
- feedback: Feedback | None,
1209
- max_response_time: int | None,
1210
- ) -> requests.Response:
1211
- hook_context = HookContext(operation=case.operation)
1212
- kwargs: dict[str, Any] = {"headers": headers}
1213
- hooks.dispatch("process_call_kwargs", hook_context, case, kwargs)
1214
- response = case.call(**kwargs)
1215
- context = TargetContext(case=case, response=response, response_time=response.elapsed.total_seconds())
1216
- run_targets(targets, context)
1217
- status = Status.success
1218
- check_results: list[Check] = []
1219
- check_ctx = CheckContext(
1220
- override=ctx.override,
1221
- auth=ctx.auth,
1222
- headers=CaseInsensitiveDict(headers) if headers else None,
1223
- config=ctx.checks_config,
1224
- transport_kwargs=kwargs,
1225
- )
1226
- try:
1227
- run_checks(
1228
- case=case,
1229
- ctx=check_ctx,
1230
- checks=checks,
1231
- check_results=check_results,
1232
- result=result,
1233
- response=response,
1234
- elapsed_time=context.response_time * 1000,
1235
- max_response_time=max_response_time,
1236
- no_failfast=ctx.no_failfast,
1237
- )
1238
- except CheckFailed:
1239
- status = Status.failure
1240
- raise
1241
- finally:
1242
- if feedback is not None:
1243
- feedback.add_test_case(case, response)
1244
- if store_interactions:
1245
- result.store_requests_response(case, response, status, check_results, headers, session=None)
1246
- return response