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