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,936 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import os
4
- import platform
5
- import shutil
6
- import textwrap
7
- import time
8
- from importlib import metadata
9
- from types import GeneratorType
10
- from typing import TYPE_CHECKING, Any, Generator, Literal, cast
11
-
12
- import click
13
-
14
- from ... import experimental, service
15
- from ...constants import (
16
- DISCORD_LINK,
17
- FALSE_VALUES,
18
- FLAKY_FAILURE_MESSAGE,
19
- GITHUB_APP_LINK,
20
- ISSUE_TRACKER_URL,
21
- REPORT_SUGGESTION_ENV_VAR,
22
- SCHEMATHESIS_TEST_CASE_HEADER,
23
- SCHEMATHESIS_VERSION,
24
- )
25
- from ...exceptions import (
26
- RuntimeErrorType,
27
- extract_requests_exception_details,
28
- format_exception,
29
- )
30
- from ...experimental import GLOBAL_EXPERIMENTS
31
- from ...internal.output import prepare_response_payload
32
- from ...internal.result import Ok
33
- from ...models import Status
34
- from ...runner import events
35
- from ...runner.events import InternalErrorType, SchemaErrorType
36
- from ...runner.probes import ProbeOutcome
37
- from ...runner.serialization import SerializedError, SerializedTestResult
38
- from ...service.models import AnalysisSuccess, ErrorState, UnknownExtension
39
- from ...stateful import events as stateful_events
40
- from ...stateful.sink import StateMachineSink
41
- from ..context import ExecutionContext, FileReportContext, ServiceReportContext
42
- from ..handlers import EventHandler
43
- from ..reporting import TEST_CASE_ID_TITLE, get_runtime_error_suggestion, group_by_case, split_traceback
44
-
45
- if TYPE_CHECKING:
46
- from queue import Queue
47
-
48
- import requests
49
-
50
- SPINNER_REPETITION_NUMBER = 10
51
- IO_ENCODING = os.getenv("PYTHONIOENCODING", "utf-8")
52
-
53
-
54
- def get_terminal_width() -> int:
55
- # Some CI/CD providers (e.g. CircleCI) return a (0, 0) terminal size so provide a default
56
- return shutil.get_terminal_size((80, 24)).columns
57
-
58
-
59
- def display_section_name(title: str, separator: str = "=", **kwargs: Any) -> None:
60
- """Print section name with separators in terminal with the given title nicely centered."""
61
- message = f" {title} ".center(get_terminal_width(), separator)
62
- kwargs.setdefault("bold", True)
63
- click.secho(message, **kwargs)
64
-
65
-
66
- def display_subsection(result: SerializedTestResult, color: str | None = "red") -> None:
67
- display_section_name(result.verbose_name, "_", fg=color)
68
-
69
-
70
- def get_percentage(position: int, length: int) -> str:
71
- """Format completion percentage in square brackets."""
72
- percentage_message = f"{position * 100 // length}%".rjust(4)
73
- return f"[{percentage_message}]"
74
-
75
-
76
- def display_execution_result(context: ExecutionContext, status: Literal["success", "failure", "error", "skip"]) -> None:
77
- """Display an appropriate symbol for the given event's execution result."""
78
- symbol, color = {
79
- "success": (".", "green"),
80
- "failure": ("F", "red"),
81
- "error": ("E", "red"),
82
- "skip": ("S", "yellow"),
83
- }[status]
84
- context.current_line_length += len(symbol)
85
- click.secho(symbol, nl=False, fg=color)
86
-
87
-
88
- def display_percentage(context: ExecutionContext, event: events.AfterExecution) -> None:
89
- """Add the current progress in % to the right side of the current line."""
90
- operations_count = cast(int, context.operations_count) # is already initialized via `Initialized` event
91
- current_percentage = get_percentage(context.operations_processed, operations_count)
92
- styled = click.style(current_percentage, fg="cyan")
93
- # Total length of the message, so it will fill to the right border of the terminal.
94
- # Padding is already taken into account in `context.current_line_length`
95
- length = max(get_terminal_width() - context.current_line_length + len(styled) - len(current_percentage), 1)
96
- template = f"{{:>{length}}}"
97
- click.echo(template.format(styled))
98
-
99
-
100
- def display_summary(event: events.Finished) -> None:
101
- message, color = get_summary_output(event)
102
- display_section_name(message, fg=color)
103
-
104
-
105
- def get_summary_message_parts(event: events.Finished) -> list[str]:
106
- parts = []
107
- passed = event.passed_count
108
- if passed:
109
- parts.append(f"{passed} passed")
110
- failed = event.failed_count
111
- if failed:
112
- parts.append(f"{failed} failed")
113
- errored = event.errored_count
114
- if errored:
115
- parts.append(f"{errored} errored")
116
- skipped = event.skipped_count
117
- if skipped:
118
- parts.append(f"{skipped} skipped")
119
- return parts
120
-
121
-
122
- def get_summary_output(event: events.Finished) -> tuple[str, str]:
123
- parts = get_summary_message_parts(event)
124
- if not parts:
125
- message = "Empty test suite"
126
- color = "yellow"
127
- else:
128
- message = f'{", ".join(parts)} in {event.running_time:.2f}s'
129
- if event.has_failures or event.has_errors:
130
- color = "red"
131
- elif event.skipped_count > 0:
132
- color = "yellow"
133
- else:
134
- color = "green"
135
- return message, color
136
-
137
-
138
- def display_hypothesis_output(hypothesis_output: list[str]) -> None:
139
- """Show falsifying examples from Hypothesis output if there are any."""
140
- if hypothesis_output:
141
- display_section_name("HYPOTHESIS OUTPUT")
142
- output = "\n".join(hypothesis_output)
143
- click.secho(output, fg="red")
144
-
145
-
146
- def display_errors(context: ExecutionContext, event: events.Finished) -> None:
147
- """Display all errors in the test run."""
148
- probes = context.probes or []
149
- has_probe_errors = any(probe.outcome == ProbeOutcome.ERROR for probe in probes)
150
- if not event.has_errors and not has_probe_errors:
151
- return
152
-
153
- display_section_name("ERRORS")
154
- should_display_full_traceback_message = False
155
- if context.workers_num > 1:
156
- # Events may come out of order when multiple workers are involved
157
- # Sort them to get a stable output
158
- results = sorted(context.results, key=lambda r: r.verbose_name)
159
- else:
160
- results = context.results
161
- for result in results:
162
- if not result.has_errors:
163
- continue
164
- should_display_full_traceback_message |= display_single_error(context, result)
165
- if event.generic_errors:
166
- display_generic_errors(context, event.generic_errors)
167
- if has_probe_errors:
168
- display_section_name("API Probe errors", "_", fg="red")
169
- for probe in probes:
170
- if probe.error is not None:
171
- error = SerializedError.from_exception(probe.error)
172
- _display_error(context, error)
173
- if should_display_full_traceback_message and not context.show_trace:
174
- click.secho(
175
- "\nAdd this option to your command line parameters to see full tracebacks: --show-trace",
176
- fg="red",
177
- )
178
- click.secho(
179
- f"\nNeed more help?\n" f" Join our Discord server: {DISCORD_LINK}",
180
- fg="red",
181
- )
182
-
183
-
184
- def display_single_error(context: ExecutionContext, result: SerializedTestResult) -> bool:
185
- display_subsection(result)
186
- should_display_full_traceback_message = False
187
- first = True
188
- for error in result.errors:
189
- if first:
190
- first = False
191
- else:
192
- click.echo()
193
- should_display_full_traceback_message |= _display_error(context, error)
194
- return should_display_full_traceback_message
195
-
196
-
197
- def display_generic_errors(context: ExecutionContext, errors: list[SerializedError]) -> None:
198
- for error in errors:
199
- display_section_name(error.title or "Generic error", "_", fg="red")
200
- _display_error(context, error)
201
-
202
-
203
- def display_full_traceback_message(error: SerializedError) -> bool:
204
- # Some errors should not trigger the message that suggests to show full tracebacks to the user
205
- return (
206
- not error.exception.startswith(
207
- (
208
- "DeadlineExceeded",
209
- "OperationSchemaError",
210
- "requests.exceptions",
211
- "SerializationNotPossible",
212
- "hypothesis.errors.FailedHealthCheck",
213
- "hypothesis.errors.InvalidArgument: Scalar ",
214
- "hypothesis.errors.InvalidArgument: min_size=",
215
- "hypothesis.errors.Unsatisfiable",
216
- )
217
- )
218
- and "can never generate an example, because min_size is larger than Hypothesis supports." not in error.exception
219
- )
220
-
221
-
222
- def bold(option: str) -> str:
223
- return click.style(option, bold=True)
224
-
225
-
226
- DISABLE_SSL_SUGGESTION = f"Bypass SSL verification with {bold('`--request-tls-verify=false`')}."
227
- DISABLE_SCHEMA_VALIDATION_SUGGESTION = (
228
- f"Bypass validation using {bold('`--validate-schema=false`')}. Caution: May cause unexpected errors."
229
- )
230
-
231
-
232
- def _format_health_check_suggestion(label: str) -> str:
233
- return f"Bypass this health check using {bold(f'`--hypothesis-suppress-health-check={label}`')}."
234
-
235
-
236
- RUNTIME_ERROR_SUGGESTIONS = {
237
- RuntimeErrorType.CONNECTION_SSL: DISABLE_SSL_SUGGESTION,
238
- RuntimeErrorType.HYPOTHESIS_DEADLINE_EXCEEDED: (
239
- f"Adjust the deadline using {bold('`--hypothesis-deadline=MILLIS`')} or "
240
- f"disable with {bold('`--hypothesis-deadline=None`')}."
241
- ),
242
- RuntimeErrorType.HYPOTHESIS_UNSATISFIABLE: "Examine the schema for inconsistencies and consider simplifying it.",
243
- RuntimeErrorType.SCHEMA_BODY_IN_GET_REQUEST: DISABLE_SCHEMA_VALIDATION_SUGGESTION,
244
- RuntimeErrorType.SCHEMA_INVALID_REGULAR_EXPRESSION: "Ensure your regex is compatible with Python's syntax.\n"
245
- "For guidance, visit: https://docs.python.org/3/library/re.html",
246
- RuntimeErrorType.HYPOTHESIS_UNSUPPORTED_GRAPHQL_SCALAR: "Define a custom strategy for it.\n"
247
- "For guidance, visit: https://schemathesis.readthedocs.io/en/stable/graphql.html#custom-scalars",
248
- RuntimeErrorType.HYPOTHESIS_HEALTH_CHECK_DATA_TOO_LARGE: _format_health_check_suggestion("data_too_large"),
249
- RuntimeErrorType.HYPOTHESIS_HEALTH_CHECK_FILTER_TOO_MUCH: _format_health_check_suggestion("filter_too_much"),
250
- RuntimeErrorType.HYPOTHESIS_HEALTH_CHECK_TOO_SLOW: _format_health_check_suggestion("too_slow"),
251
- RuntimeErrorType.HYPOTHESIS_HEALTH_CHECK_LARGE_BASE_EXAMPLE: _format_health_check_suggestion("large_base_example"),
252
- }
253
-
254
-
255
- def _display_error(context: ExecutionContext, error: SerializedError) -> bool:
256
- if error.title:
257
- if error.type == RuntimeErrorType.SCHEMA_GENERIC:
258
- click.secho("Schema Error", fg="red", bold=True)
259
- else:
260
- click.secho(error.title, fg="red", bold=True)
261
- click.echo()
262
- if error.message:
263
- click.echo(error.message)
264
- elif error.message:
265
- click.echo(error.message)
266
- else:
267
- click.echo(error.exception)
268
- if error.extras:
269
- extras = error.extras
270
- elif context.show_trace and error.type.has_useful_traceback:
271
- extras = split_traceback(error.exception_with_traceback)
272
- else:
273
- extras = []
274
- _display_extras(extras)
275
- suggestion = get_runtime_error_suggestion(error.type)
276
- _maybe_display_tip(suggestion)
277
- return display_full_traceback_message(error)
278
-
279
-
280
- def display_failures(context: ExecutionContext, event: events.Finished) -> None:
281
- """Display all failures in the test run."""
282
- if not event.has_failures:
283
- return
284
- relevant_results = [result for result in context.results if not result.is_errored]
285
- if not relevant_results:
286
- return
287
- display_section_name("FAILURES")
288
- for result in relevant_results:
289
- if not result.has_failures:
290
- continue
291
- display_failures_for_single_test(context, result)
292
-
293
-
294
- if IO_ENCODING != "utf-8":
295
-
296
- def _secho(text: str, **kwargs: Any) -> None:
297
- text = text.encode(IO_ENCODING, errors="replace").decode("utf-8")
298
- click.secho(text, **kwargs)
299
-
300
- else:
301
-
302
- def _secho(text: str, **kwargs: Any) -> None:
303
- click.secho(text, **kwargs)
304
-
305
-
306
- def display_failures_for_single_test(context: ExecutionContext, result: SerializedTestResult) -> None:
307
- """Display a failure for a single method / path."""
308
- from ...transports.responses import get_reason
309
-
310
- display_subsection(result)
311
- if result.is_flaky:
312
- click.secho(FLAKY_FAILURE_MESSAGE, fg="red")
313
- click.echo()
314
- for idx, (code_sample, group) in enumerate(group_by_case(result.checks, context.code_sample_style), 1):
315
- # Make server errors appear first in the list of checks
316
- checks = sorted(group, key=lambda c: c.name != "not_a_server_error")
317
-
318
- for check_idx, check in enumerate(checks):
319
- if check_idx == 0:
320
- click.secho(f"{idx}. {TEST_CASE_ID_TITLE}: {check.example.id}", bold=True)
321
- click.secho(f"\n- {check.title}", fg="red", bold=True)
322
- message = check.formatted_message
323
- if message:
324
- _secho(f"\n{message}", fg="red")
325
- if check_idx + 1 == len(checks):
326
- if check.response is not None:
327
- status_code = check.response.status_code
328
- reason = get_reason(status_code)
329
- response = bold(f"[{check.response.status_code}] {reason}")
330
- click.echo(f"\n{response}:")
331
- if check.response.body is not None:
332
- if not check.response.body:
333
- click.echo("\n <EMPTY>")
334
- else:
335
- encoding = check.response.encoding or "utf8"
336
- try:
337
- # Checked that is not None
338
- body = cast(bytes, check.response.deserialize_body())
339
- payload = body.decode(encoding)
340
- payload = prepare_response_payload(payload, config=context.output_config)
341
- payload = textwrap.indent(f"\n`{payload}`", prefix=" ")
342
- click.echo(payload)
343
- except UnicodeDecodeError:
344
- click.echo("\n <BINARY>")
345
- _secho(f"\n{bold('Reproduce with')}: \n\n {code_sample}\n")
346
-
347
-
348
- def display_application_logs(context: ExecutionContext, event: events.Finished) -> None:
349
- """Print logs captured during the application run."""
350
- if not event.has_logs:
351
- return
352
- display_section_name("APPLICATION LOGS")
353
- for result in context.results:
354
- if not result.has_logs:
355
- continue
356
- display_single_log(result)
357
-
358
-
359
- def display_single_log(result: SerializedTestResult) -> None:
360
- display_subsection(result, None)
361
- click.echo("\n\n".join(result.logs))
362
-
363
-
364
- def display_analysis(context: ExecutionContext) -> None:
365
- """Display schema analysis details."""
366
- import requests.exceptions
367
-
368
- if context.analysis is None:
369
- return
370
- display_section_name("SCHEMA ANALYSIS")
371
- if isinstance(context.analysis, Ok):
372
- analysis = context.analysis.ok()
373
- click.echo()
374
- if isinstance(analysis, AnalysisSuccess):
375
- click.secho(analysis.message, bold=True)
376
- click.echo(f"\nAnalysis took: {analysis.elapsed:.2f}ms")
377
- if analysis.extensions:
378
- known = []
379
- failed = []
380
- unknown = []
381
- for extension in analysis.extensions:
382
- if isinstance(extension, UnknownExtension):
383
- unknown.append(extension)
384
- elif isinstance(extension.state, ErrorState):
385
- failed.append(extension)
386
- else:
387
- known.append(extension)
388
- if known:
389
- click.echo("\nThe following extensions have been applied:\n")
390
- for extension in known:
391
- click.echo(f" - {extension.summary}")
392
- if failed:
393
- click.echo("\nThe following extensions errored:\n")
394
- for extension in failed:
395
- click.echo(f" - {extension.summary}")
396
- suggestion = f"Please, consider reporting this to our issue tracker:\n\n {ISSUE_TRACKER_URL}"
397
- click.secho(f"\n{click.style('Tip:', bold=True, fg='green')} {suggestion}")
398
- if unknown:
399
- noun = "extension" if len(unknown) == 1 else "extensions"
400
- specific_noun = "this extension" if len(unknown) == 1 else "these extensions"
401
- title = click.style("Compatibility Notice", bold=True)
402
- click.secho(f"\n{title}: {len(unknown)} {noun} not recognized:\n")
403
- for extension in unknown:
404
- click.echo(f" - {extension.summary}")
405
- suggestion = f"Consider updating the CLI to add support for {specific_noun}."
406
- click.secho(f"\n{click.style('Tip:', bold=True, fg='green')} {suggestion}")
407
- else:
408
- click.echo("\nNo extensions have been applied.")
409
- else:
410
- click.echo("An error happened during schema analysis:\n")
411
- click.secho(f" {analysis.message}", bold=True)
412
- click.echo()
413
- else:
414
- exception = context.analysis.err()
415
- suggestion = None
416
- if isinstance(exception, requests.exceptions.HTTPError):
417
- response = exception.response
418
- click.secho("Error\n", fg="red", bold=True)
419
- _display_service_network_error(response)
420
- click.echo()
421
- return
422
- if isinstance(exception, requests.RequestException):
423
- message, extras = extract_requests_exception_details(exception)
424
- suggestion = "Please check your network connection and try again."
425
- title = "Network Error"
426
- else:
427
- traceback = format_exception(exception, True)
428
- extras = split_traceback(traceback)
429
- title = "Internal Error"
430
- message = f"We apologize for the inconvenience. This appears to be an internal issue.\nPlease, consider reporting the following details to our issue tracker:\n\n {ISSUE_TRACKER_URL}"
431
- suggestion = "Please update your CLI to the latest version and try again."
432
- click.secho(f"{title}\n", fg="red", bold=True)
433
- click.echo(message)
434
- _display_extras(extras)
435
- _maybe_display_tip(suggestion)
436
- click.echo()
437
-
438
-
439
- def display_statistic(context: ExecutionContext, event: events.Finished) -> None:
440
- """Format and print statistic collected by :obj:`models.TestResult`."""
441
- display_section_name("SUMMARY")
442
- click.echo()
443
- total = event.total
444
- if context.state_machine_sink is not None:
445
- click.echo(context.state_machine_sink.transitions.to_formatted_table(get_terminal_width()))
446
- click.echo()
447
- if event.is_empty or not total:
448
- click.secho("No checks were performed.", bold=True)
449
-
450
- if total:
451
- display_checks_statistics(total)
452
-
453
- if context.cassette_path:
454
- click.echo()
455
- category = click.style("Network log", bold=True)
456
- click.secho(f"{category}: {context.cassette_path}")
457
-
458
- if context.junit_xml_file:
459
- click.echo()
460
- category = click.style("JUnit XML file", bold=True)
461
- click.secho(f"{category}: {context.junit_xml_file}")
462
-
463
- if event.warnings:
464
- click.echo()
465
- if len(event.warnings) == 1:
466
- title = click.style("WARNING:", bold=True, fg="yellow")
467
- warning = click.style(event.warnings[0], fg="yellow")
468
- click.secho(f"{title} {warning}")
469
- else:
470
- click.secho("WARNINGS:", bold=True, fg="yellow")
471
- for warning in event.warnings:
472
- click.secho(f" - {warning}", fg="yellow")
473
-
474
- if len(GLOBAL_EXPERIMENTS.enabled) > 0:
475
- click.secho("\nExperimental Features:", bold=True)
476
- for experiment in sorted(GLOBAL_EXPERIMENTS.enabled, key=lambda e: e.name):
477
- click.secho(f" - {experiment.verbose_name}: {experiment.description}")
478
- click.secho(f" Feedback: {experiment.discussion_url}")
479
- click.echo()
480
- click.echo(
481
- "Your feedback is crucial for experimental features. "
482
- "Please visit the provided URL(s) to share your thoughts."
483
- )
484
-
485
- if event.failed_count > 0:
486
- click.echo(
487
- f"\n{bold('Note')}: Use the '{SCHEMATHESIS_TEST_CASE_HEADER}' header to correlate test case ids "
488
- "from failure messages with server logs for debugging."
489
- )
490
- if context.seed is not None:
491
- seed_option = f"`--hypothesis-seed={context.seed}`"
492
- click.secho(f"\n{bold('Note')}: To replicate these test failures, rerun with {bold(seed_option)}")
493
-
494
- if context.report is not None and not context.is_interrupted:
495
- if isinstance(context.report, FileReportContext):
496
- click.echo()
497
- display_report_metadata(context.report.queue.get())
498
- click.secho(f"Report is saved to {context.report.filename}", bold=True)
499
- elif isinstance(context.report, ServiceReportContext):
500
- click.echo()
501
- handle_service_integration(context.report)
502
- else:
503
- env_var = os.getenv(REPORT_SUGGESTION_ENV_VAR)
504
- if env_var is not None and env_var.lower() in FALSE_VALUES:
505
- return
506
- click.echo(
507
- f"\n{bold('Tip')}: Use the {bold('`--report`')} CLI option to visualize test results via Schemathesis.io.\n"
508
- "We run additional conformance checks on reports from public repos."
509
- )
510
- if service.ci.detect() == service.ci.CIProvider.GITHUB:
511
- click.echo(
512
- "Optionally, for reporting results as PR comments, install the Schemathesis GitHub App:\n\n"
513
- f" {GITHUB_APP_LINK}"
514
- )
515
-
516
-
517
- def handle_service_integration(context: ServiceReportContext) -> None:
518
- """If Schemathesis.io integration is enabled, wait for the handler & print the resulting status."""
519
- event = context.queue.get()
520
- title = click.style("Upload", bold=True)
521
- if isinstance(event, service.Metadata):
522
- display_report_metadata(event)
523
- click.secho(f"Uploading reports to {context.service_base_url} ...", bold=True)
524
- event = wait_for_report_handler(context.queue, title)
525
- color = {
526
- service.Completed: "green",
527
- service.Error: "red",
528
- service.Failed: "red",
529
- service.Timeout: "red",
530
- }[event.__class__]
531
- status = click.style(event.status, fg=color, bold=True)
532
- click.echo(f"{title}: {status}\r", nl=False)
533
- click.echo()
534
- if isinstance(event, service.Error):
535
- click.echo()
536
- display_service_error(event)
537
- if isinstance(event, service.Failed):
538
- click.echo()
539
- click.echo(event.detail)
540
- if isinstance(event, service.Completed):
541
- click.echo()
542
- click.echo(event.message)
543
- click.echo()
544
- click.echo(event.next_url)
545
-
546
-
547
- def display_report_metadata(meta: service.Metadata) -> None:
548
- if meta.ci_environment is not None:
549
- click.secho(f"{meta.ci_environment.verbose_name} detected:", bold=True)
550
- for key, value in meta.ci_environment.as_env().items():
551
- if value is not None:
552
- click.secho(f" -> {key}: {value}")
553
- click.echo()
554
- click.secho(f"Compressed report size: {meta.size / 1024.0:,.0f} KB", bold=True)
555
-
556
-
557
- def display_service_unauthorized(hostname: str) -> None:
558
- click.secho("\nTo authenticate:")
559
- click.secho(f"1. Retrieve your token from {bold(hostname)}")
560
- click.secho(f"2. Execute {bold('`st auth login <TOKEN>`')}")
561
- env_var = bold(f"`{service.TOKEN_ENV_VAR}`")
562
- click.secho(
563
- f"\nAs an alternative, supply the token directly "
564
- f"using the {bold('`--schemathesis-io-token`')} option "
565
- f"or the {env_var} environment variable."
566
- )
567
- click.echo("\nFor more information, please visit: https://schemathesis.readthedocs.io/en/stable/service.html")
568
-
569
-
570
- def display_service_error(event: service.Error, message_prefix: str = "") -> None:
571
- """Show information about an error during communication with Schemathesis.io."""
572
- from requests import HTTPError, RequestException, Response
573
-
574
- if isinstance(event.exception, HTTPError):
575
- response = cast(Response, event.exception.response)
576
- _display_service_network_error(response, message_prefix)
577
- elif isinstance(event.exception, RequestException):
578
- ask_to_report(event, report_to_issues=False)
579
- else:
580
- ask_to_report(event)
581
-
582
-
583
- def _display_service_network_error(response: requests.Response, message_prefix: str = "") -> None:
584
- status_code = response.status_code
585
- if 500 <= status_code <= 599:
586
- click.secho(f"Schemathesis.io responded with HTTP {status_code}", fg="red")
587
- # Server error, should be resolved soon
588
- click.secho(
589
- "\nIt is likely that we are already notified about the issue and working on a fix\n"
590
- "Please, try again in 30 minutes",
591
- fg="red",
592
- )
593
- elif status_code == 401:
594
- # Likely an invalid token
595
- click.echo("Your CLI is not authenticated.")
596
- display_service_unauthorized("schemathesis.io")
597
- else:
598
- try:
599
- data = response.json()
600
- detail = data["detail"]
601
- click.secho(f"{message_prefix}{detail}", fg="red")
602
- except Exception:
603
- # Other client-side errors are likely caused by a bug on the CLI side
604
- click.secho(
605
- "We apologize for the inconvenience. This appears to be an internal issue.\n"
606
- "Please, consider reporting the following details to our issue "
607
- f"tracker:\n\n {ISSUE_TRACKER_URL}\n\nResponse: {response.text!r}\n"
608
- f"Status: {response.status_code}\n"
609
- f"Headers: {response.headers!r}",
610
- fg="red",
611
- )
612
- _maybe_display_tip("Please update your CLI to the latest version and try again.")
613
-
614
-
615
- SERVICE_ERROR_MESSAGE = "An error happened during uploading reports to Schemathesis.io"
616
-
617
-
618
- def ask_to_report(event: service.Error, report_to_issues: bool = True, extra: str = "") -> None:
619
- from requests import RequestException
620
-
621
- # Likely an internal Schemathesis error
622
- traceback = event.get_message(True)
623
- if isinstance(event.exception, RequestException) and event.exception.response is not None:
624
- response = f"Response: {event.exception.response.text}\n"
625
- else:
626
- response = ""
627
- if report_to_issues:
628
- ask = f"Please, consider reporting the following details to our issue tracker:\n\n {ISSUE_TRACKER_URL}\n\n"
629
- else:
630
- ask = ""
631
- click.secho(
632
- f"{SERVICE_ERROR_MESSAGE}:\n{extra}{ask}{response}\n{traceback.strip()}",
633
- fg="red",
634
- )
635
-
636
-
637
- def wait_for_report_handler(queue: Queue, title: str, timeout: float = service.WORKER_FINISH_TIMEOUT) -> service.Event:
638
- """Wait for the Schemathesis.io handler to finish its job."""
639
- start = time.monotonic()
640
- spinner = create_spinner(SPINNER_REPETITION_NUMBER)
641
- # The testing process is done, and we need to wait for the Schemathesis.io handler to finish
642
- # It might still have some data to send
643
- while queue.empty():
644
- if time.monotonic() - start >= timeout:
645
- return service.Timeout()
646
- click.echo(f"{title}: {next(spinner)}\r", nl=False)
647
- time.sleep(service.WORKER_CHECK_PERIOD)
648
- return queue.get()
649
-
650
-
651
- def create_spinner(repetitions: int) -> Generator[str, None, None]:
652
- """A simple spinner that yields its individual characters."""
653
- while True:
654
- for ch in "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏":
655
- # Skip branch coverage, as it is not possible because of the assertion above
656
- for _ in range(repetitions): # pragma: no branch
657
- yield ch
658
-
659
-
660
- def display_checks_statistics(total: dict[str, dict[str | Status, int]]) -> None:
661
- padding = 20
662
- col1_len = max(map(len, total.keys())) + padding
663
- col2_len = len(str(max(total.values(), key=lambda v: v["total"])["total"])) * 2 + padding
664
- col3_len = padding
665
- click.secho("Performed checks:", bold=True)
666
- template = f" {{:{col1_len}}}{{:{col2_len}}}{{:{col3_len}}}"
667
- for check_name, results in total.items():
668
- display_check_result(check_name, results, template)
669
-
670
-
671
- def display_check_result(check_name: str, results: dict[str | Status, int], template: str) -> None:
672
- """Show results of single check execution."""
673
- if Status.failure in results:
674
- verdict = "FAILED"
675
- color = "red"
676
- else:
677
- verdict = "PASSED"
678
- color = "green"
679
- success = results.get(Status.success, 0)
680
- total = results.get("total", 0)
681
- click.echo(template.format(check_name, f"{success} / {total} passed", click.style(verdict, fg=color, bold=True)))
682
-
683
-
684
- VERIFY_URL_SUGGESTION = "Verify that the URL points directly to the Open API schema"
685
-
686
-
687
- SCHEMA_ERROR_SUGGESTIONS = {
688
- # SSL-specific connection issue
689
- SchemaErrorType.CONNECTION_SSL: DISABLE_SSL_SUGGESTION,
690
- # Other connection problems
691
- SchemaErrorType.CONNECTION_OTHER: f"Use {bold('`--wait-for-schema=NUM`')} to wait up to NUM seconds for schema availability.",
692
- # Response issues
693
- SchemaErrorType.UNEXPECTED_CONTENT_TYPE: VERIFY_URL_SUGGESTION,
694
- SchemaErrorType.HTTP_FORBIDDEN: "Verify your API keys or authentication headers.",
695
- SchemaErrorType.HTTP_NOT_FOUND: VERIFY_URL_SUGGESTION,
696
- # OpenAPI specification issues
697
- SchemaErrorType.OPEN_API_UNSPECIFIED_VERSION: f"Include the version in the schema or manually set it with {bold('`--force-schema-version`')}.",
698
- SchemaErrorType.OPEN_API_UNSUPPORTED_VERSION: f"Proceed with {bold('`--force-schema-version`')}. Caution: May not be fully supported.",
699
- SchemaErrorType.OPEN_API_EXPERIMENTAL_VERSION: f"Proceed with {bold('`--experimental=openapi-3.1`. Caution: May not be fully supported.')}",
700
- SchemaErrorType.OPEN_API_INVALID_SCHEMA: DISABLE_SCHEMA_VALIDATION_SUGGESTION,
701
- # YAML specific issues
702
- SchemaErrorType.YAML_NUMERIC_STATUS_CODES: "Convert numeric status codes to strings.",
703
- SchemaErrorType.YAML_NON_STRING_KEYS: "Convert non-string keys to strings.",
704
- # Unclassified
705
- SchemaErrorType.UNCLASSIFIED: f"If you suspect this is a Schemathesis issue and the schema is valid, please report it and include the schema if you can:\n\n {ISSUE_TRACKER_URL}",
706
- }
707
-
708
-
709
- def should_skip_suggestion(context: ExecutionContext, event: events.InternalError) -> bool:
710
- return event.subtype == SchemaErrorType.CONNECTION_OTHER and context.wait_for_schema is not None
711
-
712
-
713
- def _display_extras(extras: list[str]) -> None:
714
- if extras:
715
- click.echo()
716
- for extra in extras:
717
- click.secho(f" {extra}")
718
-
719
-
720
- def _maybe_display_tip(suggestion: str | None) -> None:
721
- # Display suggestion if any
722
- if suggestion is not None:
723
- click.secho(f"\n{click.style('Tip:', bold=True, fg='green')} {suggestion}")
724
-
725
-
726
- def display_internal_error(context: ExecutionContext, event: events.InternalError) -> None:
727
- click.secho(event.title, fg="red", bold=True)
728
- click.echo()
729
- click.secho(event.message)
730
- if event.type == InternalErrorType.SCHEMA:
731
- extras = event.extras
732
- elif context.show_trace:
733
- extras = split_traceback(event.exception_with_traceback)
734
- else:
735
- extras = [event.exception]
736
- _display_extras(extras)
737
- if not should_skip_suggestion(context, event):
738
- if event.type == InternalErrorType.SCHEMA and isinstance(event.subtype, SchemaErrorType):
739
- suggestion = SCHEMA_ERROR_SUGGESTIONS.get(event.subtype)
740
- elif context.show_trace:
741
- suggestion = (
742
- f"Please consider reporting the traceback above to our issue tracker:\n\n {ISSUE_TRACKER_URL}."
743
- )
744
- else:
745
- suggestion = f"To see full tracebacks, add {bold('`--show-trace`')} to your CLI options"
746
- _maybe_display_tip(suggestion)
747
-
748
-
749
- def handle_initialized(context: ExecutionContext, event: events.Initialized) -> None:
750
- """Display information about the test session."""
751
- context.operations_count = cast(int, event.operations_count) # INVARIANT: should not be `None`
752
- context.seed = event.seed
753
- display_section_name("Schemathesis test session starts")
754
- if context.verbosity > 0:
755
- versions = (
756
- f"platform {platform.system()} -- "
757
- f"Python {platform.python_version()}, "
758
- f"schemathesis-{SCHEMATHESIS_VERSION}, "
759
- f"hypothesis-{metadata.version('hypothesis')}, "
760
- f"hypothesis_jsonschema-{metadata.version('hypothesis_jsonschema')}, "
761
- f"jsonschema-{metadata.version('jsonschema')}"
762
- )
763
- click.echo(versions)
764
- click.echo(f"rootdir: {os.getcwd()}")
765
- click.echo(f"Hypothesis: {context.hypothesis_settings.show_changed()}")
766
- if event.location is not None:
767
- click.secho(f"Schema location: {event.location}", bold=True)
768
- click.secho(f"Base URL: {event.base_url}", bold=True)
769
- click.secho(f"Specification version: {event.specification_name}", bold=True)
770
- if context.seed is not None:
771
- click.secho(f"Random seed: {context.seed}", bold=True)
772
- click.secho(f"Workers: {context.workers_num}", bold=True)
773
- if context.rate_limit is not None:
774
- click.secho(f"Rate limit: {context.rate_limit}", bold=True)
775
- click.secho(f"Collected API operations: {context.operations_count}", bold=True)
776
- links_count = cast(int, event.links_count)
777
- click.secho(f"Collected API links: {links_count}", bold=True)
778
- if isinstance(context.report, ServiceReportContext):
779
- click.secho("Report to Schemathesis.io: ENABLED", bold=True)
780
- if context.initialization_lines:
781
- _print_lines(context.initialization_lines)
782
-
783
-
784
- def handle_before_probing(context: ExecutionContext, event: events.BeforeProbing) -> None:
785
- click.secho("API probing: ...\r", bold=True, nl=False)
786
-
787
-
788
- def handle_after_probing(context: ExecutionContext, event: events.AfterProbing) -> None:
789
- context.probes = event.probes
790
- status = "SKIP"
791
- if event.probes is not None:
792
- for probe in event.probes:
793
- if probe.outcome in (ProbeOutcome.SUCCESS, ProbeOutcome.FAILURE):
794
- # The probe itself has been executed
795
- status = "SUCCESS"
796
- elif probe.outcome == ProbeOutcome.ERROR:
797
- status = "ERROR"
798
- click.secho(f"API probing: {status}", bold=True, nl=False)
799
- click.echo()
800
-
801
-
802
- def handle_before_analysis(context: ExecutionContext, event: events.BeforeAnalysis) -> None:
803
- click.secho("Schema analysis: ...\r", bold=True, nl=False)
804
-
805
-
806
- def handle_after_analysis(context: ExecutionContext, event: events.AfterAnalysis) -> None:
807
- context.analysis = event.analysis
808
- status = "SKIP"
809
- if event.analysis is not None:
810
- if isinstance(event.analysis, Ok) and isinstance(event.analysis.ok(), AnalysisSuccess):
811
- status = "SUCCESS"
812
- else:
813
- status = "ERROR"
814
- click.secho(f"Schema analysis: {status}", bold=True, nl=False)
815
- click.echo()
816
- operations_count = cast(int, context.operations_count) # INVARIANT: should not be `None`
817
- if operations_count >= 1:
818
- click.echo()
819
-
820
-
821
- TRUNCATION_PLACEHOLDER = "[...]"
822
-
823
-
824
- def handle_before_execution(context: ExecutionContext, event: events.BeforeExecution) -> None:
825
- """Display what method / path will be tested next."""
826
- # We should display execution result + percentage in the end. For example:
827
- max_length = get_terminal_width() - len(" . [XXX%]") - len(TRUNCATION_PLACEHOLDER)
828
- message = event.verbose_name
829
- if event.recursion_level > 0:
830
- message = f"{' ' * event.recursion_level}-> {message}"
831
- # This value is not `None` - the value is set in runtime before this line
832
- context.operations_count += 1 # type: ignore
833
-
834
- message = message[:max_length] + (message[max_length:] and "[...]") + " "
835
- context.current_line_length = len(message)
836
- click.echo(message, nl=False)
837
-
838
-
839
- def handle_after_execution(context: ExecutionContext, event: events.AfterExecution) -> None:
840
- """Display the execution result + current progress at the same line with the method / path names."""
841
- context.operations_processed += 1
842
- context.results.append(event.result)
843
- display_execution_result(context, event.status.value)
844
- display_percentage(context, event)
845
-
846
-
847
- def handle_finished(context: ExecutionContext, event: events.Finished) -> None:
848
- """Show the outcome of the whole testing session."""
849
- click.echo()
850
- display_hypothesis_output(context.hypothesis_output)
851
- display_errors(context, event)
852
- display_failures(context, event)
853
- display_application_logs(context, event)
854
- display_analysis(context)
855
- display_statistic(context, event)
856
- if context.summary_lines:
857
- click.echo()
858
- _print_lines(context.summary_lines)
859
- click.echo()
860
- display_summary(event)
861
-
862
-
863
- def _print_lines(lines: list[str | Generator[str, None, None]]) -> None:
864
- for entry in lines:
865
- if isinstance(entry, str):
866
- click.echo(entry)
867
- elif isinstance(entry, GeneratorType):
868
- for line in entry:
869
- click.echo(line)
870
-
871
-
872
- def handle_interrupted(context: ExecutionContext, event: events.Interrupted) -> None:
873
- click.echo()
874
- _handle_interrupted(context)
875
-
876
-
877
- def _handle_interrupted(context: ExecutionContext) -> None:
878
- context.is_interrupted = True
879
- display_section_name("KeyboardInterrupt", "!", bold=False)
880
-
881
-
882
- def handle_internal_error(context: ExecutionContext, event: events.InternalError) -> None:
883
- display_internal_error(context, event)
884
- raise click.Abort
885
-
886
-
887
- def handle_stateful_event(context: ExecutionContext, event: events.StatefulEvent) -> None:
888
- if isinstance(event.data, stateful_events.RunStarted):
889
- context.state_machine_sink = event.data.state_machine.sink()
890
- if not experimental.STATEFUL_ONLY.is_enabled:
891
- click.echo()
892
- click.secho("Stateful tests\n", bold=True)
893
- elif isinstance(event.data, stateful_events.ScenarioFinished) and not event.data.is_final:
894
- if event.data.status == stateful_events.ScenarioStatus.INTERRUPTED:
895
- _handle_interrupted(context)
896
- elif event.data.status != stateful_events.ScenarioStatus.REJECTED:
897
- display_execution_result(context, event.data.status.value)
898
- elif isinstance(event.data, stateful_events.RunFinished):
899
- click.echo()
900
- # It is initialized in `RunStarted`
901
- sink = cast(StateMachineSink, context.state_machine_sink)
902
- sink.consume(event.data)
903
-
904
-
905
- def handle_after_stateful_execution(context: ExecutionContext, event: events.AfterStatefulExecution) -> None:
906
- context.results.append(event.result)
907
-
908
-
909
- class DefaultOutputStyleHandler(EventHandler):
910
- def handle_event(self, context: ExecutionContext, event: events.ExecutionEvent) -> None:
911
- """Choose and execute a proper handler for the given event."""
912
- if isinstance(event, events.Initialized):
913
- handle_initialized(context, event)
914
- elif isinstance(event, events.BeforeProbing):
915
- handle_before_probing(context, event)
916
- elif isinstance(event, events.AfterProbing):
917
- handle_after_probing(context, event)
918
- elif isinstance(event, events.BeforeAnalysis):
919
- handle_before_analysis(context, event)
920
- elif isinstance(event, events.AfterAnalysis):
921
- handle_after_analysis(context, event)
922
- elif isinstance(event, events.BeforeExecution):
923
- handle_before_execution(context, event)
924
- elif isinstance(event, events.AfterExecution):
925
- context.hypothesis_output.extend(event.hypothesis_output)
926
- handle_after_execution(context, event)
927
- elif isinstance(event, events.Finished):
928
- handle_finished(context, event)
929
- elif isinstance(event, events.Interrupted):
930
- handle_interrupted(context, event)
931
- elif isinstance(event, events.InternalError):
932
- handle_internal_error(context, event)
933
- elif isinstance(event, events.StatefulEvent):
934
- handle_stateful_event(context, event)
935
- elif isinstance(event, events.AfterStatefulExecution):
936
- handle_after_stateful_execution(context, event)