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