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,2083 +1,11 @@
1
1
  from __future__ import annotations
2
2
 
3
- import base64
4
- import os
5
- import sys
6
- import traceback
7
- import warnings
8
- from collections import defaultdict
9
- from dataclasses import dataclass
10
- from enum import Enum
11
- from queue import Queue
12
- from typing import TYPE_CHECKING, Any, Callable, Generator, Iterable, Literal, NoReturn, Sequence, Type, cast
13
- from urllib.parse import urlparse
3
+ from schemathesis.cli.commands import Group, run, schemathesis
4
+ from schemathesis.cli.commands.run.executor import handler
5
+ from schemathesis.cli.commands.run.handlers import EventHandler
6
+ from schemathesis.cli.ext.groups import GROUPS
14
7
 
15
- import click
16
-
17
- from .. import checks as checks_module
18
- from .. import contrib, experimental, generation, runner, service
19
- from .. import fixups as _fixups
20
- from .. import targets as targets_module
21
- from .._override import CaseOverride
22
- from ..code_samples import CodeSampleStyle
23
- from ..constants import (
24
- API_NAME_ENV_VAR,
25
- BASE_URL_ENV_VAR,
26
- DEFAULT_RESPONSE_TIMEOUT,
27
- DEFAULT_STATEFUL_RECURSION_LIMIT,
28
- EXTENSIONS_DOCUMENTATION_URL,
29
- HOOKS_MODULE_ENV_VAR,
30
- HYPOTHESIS_IN_MEMORY_DATABASE_IDENTIFIER,
31
- ISSUE_TRACKER_URL,
32
- WAIT_FOR_SCHEMA_ENV_VAR,
33
- )
34
- from ..exceptions import SchemaError, SchemaErrorType, extract_nth_traceback
35
- from ..filters import FilterSet, expression_to_filter_function, is_deprecated
36
- from ..fixups import ALL_FIXUPS
37
- from ..generation import DEFAULT_DATA_GENERATION_METHODS, DataGenerationMethod
38
- from ..hooks import GLOBAL_HOOK_DISPATCHER, HookContext, HookDispatcher, HookScope
39
- from ..internal.checks import CheckConfig
40
- from ..internal.datetime import current_datetime
41
- from ..internal.output import OutputConfig
42
- from ..internal.validation import file_exists
43
- from ..loaders import load_app, load_yaml
44
- from ..runner import events, prepare_hypothesis_settings, probes
45
- from ..specs.graphql import loaders as gql_loaders
46
- from ..specs.openapi import loaders as oas_loaders
47
- from ..stateful import Stateful
48
- from ..transports import RequestConfig
49
- from ..transports.auth import get_requests_auth
50
- from . import callbacks, cassettes, output
51
- from .constants import DEFAULT_WORKERS, MAX_WORKERS, MIN_WORKERS, HealthCheck, Phase, Verbosity
52
- from .context import ExecutionContext, FileReportContext, ServiceReportContext
53
- from .debug import DebugOutputHandler
54
- from .handlers import EventHandler
55
- from .junitxml import JunitXMLHandler
56
- from .options import CsvChoice, CsvEnumChoice, CsvListChoice, CustomHelpMessageChoice, OptionalInt
57
- from .sanitization import SanitizationHandler
58
-
59
- if TYPE_CHECKING:
60
- import io
61
-
62
- import hypothesis
63
- import requests
64
-
65
- from ..models import Case, CheckFunction
66
- from ..schemas import BaseSchema
67
- from ..service.client import ServiceClient
68
- from ..specs.graphql.schemas import GraphQLSchema
69
- from ..targets import Target
70
- from ..types import NotSet, PathLike, RequestCert
71
-
72
-
73
- __all__ = [
74
- "EventHandler",
75
- ]
76
-
77
-
78
- def _get_callable_names(items: tuple[Callable, ...]) -> tuple[str, ...]:
79
- return tuple(item.__name__ for item in items)
80
-
81
-
82
- CUSTOM_HANDLERS: list[type[EventHandler]] = []
83
- CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
84
-
85
- DEFAULT_CHECKS_NAMES = _get_callable_names(checks_module.DEFAULT_CHECKS)
86
- ALL_CHECKS_NAMES = _get_callable_names(checks_module.ALL_CHECKS)
87
- CHECKS_TYPE = CsvChoice((*ALL_CHECKS_NAMES, "all"))
88
- EXCLUDE_CHECKS_TYPE = CsvChoice((*ALL_CHECKS_NAMES,))
89
-
90
- DEFAULT_TARGETS_NAMES = _get_callable_names(targets_module.DEFAULT_TARGETS)
91
- ALL_TARGETS_NAMES = _get_callable_names(targets_module.ALL_TARGETS)
92
- TARGETS_TYPE = click.Choice((*ALL_TARGETS_NAMES, "all"))
93
-
94
- DATA_GENERATION_METHOD_TYPE = click.Choice([item.name for item in DataGenerationMethod] + ["all"])
95
-
96
- DEPRECATED_CASSETTE_PATH_OPTION_WARNING = (
97
- "Warning: Option `--store-network-log` is deprecated and will be removed in Schemathesis 4.0. "
98
- "Use `--cassette-path` instead."
99
- )
100
- DEPRECATED_PRE_RUN_OPTION_WARNING = (
101
- "Warning: Option `--pre-run` is deprecated and will be removed in Schemathesis 4.0. "
102
- f"Use the `{HOOKS_MODULE_ENV_VAR}` environment variable instead"
103
- )
104
- DEPRECATED_SHOW_ERROR_TRACEBACKS_OPTION_WARNING = (
105
- "Warning: Option `--show-errors-tracebacks` is deprecated and will be removed in Schemathesis 4.0. "
106
- "Use `--show-trace` instead"
107
- )
108
- CASSETTES_PATH_INVALID_USAGE_MESSAGE = "Can't use `--store-network-log` and `--cassette-path` simultaneously"
109
- COLOR_OPTIONS_INVALID_USAGE_MESSAGE = "Can't use `--no-color` and `--force-color` simultaneously"
110
- PHASES_INVALID_USAGE_MESSAGE = "Can't use `--hypothesis-phases` and `--hypothesis-no-phases` simultaneously"
111
-
112
-
113
- def reset_checks() -> None:
114
- """Get checks list to their default state."""
115
- # Useful in tests
116
- checks_module.ALL_CHECKS = checks_module.DEFAULT_CHECKS + checks_module.OPTIONAL_CHECKS
117
- CHECKS_TYPE.choices = (*_get_callable_names(checks_module.ALL_CHECKS), "all")
118
-
119
-
120
- def reset_targets() -> None:
121
- """Get targets list to their default state."""
122
- # Useful in tests
123
- targets_module.ALL_TARGETS = targets_module.DEFAULT_TARGETS + targets_module.OPTIONAL_TARGETS
124
- TARGETS_TYPE.choices = (*_get_callable_names(targets_module.ALL_TARGETS), "all")
125
-
126
-
127
- @click.group(context_settings=CONTEXT_SETTINGS)
128
- @click.option("--pre-run", help="[DEPRECATED] A module to execute before running the tests", type=str, hidden=True)
129
- @click.version_option()
130
- def schemathesis(pre_run: str | None = None) -> None:
131
- """Property-based API testing for OpenAPI and GraphQL."""
132
- # Don't use `envvar=HOOKS_MODULE_ENV_VAR` arg to raise a deprecation warning for hooks
133
- hooks: str | None
134
- if pre_run:
135
- click.secho(DEPRECATED_PRE_RUN_OPTION_WARNING, fg="yellow")
136
- hooks = pre_run
137
- else:
138
- hooks = os.getenv(HOOKS_MODULE_ENV_VAR)
139
- if hooks:
140
- load_hook(hooks)
141
-
142
-
143
- GROUPS: list[str] = []
144
-
145
-
146
- class CommandWithGroupedOptions(click.Command):
147
- def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
148
- groups = defaultdict(list)
149
- for param in self.get_params(ctx):
150
- rv = param.get_help_record(ctx)
151
- if rv is not None:
152
- (option_repr, message) = rv
153
- if isinstance(param.type, click.Choice):
154
- message += (
155
- getattr(param.type, "choices_repr", None)
156
- or f" [possible values: {', '.join(param.type.choices)}]"
157
- )
158
-
159
- if isinstance(param, GroupedOption):
160
- group = param.group
161
- else:
162
- group = "Global options"
163
- groups[group].append((option_repr, message))
164
- for group in GROUPS:
165
- with formatter.section(group or "Options"):
166
- formatter.write_dl(groups[group], col_max=40)
167
-
168
-
169
- class GroupedOption(click.Option):
170
- def __init__(self, *args: Any, group: str | None = None, **kwargs: Any):
171
- super().__init__(*args, **kwargs)
172
- self.group = group
173
-
174
-
175
- def group(name: str) -> Callable:
176
- GROUPS.append(name)
177
-
178
- def _inner(cmd: Callable) -> Callable:
179
- for param in reversed(cmd.__click_params__): # type: ignore[attr-defined]
180
- if not isinstance(param, GroupedOption) or param.group is not None:
181
- break
182
- param.group = name
183
- return cmd
184
-
185
- return _inner
186
-
187
-
188
- def grouped_option(*args: Any, **kwargs: Any) -> Callable:
189
- kwargs.setdefault("cls", GroupedOption)
190
- return click.option(*args, **kwargs)
191
-
192
-
193
- with_request_proxy = grouped_option(
194
- "--request-proxy",
195
- help="Set the proxy for all network requests",
196
- type=str,
197
- )
198
- with_request_tls_verify = grouped_option(
199
- "--request-tls-verify",
200
- help="Configures TLS certificate verification for server requests. Can specify path to CA_BUNDLE for custom certs",
201
- type=str,
202
- default="true",
203
- show_default=True,
204
- callback=callbacks.convert_boolean_string,
205
- )
206
- with_request_cert = grouped_option(
207
- "--request-cert",
208
- help="File path of unencrypted client certificate for authentication. "
209
- "The certificate can be bundled with a private key (e.g. PEM) or the private "
210
- "key can be provided with the --request-cert-key argument",
211
- type=click.Path(exists=True),
212
- default=None,
213
- show_default=False,
214
- )
215
- with_request_cert_key = grouped_option(
216
- "--request-cert-key",
217
- help="Specify the file path of the private key for the client certificate",
218
- type=click.Path(exists=True),
219
- default=None,
220
- show_default=False,
221
- callback=callbacks.validate_request_cert_key,
222
- )
223
- with_hosts_file = grouped_option(
224
- "--hosts-file",
225
- help="Path to a file to store the Schemathesis.io auth configuration",
226
- type=click.Path(dir_okay=False, writable=True),
227
- default=service.DEFAULT_HOSTS_PATH,
228
- envvar=service.HOSTS_PATH_ENV_VAR,
229
- callback=callbacks.convert_hosts_file,
230
- )
231
-
232
-
233
- def _with_filter(*, by: str, mode: Literal["include", "exclude"], modifier: Literal["regex"] | None = None) -> Callable:
234
- """Generate a CLI option for filtering API operations."""
235
- param = f"--{mode}-{by}"
236
- action = "include in" if mode == "include" else "exclude from"
237
- prop = {
238
- "operation-id": "ID",
239
- "name": "Operation name",
240
- }.get(by, by.capitalize())
241
- if modifier:
242
- param += f"-{modifier}"
243
- prop += " pattern"
244
- help_text = f"{prop} to {action} testing."
245
- return grouped_option(
246
- param,
247
- help=help_text,
248
- type=str,
249
- multiple=modifier is None,
250
- )
251
-
252
-
253
- _BY_VALUES = ("operation-id", "tag", "name", "method", "path")
254
-
255
-
256
- def with_filters(command: Callable) -> Callable:
257
- for by in _BY_VALUES:
258
- for mode in ("exclude", "include"):
259
- for modifier in ("regex", None):
260
- command = _with_filter(by=by, mode=mode, modifier=modifier)(command) # type: ignore[arg-type]
261
- return command
262
-
263
-
264
- class ReportToService:
265
- pass
266
-
267
-
268
- REPORT_TO_SERVICE = ReportToService()
269
-
270
-
271
- @schemathesis.command(
272
- short_help="Execute automated tests based on API specifications",
273
- cls=CommandWithGroupedOptions,
274
- context_settings={"terminal_width": output.default.get_terminal_width(), **CONTEXT_SETTINGS},
275
- )
276
- @click.argument("schema", type=str)
277
- @click.argument("api_name", type=str, required=False, envvar=API_NAME_ENV_VAR)
278
- @group("Options")
279
- @grouped_option(
280
- "--workers",
281
- "-w",
282
- "workers_num",
283
- help="Number of concurrent workers for testing. Auto-adjusts if 'auto' is specified",
284
- type=CustomHelpMessageChoice(
285
- ["auto", *list(map(str, range(MIN_WORKERS, MAX_WORKERS + 1)))],
286
- choices_repr=f"[auto, {MIN_WORKERS}-{MAX_WORKERS}]",
287
- ),
288
- default=str(DEFAULT_WORKERS),
289
- show_default=True,
290
- callback=callbacks.convert_workers,
291
- metavar="",
292
- )
293
- @grouped_option(
294
- "--dry-run",
295
- "dry_run",
296
- is_flag=True,
297
- default=False,
298
- help="Simulate test execution without making any actual requests, useful for validating data generation",
299
- )
300
- @grouped_option(
301
- "--fixups",
302
- help="Apply compatibility adjustments",
303
- multiple=True,
304
- type=click.Choice([*ALL_FIXUPS, "all"]),
305
- metavar="",
306
- )
307
- @group("Experimental options")
308
- @grouped_option(
309
- "--experimental",
310
- "experiments",
311
- help="Enable experimental features",
312
- type=click.Choice(
313
- [
314
- experimental.OPEN_API_3_1.name,
315
- experimental.SCHEMA_ANALYSIS.name,
316
- experimental.STATEFUL_TEST_RUNNER.name,
317
- experimental.STATEFUL_ONLY.name,
318
- experimental.COVERAGE_PHASE.name,
319
- experimental.POSITIVE_DATA_ACCEPTANCE.name,
320
- ]
321
- ),
322
- callback=callbacks.convert_experimental,
323
- multiple=True,
324
- metavar="",
325
- )
326
- @grouped_option(
327
- "--experimental-no-failfast",
328
- "no_failfast",
329
- help="Continue testing an API operation after a failure is found",
330
- is_flag=True,
331
- default=False,
332
- metavar="",
333
- envvar="SCHEMATHESIS_EXPERIMENTAL_NO_FAILFAST",
334
- )
335
- @grouped_option(
336
- "--experimental-missing-required-header-allowed-statuses",
337
- "missing_required_header_allowed_statuses",
338
- help="Comma-separated list of status codes expected for test cases with a missing required header",
339
- type=CsvListChoice(),
340
- callback=callbacks.convert_status_codes,
341
- metavar="",
342
- envvar="SCHEMATHESIS_EXPERIMENTAL_MISSING_REQUIRED_HEADER_ALLOWED_STATUSES",
343
- )
344
- @grouped_option(
345
- "--experimental-positive-data-acceptance-allowed-statuses",
346
- "positive_data_acceptance_allowed_statuses",
347
- help="Comma-separated list of status codes considered as successful responses",
348
- type=CsvListChoice(),
349
- callback=callbacks.convert_status_codes,
350
- metavar="",
351
- envvar="SCHEMATHESIS_EXPERIMENTAL_POSITIVE_DATA_ACCEPTANCE_ALLOWED_STATUSES",
352
- )
353
- @grouped_option(
354
- "--experimental-negative-data-rejection-allowed-statuses",
355
- "negative_data_rejection_allowed_statuses",
356
- help="Comma-separated list of status codes expected for rejected negative data",
357
- type=CsvListChoice(),
358
- callback=callbacks.convert_status_codes,
359
- metavar="",
360
- envvar="SCHEMATHESIS_EXPERIMENTAL_NEGATIVE_DATA_REJECTION_ALLOWED_STATUSES",
361
- )
362
- @group("API validation options")
363
- @grouped_option(
364
- "--checks",
365
- "-c",
366
- multiple=True,
367
- help="Comma-separated list of checks to run against API responses",
368
- type=CHECKS_TYPE,
369
- default=DEFAULT_CHECKS_NAMES,
370
- callback=callbacks.convert_checks,
371
- show_default=True,
372
- metavar="",
373
- )
374
- @grouped_option(
375
- "--exclude-checks",
376
- multiple=True,
377
- help="Comma-separated list of checks to skip during testing",
378
- type=EXCLUDE_CHECKS_TYPE,
379
- default=[],
380
- callback=callbacks.convert_checks,
381
- show_default=True,
382
- metavar="",
383
- )
384
- @grouped_option(
385
- "--max-response-time",
386
- help="Time limit in milliseconds for API response times. "
387
- "The test will fail if a response time exceeds this limit. ",
388
- type=click.IntRange(min=1),
389
- )
390
- @grouped_option(
391
- "-x",
392
- "--exitfirst",
393
- "exit_first",
394
- is_flag=True,
395
- default=False,
396
- help="Terminate the test suite immediately upon the first failure or error encountered",
397
- show_default=True,
398
- )
399
- @grouped_option(
400
- "--max-failures",
401
- "max_failures",
402
- type=click.IntRange(min=1),
403
- help="Terminate the test suite after reaching a specified number of failures or errors",
404
- show_default=True,
405
- )
406
- @group("Loader options")
407
- @grouped_option(
408
- "--app",
409
- help="Specify the WSGI/ASGI application under test, provided as an importable Python path",
410
- type=str,
411
- callback=callbacks.validate_app,
412
- )
413
- @grouped_option(
414
- "--wait-for-schema",
415
- help="Maximum duration, in seconds, to wait for the API schema to become available. Disabled by default",
416
- type=click.FloatRange(1.0),
417
- default=None,
418
- envvar=WAIT_FOR_SCHEMA_ENV_VAR,
419
- )
420
- @grouped_option(
421
- "--validate-schema",
422
- help="Validate input API schema. Set to 'true' to enable or 'false' to disable",
423
- type=bool,
424
- default=False,
425
- show_default=True,
426
- )
427
- @group("Network requests options")
428
- @grouped_option(
429
- "--base-url",
430
- "-b",
431
- help="Base URL of the API, required when schema is provided as a file",
432
- type=str,
433
- callback=callbacks.validate_base_url,
434
- envvar=BASE_URL_ENV_VAR,
435
- )
436
- @grouped_option(
437
- "--request-timeout",
438
- help="Timeout limit, in milliseconds, for each network request during tests",
439
- type=click.IntRange(1),
440
- default=DEFAULT_RESPONSE_TIMEOUT,
441
- )
442
- @with_request_proxy
443
- @with_request_tls_verify
444
- @with_request_cert
445
- @with_request_cert_key
446
- @grouped_option(
447
- "--rate-limit",
448
- help="Specify a rate limit for test requests in '<limit>/<duration>' format. "
449
- "Example - `100/m` for 100 requests per minute",
450
- type=str,
451
- callback=callbacks.validate_rate_limit,
452
- )
453
- @grouped_option(
454
- "--header",
455
- "-H",
456
- "headers",
457
- help=r"Add a custom HTTP header to all API requests. Format: 'Header-Name: Value'",
458
- multiple=True,
459
- type=str,
460
- callback=callbacks.validate_headers,
461
- )
462
- @grouped_option(
463
- "--auth",
464
- "-a",
465
- help="Provide the server authentication details in the 'USER:PASSWORD' format",
466
- type=str,
467
- callback=callbacks.validate_auth,
468
- )
469
- @grouped_option(
470
- "--auth-type",
471
- "-A",
472
- type=click.Choice(["basic", "digest"], case_sensitive=False),
473
- default="basic",
474
- help="Specify the authentication method. For custom authentication methods, see our Authentication documentation: https://schemathesis.readthedocs.io/en/stable/auth.html#custom-auth",
475
- show_default=True,
476
- metavar="",
477
- )
478
- @group("Filtering options")
479
- @with_filters
480
- @grouped_option(
481
- "--include-by",
482
- "include_by",
483
- type=str,
484
- help="Include API operations by expression",
485
- )
486
- @grouped_option(
487
- "--exclude-by",
488
- "exclude_by",
489
- type=str,
490
- help="Exclude API operations by expression",
491
- )
492
- @grouped_option(
493
- "--exclude-deprecated",
494
- help="Exclude deprecated API operations from testing",
495
- is_flag=True,
496
- is_eager=True,
497
- default=False,
498
- show_default=True,
499
- )
500
- @grouped_option(
501
- "--endpoint",
502
- "-E",
503
- "endpoints",
504
- type=str,
505
- multiple=True,
506
- help=r"[DEPRECATED] API operation path pattern (e.g., users/\d+)",
507
- callback=callbacks.validate_regex,
508
- hidden=True,
509
- )
510
- @grouped_option(
511
- "--method",
512
- "-M",
513
- "methods",
514
- type=str,
515
- multiple=True,
516
- help="[DEPRECATED] HTTP method (e.g., GET, POST)",
517
- callback=callbacks.validate_regex,
518
- hidden=True,
519
- )
520
- @grouped_option(
521
- "--tag",
522
- "-T",
523
- "tags",
524
- type=str,
525
- multiple=True,
526
- help="[DEPRECATED] Schema tag pattern",
527
- callback=callbacks.validate_regex,
528
- hidden=True,
529
- )
530
- @grouped_option(
531
- "--operation-id",
532
- "-O",
533
- "operation_ids",
534
- type=str,
535
- multiple=True,
536
- help="[DEPRECATED] OpenAPI operationId pattern",
537
- callback=callbacks.validate_regex,
538
- hidden=True,
539
- )
540
- @grouped_option(
541
- "--skip-deprecated-operations",
542
- help="[DEPRECATED] Exclude deprecated API operations from testing",
543
- is_flag=True,
544
- is_eager=True,
545
- default=False,
546
- show_default=True,
547
- hidden=True,
548
- )
549
- @group("Output options")
550
- @grouped_option(
551
- "--junit-xml",
552
- help="Output a JUnit-XML style report at the specified file path",
553
- type=click.File("w", encoding="utf-8"),
554
- )
555
- @grouped_option(
556
- "--cassette-path",
557
- help="Save the test outcomes in a VCR-compatible format",
558
- type=click.File("w", encoding="utf-8"),
559
- is_eager=True,
560
- )
561
- @grouped_option(
562
- "--cassette-format",
563
- help="Format of the saved cassettes",
564
- type=click.Choice([item.name.lower() for item in cassettes.CassetteFormat]),
565
- default=cassettes.CassetteFormat.VCR.name.lower(),
566
- callback=callbacks.convert_cassette_format,
567
- metavar="",
568
- )
569
- @grouped_option(
570
- "--cassette-preserve-exact-body-bytes",
571
- help="Retain exact byte sequence of payloads in cassettes, encoded as base64",
572
- is_flag=True,
573
- callback=callbacks.validate_preserve_exact_body_bytes,
574
- )
575
- @grouped_option(
576
- "--code-sample-style",
577
- help="Code sample style for reproducing failures",
578
- type=click.Choice([item.name for item in CodeSampleStyle]),
579
- default=CodeSampleStyle.default().name,
580
- callback=callbacks.convert_code_sample_style,
581
- metavar="",
582
- )
583
- @grouped_option(
584
- "--sanitize-output",
585
- type=bool,
586
- default=True,
587
- show_default=True,
588
- help="Enable or disable automatic output sanitization to obscure sensitive data",
589
- )
590
- @grouped_option(
591
- "--output-truncate",
592
- help="Truncate schemas and responses in error messages",
593
- type=str,
594
- default="true",
595
- show_default=True,
596
- callback=callbacks.convert_boolean_string,
597
- )
598
- @grouped_option(
599
- "--show-trace",
600
- help="Display complete traceback information for internal errors",
601
- is_flag=True,
602
- is_eager=True,
603
- default=False,
604
- show_default=True,
605
- )
606
- @grouped_option(
607
- "--debug-output-file",
608
- help="Save debugging information in a JSONL format at the specified file path",
609
- type=click.File("w", encoding="utf-8"),
610
- )
611
- @grouped_option(
612
- "--store-network-log",
613
- help="[DEPRECATED] Save the test outcomes in a VCR-compatible format",
614
- type=click.File("w", encoding="utf-8"),
615
- hidden=True,
616
- )
617
- @grouped_option(
618
- "--show-errors-tracebacks",
619
- help="[DEPRECATED] Display complete traceback information for internal errors",
620
- is_flag=True,
621
- is_eager=True,
622
- default=False,
623
- hidden=True,
624
- show_default=True,
625
- )
626
- @group("Data generation options")
627
- @grouped_option(
628
- "--data-generation-method",
629
- "-D",
630
- "data_generation_methods",
631
- help="Specify the approach Schemathesis uses to generate test data. "
632
- "Use 'positive' for valid data, 'negative' for invalid data, or 'all' for both",
633
- type=DATA_GENERATION_METHOD_TYPE,
634
- default=DataGenerationMethod.default().name,
635
- callback=callbacks.convert_data_generation_method,
636
- show_default=True,
637
- metavar="",
638
- )
639
- @grouped_option(
640
- "--stateful",
641
- help="Enable or disable stateful testing",
642
- type=click.Choice([item.name for item in Stateful]),
643
- default=Stateful.links.name,
644
- callback=callbacks.convert_stateful,
645
- metavar="",
646
- )
647
- @grouped_option(
648
- "--stateful-recursion-limit",
649
- help="Recursion depth limit for stateful testing",
650
- default=DEFAULT_STATEFUL_RECURSION_LIMIT,
651
- show_default=True,
652
- type=click.IntRange(1, 100),
653
- hidden=True,
654
- )
655
- @grouped_option(
656
- "--generation-allow-x00",
657
- help="Whether to allow the generation of `\x00` bytes within strings",
658
- type=str,
659
- default="true",
660
- show_default=True,
661
- callback=callbacks.convert_boolean_string,
662
- )
663
- @grouped_option(
664
- "--generation-codec",
665
- help="The codec used for generating strings",
666
- type=str,
667
- default="utf-8",
668
- callback=callbacks.validate_generation_codec,
669
- )
670
- @grouped_option(
671
- "--generation-with-security-parameters",
672
- help="Whether to generate security parameters",
673
- type=str,
674
- default="true",
675
- show_default=True,
676
- callback=callbacks.convert_boolean_string,
677
- )
678
- @grouped_option(
679
- "--generation-graphql-allow-null",
680
- help="Whether to use `null` values for optional arguments in GraphQL queries",
681
- type=str,
682
- default="true",
683
- show_default=True,
684
- callback=callbacks.convert_boolean_string,
685
- )
686
- @grouped_option(
687
- "--contrib-unique-data",
688
- "contrib_unique_data",
689
- help="Force the generation of unique test cases",
690
- is_flag=True,
691
- default=False,
692
- show_default=True,
693
- )
694
- @grouped_option(
695
- "--contrib-openapi-formats-uuid",
696
- "contrib_openapi_formats_uuid",
697
- help="Enable support for the 'uuid' string format in OpenAPI",
698
- is_flag=True,
699
- default=False,
700
- show_default=True,
701
- )
702
- @grouped_option(
703
- "--contrib-openapi-fill-missing-examples",
704
- "contrib_openapi_fill_missing_examples",
705
- help="Enable generation of random examples for API operations that do not have explicit examples",
706
- is_flag=True,
707
- default=False,
708
- show_default=True,
709
- )
710
- @grouped_option(
711
- "--target",
712
- "-t",
713
- "targets",
714
- multiple=True,
715
- help="Guide input generation to values more likely to expose bugs via targeted property-based testing",
716
- type=TARGETS_TYPE,
717
- default=DEFAULT_TARGETS_NAMES,
718
- show_default=True,
719
- metavar="",
720
- )
721
- @group("Open API options")
722
- @grouped_option(
723
- "--force-schema-version",
724
- help="Force the schema to be interpreted as a particular OpenAPI version",
725
- type=click.Choice(["20", "30"]),
726
- metavar="",
727
- )
728
- @grouped_option(
729
- "--set-query",
730
- "set_query",
731
- help=r"OpenAPI: Override a specific query parameter by specifying 'parameter=value'",
732
- multiple=True,
733
- type=str,
734
- callback=callbacks.validate_set_query,
735
- )
736
- @grouped_option(
737
- "--set-header",
738
- "set_header",
739
- help=r"OpenAPI: Override a specific header parameter by specifying 'parameter=value'",
740
- multiple=True,
741
- type=str,
742
- callback=callbacks.validate_set_header,
743
- )
744
- @grouped_option(
745
- "--set-cookie",
746
- "set_cookie",
747
- help=r"OpenAPI: Override a specific cookie parameter by specifying 'parameter=value'",
748
- multiple=True,
749
- type=str,
750
- callback=callbacks.validate_set_cookie,
751
- )
752
- @grouped_option(
753
- "--set-path",
754
- "set_path",
755
- help=r"OpenAPI: Override a specific path parameter by specifying 'parameter=value'",
756
- multiple=True,
757
- type=str,
758
- callback=callbacks.validate_set_path,
759
- )
760
- @group("Hypothesis engine options")
761
- @grouped_option(
762
- "--hypothesis-database",
763
- help="Storage for examples discovered by Hypothesis. "
764
- f"Use 'none' to disable, '{HYPOTHESIS_IN_MEMORY_DATABASE_IDENTIFIER}' for temporary storage, "
765
- f"or specify a file path for persistent storage",
766
- type=str,
767
- callback=callbacks.validate_hypothesis_database,
768
- )
769
- @grouped_option(
770
- "--hypothesis-deadline",
771
- help="Time limit for each test case generated by Hypothesis, in milliseconds. "
772
- "Exceeding this limit will cause the test to fail",
773
- type=OptionalInt(1, 5 * 60 * 1000),
774
- )
775
- @grouped_option(
776
- "--hypothesis-derandomize",
777
- help="Enables deterministic mode in Hypothesis, which eliminates random variation between tests",
778
- is_flag=True,
779
- is_eager=True,
780
- default=None,
781
- show_default=True,
782
- )
783
- @grouped_option(
784
- "--hypothesis-max-examples",
785
- help="The cap on the number of examples generated by Hypothesis for each API operation",
786
- type=click.IntRange(1),
787
- )
788
- @grouped_option(
789
- "--hypothesis-phases",
790
- help="Testing phases to execute",
791
- type=CsvEnumChoice(Phase),
792
- metavar="",
793
- )
794
- @grouped_option(
795
- "--hypothesis-no-phases",
796
- help="Testing phases to exclude from execution",
797
- type=CsvEnumChoice(Phase),
798
- metavar="",
799
- )
800
- @grouped_option(
801
- "--hypothesis-report-multiple-bugs",
802
- help="Report only the most easily reproducible error when multiple issues are found",
803
- type=bool,
804
- )
805
- @grouped_option(
806
- "--hypothesis-seed",
807
- help="Seed value for Hypothesis, ensuring reproducibility across test runs",
808
- type=int,
809
- )
810
- @grouped_option(
811
- "--hypothesis-suppress-health-check",
812
- help="A comma-separated list of Hypothesis health checks to disable",
813
- type=CsvEnumChoice(HealthCheck),
814
- metavar="",
815
- )
816
- @grouped_option(
817
- "--hypothesis-verbosity",
818
- help="Verbosity level of Hypothesis output",
819
- type=click.Choice([item.name for item in Verbosity]),
820
- callback=callbacks.convert_verbosity,
821
- metavar="",
822
- )
823
- @group("Schemathesis.io options")
824
- @grouped_option(
825
- "--report",
826
- "report_value",
827
- help="""Specify how the generated report should be handled.
828
- If used without an argument, the report data will automatically be uploaded to Schemathesis.io.
829
- If a file name is provided, the report will be stored in that file.
830
- The report data, consisting of a tar gz file with multiple JSON files, is subject to change""",
831
- is_flag=False,
832
- flag_value="",
833
- envvar=service.REPORT_ENV_VAR,
834
- callback=callbacks.convert_report, # type: ignore
835
- )
836
- @grouped_option(
837
- "--schemathesis-io-token",
838
- help="Schemathesis.io authentication token",
839
- type=str,
840
- envvar=service.TOKEN_ENV_VAR,
841
- )
842
- @grouped_option(
843
- "--schemathesis-io-url",
844
- help="Schemathesis.io base URL",
845
- default=service.DEFAULT_URL,
846
- type=str,
847
- envvar=service.URL_ENV_VAR,
848
- )
849
- @grouped_option(
850
- "--schemathesis-io-telemetry",
851
- help="Whether to send anonymized usage data to Schemathesis.io along with your report",
852
- type=str,
853
- default="true",
854
- show_default=True,
855
- callback=callbacks.convert_boolean_string,
856
- envvar=service.TELEMETRY_ENV_VAR,
857
- )
858
- @with_hosts_file
859
- @group("Global options")
860
- @grouped_option("--verbosity", "-v", help="Increase verbosity of the output", count=True)
861
- @grouped_option("--no-color", help="Disable ANSI color escape codes", type=bool, is_flag=True)
862
- @grouped_option("--force-color", help="Explicitly tells to enable ANSI color escape codes", type=bool, is_flag=True)
863
- @click.pass_context
864
- def run(
865
- ctx: click.Context,
866
- schema: str,
867
- api_name: str | None,
868
- auth: tuple[str, str] | None,
869
- auth_type: str,
870
- headers: dict[str, str],
871
- set_query: dict[str, str],
872
- set_header: dict[str, str],
873
- set_cookie: dict[str, str],
874
- set_path: dict[str, str],
875
- experiments: list,
876
- no_failfast: bool,
877
- missing_required_header_allowed_statuses: list[str],
878
- positive_data_acceptance_allowed_statuses: list[str],
879
- negative_data_rejection_allowed_statuses: list[str],
880
- checks: Iterable[str] = DEFAULT_CHECKS_NAMES,
881
- exclude_checks: Iterable[str] = (),
882
- data_generation_methods: tuple[DataGenerationMethod, ...] = DEFAULT_DATA_GENERATION_METHODS,
883
- max_response_time: int | None = None,
884
- targets: Iterable[str] = DEFAULT_TARGETS_NAMES,
885
- exit_first: bool = False,
886
- max_failures: int | None = None,
887
- dry_run: bool = False,
888
- include_path: Sequence[str] = (),
889
- include_path_regex: str | None = None,
890
- include_method: Sequence[str] = (),
891
- include_method_regex: str | None = None,
892
- include_name: Sequence[str] = (),
893
- include_name_regex: str | None = None,
894
- include_tag: Sequence[str] = (),
895
- include_tag_regex: str | None = None,
896
- include_operation_id: Sequence[str] = (),
897
- include_operation_id_regex: str | None = None,
898
- exclude_path: Sequence[str] = (),
899
- exclude_path_regex: str | None = None,
900
- exclude_method: Sequence[str] = (),
901
- exclude_method_regex: str | None = None,
902
- exclude_name: Sequence[str] = (),
903
- exclude_name_regex: str | None = None,
904
- exclude_tag: Sequence[str] = (),
905
- exclude_tag_regex: str | None = None,
906
- exclude_operation_id: Sequence[str] = (),
907
- exclude_operation_id_regex: str | None = None,
908
- include_by: str | None = None,
909
- exclude_by: str | None = None,
910
- exclude_deprecated: bool = False,
911
- endpoints: tuple[str, ...] = (),
912
- methods: tuple[str, ...] = (),
913
- tags: tuple[str, ...] = (),
914
- operation_ids: tuple[str, ...] = (),
915
- workers_num: int = DEFAULT_WORKERS,
916
- base_url: str | None = None,
917
- app: str | None = None,
918
- request_timeout: int | None = None,
919
- request_tls_verify: bool = True,
920
- request_cert: str | None = None,
921
- request_cert_key: str | None = None,
922
- request_proxy: str | None = None,
923
- validate_schema: bool = True,
924
- skip_deprecated_operations: bool = False,
925
- junit_xml: click.utils.LazyFile | None = None,
926
- debug_output_file: click.utils.LazyFile | None = None,
927
- show_errors_tracebacks: bool = False,
928
- show_trace: bool = False,
929
- code_sample_style: CodeSampleStyle = CodeSampleStyle.default(),
930
- cassette_path: click.utils.LazyFile | None = None,
931
- cassette_format: cassettes.CassetteFormat = cassettes.CassetteFormat.VCR,
932
- cassette_preserve_exact_body_bytes: bool = False,
933
- store_network_log: click.utils.LazyFile | None = None,
934
- wait_for_schema: float | None = None,
935
- fixups: tuple[str] = (), # type: ignore
936
- rate_limit: str | None = None,
937
- stateful: Stateful | None = None,
938
- stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT,
939
- force_schema_version: str | None = None,
940
- sanitize_output: bool = True,
941
- output_truncate: bool = True,
942
- contrib_unique_data: bool = False,
943
- contrib_openapi_formats_uuid: bool = False,
944
- contrib_openapi_fill_missing_examples: bool = False,
945
- hypothesis_database: str | None = None,
946
- hypothesis_deadline: int | NotSet | None = None,
947
- hypothesis_derandomize: bool | None = None,
948
- hypothesis_max_examples: int | None = None,
949
- hypothesis_phases: list[Phase] | None = None,
950
- hypothesis_no_phases: list[Phase] | None = None,
951
- hypothesis_report_multiple_bugs: bool | None = None,
952
- hypothesis_suppress_health_check: list[HealthCheck] | None = None,
953
- hypothesis_seed: int | None = None,
954
- hypothesis_verbosity: hypothesis.Verbosity | None = None,
955
- verbosity: int = 0,
956
- no_color: bool = False,
957
- report_value: str | None = None,
958
- generation_allow_x00: bool = True,
959
- generation_graphql_allow_null: bool = True,
960
- generation_with_security_parameters: bool = True,
961
- generation_codec: str = "utf-8",
962
- schemathesis_io_token: str | None = None,
963
- schemathesis_io_url: str = service.DEFAULT_URL,
964
- schemathesis_io_telemetry: bool = True,
965
- hosts_file: PathLike = service.DEFAULT_HOSTS_PATH,
966
- force_color: bool = False,
967
- **__kwargs,
968
- ) -> None:
969
- """Run tests against an API using a specified SCHEMA.
970
-
971
- [Required] SCHEMA: Path to an OpenAPI (`.json`, `.yml`) or GraphQL SDL file, or a URL pointing to such specifications
972
-
973
- [Optional] API_NAME: Identifier for uploading test data to Schemathesis.io
974
- """
975
- _hypothesis_phases: list[hypothesis.Phase] | None = None
976
- if hypothesis_phases is not None:
977
- _hypothesis_phases = [phase.as_hypothesis() for phase in hypothesis_phases]
978
- if hypothesis_no_phases is not None:
979
- raise click.UsageError(PHASES_INVALID_USAGE_MESSAGE)
980
- if hypothesis_no_phases is not None:
981
- _hypothesis_phases = Phase.filter_from_all(hypothesis_no_phases)
982
- _hypothesis_suppress_health_check: list[hypothesis.HealthCheck] | None = None
983
- if hypothesis_suppress_health_check is not None:
984
- _hypothesis_suppress_health_check = [
985
- entry for health_check in hypothesis_suppress_health_check for entry in health_check.as_hypothesis()
986
- ]
987
-
988
- if show_errors_tracebacks:
989
- click.secho(DEPRECATED_SHOW_ERROR_TRACEBACKS_OPTION_WARNING, fg="yellow")
990
- show_trace = show_errors_tracebacks
991
-
992
- # Enable selected experiments
993
- for experiment in experiments:
994
- experiment.enable()
995
-
996
- override = CaseOverride(query=set_query, headers=set_header, cookies=set_cookie, path_parameters=set_path)
997
-
998
- generation_config = generation.GenerationConfig(
999
- allow_x00=generation_allow_x00,
1000
- graphql_allow_null=generation_graphql_allow_null,
1001
- codec=generation_codec,
1002
- with_security_parameters=generation_with_security_parameters,
1003
- )
1004
-
1005
- report: ReportToService | click.utils.LazyFile | None
1006
- if report_value is None:
1007
- report = None
1008
- elif report_value:
1009
- report = click.utils.LazyFile(report_value, mode="wb")
1010
- else:
1011
- report = REPORT_TO_SERVICE
1012
- started_at = current_datetime()
1013
-
1014
- if no_color and force_color:
1015
- raise click.UsageError(COLOR_OPTIONS_INVALID_USAGE_MESSAGE)
1016
- decide_color_output(ctx, no_color, force_color)
1017
-
1018
- check_auth(auth, headers, override)
1019
- selected_targets = tuple(target for target in targets_module.ALL_TARGETS if target.__name__ in targets)
1020
-
1021
- if store_network_log and cassette_path:
1022
- raise click.UsageError(CASSETTES_PATH_INVALID_USAGE_MESSAGE)
1023
- if store_network_log is not None:
1024
- click.secho(DEPRECATED_CASSETTE_PATH_OPTION_WARNING, fg="yellow")
1025
- cassette_path = store_network_log
1026
-
1027
- output_config = OutputConfig(truncate=output_truncate)
1028
-
1029
- deprecated_filters = {
1030
- "--method": "--include-method",
1031
- "--endpoint": "--include-path",
1032
- "--tag": "--include-tag",
1033
- "--operation-id": "--include-operation-id",
1034
- }
1035
- for values, arg_name in (
1036
- (include_path, "--include-path"),
1037
- (include_method, "--include-method"),
1038
- (include_name, "--include-name"),
1039
- (include_tag, "--include-tag"),
1040
- (include_operation_id, "--include-operation-id"),
1041
- (exclude_path, "--exclude-path"),
1042
- (exclude_method, "--exclude-method"),
1043
- (exclude_name, "--exclude-name"),
1044
- (exclude_tag, "--exclude-tag"),
1045
- (exclude_operation_id, "--exclude-operation-id"),
1046
- (methods, "--method"),
1047
- (endpoints, "--endpoint"),
1048
- (tags, "--tag"),
1049
- (operation_ids, "--operation-id"),
1050
- ):
1051
- if values and arg_name in deprecated_filters:
1052
- replacement = deprecated_filters[arg_name]
1053
- click.secho(
1054
- f"Warning: Option `{arg_name}` is deprecated and will be removed in Schemathesis 4.0. "
1055
- f"Use `{replacement}` instead",
1056
- fg="yellow",
1057
- )
1058
- _ensure_unique_filter(values, arg_name)
1059
- include_by_function = _filter_by_expression_to_func(include_by, "--include-by")
1060
- exclude_by_function = _filter_by_expression_to_func(exclude_by, "--exclude-by")
1061
-
1062
- filter_set = FilterSet()
1063
- if include_by_function:
1064
- filter_set.include(include_by_function)
1065
- for name_ in include_name:
1066
- filter_set.include(name=name_)
1067
- for method in include_method:
1068
- filter_set.include(method=method)
1069
- if methods:
1070
- for method in methods:
1071
- filter_set.include(method_regex=method)
1072
- for path in include_path:
1073
- filter_set.include(path=path)
1074
- if endpoints:
1075
- for endpoint in endpoints:
1076
- filter_set.include(path_regex=endpoint)
1077
- for tag in include_tag:
1078
- filter_set.include(tag=tag)
1079
- if tags:
1080
- for tag in tags:
1081
- filter_set.include(tag_regex=tag)
1082
- for operation_id in include_operation_id:
1083
- filter_set.include(operation_id=operation_id)
1084
- if operation_ids:
1085
- for operation_id in operation_ids:
1086
- filter_set.include(operation_id_regex=operation_id)
1087
- if (
1088
- include_name_regex
1089
- or include_method_regex
1090
- or include_path_regex
1091
- or include_tag_regex
1092
- or include_operation_id_regex
1093
- ):
1094
- filter_set.include(
1095
- name_regex=include_name_regex,
1096
- method_regex=include_method_regex,
1097
- path_regex=include_path_regex,
1098
- tag_regex=include_tag_regex,
1099
- operation_id_regex=include_operation_id_regex,
1100
- )
1101
- if exclude_by_function:
1102
- filter_set.exclude(exclude_by_function)
1103
- for name_ in exclude_name:
1104
- filter_set.exclude(name=name_)
1105
- for method in exclude_method:
1106
- filter_set.exclude(method=method)
1107
- for path in exclude_path:
1108
- filter_set.exclude(path=path)
1109
- for tag in exclude_tag:
1110
- filter_set.exclude(tag=tag)
1111
- for operation_id in exclude_operation_id:
1112
- filter_set.exclude(operation_id=operation_id)
1113
- if (
1114
- exclude_name_regex
1115
- or exclude_method_regex
1116
- or exclude_path_regex
1117
- or exclude_tag_regex
1118
- or exclude_operation_id_regex
1119
- ):
1120
- filter_set.exclude(
1121
- name_regex=exclude_name_regex,
1122
- method_regex=exclude_method_regex,
1123
- path_regex=exclude_path_regex,
1124
- tag_regex=exclude_tag_regex,
1125
- operation_id_regex=exclude_operation_id_regex,
1126
- )
1127
- if exclude_deprecated or skip_deprecated_operations:
1128
- filter_set.exclude(is_deprecated)
1129
-
1130
- schemathesis_io_hostname = urlparse(schemathesis_io_url).netloc
1131
- token = schemathesis_io_token or service.hosts.get_token(hostname=schemathesis_io_hostname, hosts_file=hosts_file)
1132
- schema_kind = callbacks.parse_schema_kind(schema, app)
1133
- callbacks.validate_schema(schema, schema_kind, base_url=base_url, dry_run=dry_run, app=app, api_name=api_name)
1134
- client = None
1135
- schema_or_location: str | dict[str, Any] = schema
1136
- if schema_kind == callbacks.SchemaInputKind.NAME:
1137
- api_name = schema
1138
- if (
1139
- not isinstance(report, click.utils.LazyFile)
1140
- and api_name is not None
1141
- and schema_kind == callbacks.SchemaInputKind.NAME
1142
- ):
1143
- from ..service.client import ServiceClient
1144
-
1145
- client = ServiceClient(base_url=schemathesis_io_url, token=token)
1146
- # It is assigned above
1147
- if token is not None or schema_kind == callbacks.SchemaInputKind.NAME:
1148
- if token is None:
1149
- hostname = (
1150
- "Schemathesis.io"
1151
- if schemathesis_io_hostname == service.DEFAULT_HOSTNAME
1152
- else schemathesis_io_hostname
1153
- )
1154
- click.secho(f"Missing authentication for {hostname} upload", bold=True, fg="red")
1155
- click.echo(
1156
- f"\nYou've specified an API name, suggesting you want to upload data to {bold(hostname)}. "
1157
- "However, your CLI is not currently authenticated."
1158
- )
1159
- output.default.display_service_unauthorized(hostname)
1160
- raise click.exceptions.Exit(1) from None
1161
- name: str = cast(str, api_name)
1162
- import requests
1163
-
1164
- try:
1165
- details = client.get_api_details(name)
1166
- # Replace config values with ones loaded from the service
1167
- schema_or_location = details.specification.schema
1168
- default_environment = details.default_environment
1169
- base_url = base_url or (default_environment.url if default_environment else None)
1170
- except requests.HTTPError as exc:
1171
- handle_service_error(exc, name)
1172
- if report is REPORT_TO_SERVICE and not client:
1173
- from ..service.client import ServiceClient
1174
-
1175
- # Upload without connecting data to a certain API
1176
- client = ServiceClient(base_url=schemathesis_io_url, token=token)
1177
- if experimental.SCHEMA_ANALYSIS.is_enabled and not client:
1178
- from ..service.client import ServiceClient
1179
-
1180
- client = ServiceClient(base_url=schemathesis_io_url, token=token)
1181
- host_data = service.hosts.HostData(schemathesis_io_hostname, hosts_file)
1182
-
1183
- if "all" in checks:
1184
- selected_checks = checks_module.ALL_CHECKS
1185
- else:
1186
- selected_checks = tuple(check for check in checks_module.ALL_CHECKS if check.__name__ in checks)
1187
-
1188
- checks_config = CheckConfig()
1189
- if experimental.POSITIVE_DATA_ACCEPTANCE.is_enabled:
1190
- from ..specs.openapi.checks import positive_data_acceptance
1191
-
1192
- selected_checks += (positive_data_acceptance,)
1193
- if positive_data_acceptance_allowed_statuses:
1194
- checks_config.positive_data_acceptance.allowed_statuses = positive_data_acceptance_allowed_statuses
1195
- if missing_required_header_allowed_statuses:
1196
- from ..specs.openapi.checks import missing_required_header
1197
-
1198
- selected_checks += (missing_required_header,)
1199
- checks_config.missing_required_header.allowed_statuses = missing_required_header_allowed_statuses
1200
- if negative_data_rejection_allowed_statuses:
1201
- checks_config.negative_data_rejection.allowed_statuses = negative_data_rejection_allowed_statuses
1202
- if experimental.COVERAGE_PHASE.is_enabled:
1203
- from ..specs.openapi.checks import unsupported_method
1204
-
1205
- selected_checks += (unsupported_method,)
1206
-
1207
- selected_checks = tuple(check for check in selected_checks if check.__name__ not in exclude_checks)
1208
-
1209
- if fixups:
1210
- if "all" in fixups:
1211
- _fixups.install()
1212
- else:
1213
- _fixups.install(fixups)
1214
-
1215
- if contrib_openapi_formats_uuid:
1216
- contrib.openapi.formats.uuid.install()
1217
- if contrib_openapi_fill_missing_examples:
1218
- contrib.openapi.fill_missing_examples.install()
1219
-
1220
- hypothesis_settings = prepare_hypothesis_settings(
1221
- database=hypothesis_database,
1222
- deadline=hypothesis_deadline,
1223
- derandomize=hypothesis_derandomize,
1224
- max_examples=hypothesis_max_examples,
1225
- phases=_hypothesis_phases,
1226
- report_multiple_bugs=hypothesis_report_multiple_bugs,
1227
- suppress_health_check=_hypothesis_suppress_health_check,
1228
- verbosity=hypothesis_verbosity,
1229
- )
1230
- event_stream = into_event_stream(
1231
- schema_or_location,
1232
- app=app,
1233
- base_url=base_url,
1234
- started_at=started_at,
1235
- validate_schema=validate_schema,
1236
- data_generation_methods=data_generation_methods,
1237
- force_schema_version=force_schema_version,
1238
- request_tls_verify=request_tls_verify,
1239
- request_proxy=request_proxy,
1240
- request_cert=prepare_request_cert(request_cert, request_cert_key),
1241
- wait_for_schema=wait_for_schema,
1242
- auth=auth,
1243
- auth_type=auth_type,
1244
- override=override,
1245
- headers=headers,
1246
- request_timeout=request_timeout,
1247
- seed=hypothesis_seed,
1248
- exit_first=exit_first,
1249
- no_failfast=no_failfast,
1250
- max_failures=max_failures,
1251
- unique_data=contrib_unique_data,
1252
- dry_run=dry_run,
1253
- store_interactions=cassette_path is not None,
1254
- checks=selected_checks,
1255
- max_response_time=max_response_time,
1256
- targets=selected_targets,
1257
- workers_num=workers_num,
1258
- rate_limit=rate_limit,
1259
- stateful=stateful,
1260
- stateful_recursion_limit=stateful_recursion_limit,
1261
- hypothesis_settings=hypothesis_settings,
1262
- generation_config=generation_config,
1263
- checks_config=checks_config,
1264
- output_config=output_config,
1265
- service_client=client,
1266
- filter_set=filter_set,
1267
- )
1268
- execute(
1269
- event_stream,
1270
- ctx=ctx,
1271
- hypothesis_settings=hypothesis_settings,
1272
- workers_num=workers_num,
1273
- rate_limit=rate_limit,
1274
- show_trace=show_trace,
1275
- wait_for_schema=wait_for_schema,
1276
- validate_schema=validate_schema,
1277
- cassette_path=cassette_path,
1278
- cassette_format=cassette_format,
1279
- cassette_preserve_exact_body_bytes=cassette_preserve_exact_body_bytes,
1280
- junit_xml=junit_xml,
1281
- verbosity=verbosity,
1282
- code_sample_style=code_sample_style,
1283
- data_generation_methods=data_generation_methods,
1284
- debug_output_file=debug_output_file,
1285
- sanitize_output=sanitize_output,
1286
- host_data=host_data,
1287
- client=client,
1288
- report=report,
1289
- telemetry=schemathesis_io_telemetry,
1290
- api_name=api_name,
1291
- location=schema,
1292
- base_url=base_url,
1293
- started_at=started_at,
1294
- output_config=output_config,
1295
- )
1296
-
1297
-
1298
- def _ensure_unique_filter(values: Sequence[str], arg_name: str) -> None:
1299
- if len(values) != len(set(values)):
1300
- duplicates = ",".join(sorted({value for value in values if values.count(value) > 1}))
1301
- raise click.UsageError(f"Duplicate values are not allowed for `{arg_name}`: {duplicates}")
1302
-
1303
-
1304
- def _filter_by_expression_to_func(value: str | None, arg_name: str) -> Callable | None:
1305
- if value:
1306
- try:
1307
- return expression_to_filter_function(value)
1308
- except ValueError:
1309
- raise click.UsageError(f"Invalid expression for {arg_name}: {value}") from None
1310
- return None
1311
-
1312
-
1313
- def prepare_request_cert(cert: str | None, key: str | None) -> RequestCert | None:
1314
- if cert is not None and key is not None:
1315
- return cert, key
1316
- return cert
1317
-
1318
-
1319
- @dataclass
1320
- class LoaderConfig:
1321
- """Container for API loader parameters.
1322
-
1323
- The main goal is to avoid too many parameters in function signatures.
1324
- """
1325
-
1326
- schema_or_location: str | dict[str, Any]
1327
- app: Any
1328
- base_url: str | None
1329
- validate_schema: bool
1330
- data_generation_methods: tuple[DataGenerationMethod, ...]
1331
- force_schema_version: str | None
1332
- request_tls_verify: bool | str
1333
- request_proxy: str | None
1334
- request_cert: RequestCert | None
1335
- wait_for_schema: float | None
1336
- rate_limit: str | None
1337
- output_config: OutputConfig
1338
- generation_config: generation.GenerationConfig
1339
- # Network request parameters
1340
- auth: tuple[str, str] | None
1341
- auth_type: str | None
1342
- headers: dict[str, str] | None
1343
-
1344
-
1345
- def into_event_stream(
1346
- schema_or_location: str | dict[str, Any],
1347
- *,
1348
- app: Any,
1349
- base_url: str | None,
1350
- started_at: str,
1351
- validate_schema: bool,
1352
- data_generation_methods: tuple[DataGenerationMethod, ...],
1353
- force_schema_version: str | None,
1354
- request_tls_verify: bool | str,
1355
- request_proxy: str | None,
1356
- request_cert: RequestCert | None,
1357
- # Network request parameters
1358
- auth: tuple[str, str] | None,
1359
- auth_type: str | None,
1360
- override: CaseOverride,
1361
- headers: dict[str, str] | None,
1362
- request_timeout: int | None,
1363
- wait_for_schema: float | None,
1364
- filter_set: FilterSet,
1365
- # Runtime behavior
1366
- checks: Iterable[CheckFunction],
1367
- checks_config: CheckConfig,
1368
- max_response_time: int | None,
1369
- targets: Iterable[Target],
1370
- workers_num: int,
1371
- hypothesis_settings: hypothesis.settings | None,
1372
- generation_config: generation.GenerationConfig,
1373
- output_config: OutputConfig,
1374
- seed: int | None,
1375
- exit_first: bool,
1376
- no_failfast: bool,
1377
- max_failures: int | None,
1378
- rate_limit: str | None,
1379
- unique_data: bool,
1380
- dry_run: bool,
1381
- store_interactions: bool,
1382
- stateful: Stateful | None,
1383
- stateful_recursion_limit: int,
1384
- service_client: ServiceClient | None,
1385
- ) -> Generator[events.ExecutionEvent, None, None]:
1386
- try:
1387
- if app is not None:
1388
- app = load_app(app)
1389
- config = LoaderConfig(
1390
- schema_or_location=schema_or_location,
1391
- app=app,
1392
- base_url=base_url,
1393
- validate_schema=validate_schema,
1394
- data_generation_methods=data_generation_methods,
1395
- force_schema_version=force_schema_version,
1396
- request_proxy=request_proxy,
1397
- request_tls_verify=request_tls_verify,
1398
- request_cert=request_cert,
1399
- wait_for_schema=wait_for_schema,
1400
- rate_limit=rate_limit,
1401
- auth=auth,
1402
- auth_type=auth_type,
1403
- headers=headers,
1404
- output_config=output_config,
1405
- generation_config=generation_config,
1406
- )
1407
- schema = load_schema(config)
1408
- schema.filter_set = filter_set
1409
- yield from runner.from_schema(
1410
- schema,
1411
- auth=auth,
1412
- auth_type=auth_type,
1413
- override=override,
1414
- headers=headers,
1415
- request_timeout=request_timeout,
1416
- request_tls_verify=request_tls_verify,
1417
- request_proxy=request_proxy,
1418
- request_cert=request_cert,
1419
- seed=seed,
1420
- exit_first=exit_first,
1421
- no_failfast=no_failfast,
1422
- max_failures=max_failures,
1423
- started_at=started_at,
1424
- unique_data=unique_data,
1425
- dry_run=dry_run,
1426
- store_interactions=store_interactions,
1427
- checks=checks,
1428
- checks_config=checks_config,
1429
- max_response_time=max_response_time,
1430
- targets=targets,
1431
- workers_num=workers_num,
1432
- stateful=stateful,
1433
- stateful_recursion_limit=stateful_recursion_limit,
1434
- hypothesis_settings=hypothesis_settings,
1435
- generation_config=generation_config,
1436
- probe_config=probes.ProbeConfig(
1437
- base_url=config.base_url,
1438
- request=RequestConfig(
1439
- timeout=request_timeout,
1440
- tls_verify=config.request_tls_verify,
1441
- proxy=config.request_proxy,
1442
- cert=config.request_cert,
1443
- ),
1444
- auth=config.auth,
1445
- auth_type=config.auth_type,
1446
- headers=config.headers,
1447
- ),
1448
- service_client=service_client,
1449
- ).execute()
1450
- except SchemaError as error:
1451
- yield events.InternalError.from_schema_error(error)
1452
- except Exception as exc:
1453
- yield events.InternalError.from_exc(exc)
1454
-
1455
-
1456
- def load_schema(config: LoaderConfig) -> BaseSchema:
1457
- """Automatically load API schema."""
1458
- first: Callable[[LoaderConfig], BaseSchema]
1459
- second: Callable[[LoaderConfig], BaseSchema]
1460
- if is_probably_graphql(config.schema_or_location):
1461
- # Try GraphQL first, then fallback to Open API
1462
- first, second = (_load_graphql_schema, _load_openapi_schema)
1463
- else:
1464
- # Try Open API first, then fallback to GraphQL
1465
- first, second = (_load_openapi_schema, _load_graphql_schema)
1466
- return _try_load_schema(config, first, second)
1467
-
1468
-
1469
- def should_try_more(exc: SchemaError) -> bool:
1470
- import requests
1471
- from yaml.reader import ReaderError
1472
-
1473
- if isinstance(exc.__cause__, ReaderError) and "characters are not allowed" in str(exc.__cause__):
1474
- return False
1475
-
1476
- # We should not try other loaders for cases when we can't even establish connection
1477
- return not isinstance(exc.__cause__, requests.exceptions.ConnectionError) and exc.type not in (
1478
- SchemaErrorType.OPEN_API_INVALID_SCHEMA,
1479
- SchemaErrorType.OPEN_API_UNSPECIFIED_VERSION,
1480
- SchemaErrorType.OPEN_API_UNSUPPORTED_VERSION,
1481
- SchemaErrorType.OPEN_API_EXPERIMENTAL_VERSION,
1482
- )
1483
-
1484
-
1485
- Loader = Callable[[LoaderConfig], "BaseSchema"]
1486
-
1487
-
1488
- def _try_load_schema(config: LoaderConfig, first: Loader, second: Loader) -> BaseSchema:
1489
- from urllib3.exceptions import InsecureRequestWarning
1490
-
1491
- with warnings.catch_warnings():
1492
- warnings.simplefilter("ignore", InsecureRequestWarning)
1493
- try:
1494
- return first(config)
1495
- except SchemaError as exc:
1496
- if config.force_schema_version is None and should_try_more(exc):
1497
- try:
1498
- return second(config)
1499
- except Exception as second_exc:
1500
- if is_specific_exception(second, second_exc):
1501
- raise second_exc
1502
- # Re-raise the original error
1503
- raise exc
1504
-
1505
-
1506
- def is_specific_exception(loader: Loader, exc: Exception) -> bool:
1507
- return (
1508
- loader is _load_graphql_schema
1509
- and isinstance(exc, SchemaError)
1510
- and exc.type == SchemaErrorType.GRAPHQL_INVALID_SCHEMA
1511
- # In some cases it is not clear that the schema is even supposed to be GraphQL, e.g. an empty input
1512
- and "Syntax Error: Unexpected <EOF>." not in exc.extras
1513
- )
1514
-
1515
-
1516
- def _load_graphql_schema(config: LoaderConfig) -> GraphQLSchema:
1517
- loader = detect_loader(config.schema_or_location, config.app, is_openapi=False)
1518
- kwargs = get_graphql_loader_kwargs(loader, config)
1519
- return loader(config.schema_or_location, **kwargs)
1520
-
1521
-
1522
- def _load_openapi_schema(config: LoaderConfig) -> BaseSchema:
1523
- loader = detect_loader(config.schema_or_location, config.app, is_openapi=True)
1524
- kwargs = get_loader_kwargs(loader, config)
1525
- return loader(config.schema_or_location, **kwargs)
1526
-
1527
-
1528
- def detect_loader(schema_or_location: str | dict[str, Any], app: Any, is_openapi: bool) -> Callable:
1529
- """Detect API schema loader."""
1530
- if isinstance(schema_or_location, str):
1531
- if file_exists(schema_or_location):
1532
- # If there is an existing file with the given name,
1533
- # then it is likely that the user wants to load API schema from there
1534
- return oas_loaders.from_path if is_openapi else gql_loaders.from_path # type: ignore
1535
- if app is not None and not urlparse(schema_or_location).netloc:
1536
- # App is passed & location is relative
1537
- return oas_loaders.get_loader_for_app(app) if is_openapi else gql_loaders.get_loader_for_app(app)
1538
- # Default behavior
1539
- return oas_loaders.from_uri if is_openapi else gql_loaders.from_url # type: ignore
1540
- return oas_loaders.from_dict if is_openapi else gql_loaders.from_dict # type: ignore
1541
-
1542
-
1543
- def get_loader_kwargs(loader: Callable, config: LoaderConfig) -> dict[str, Any]:
1544
- """Detect the proper set of parameters for a loader."""
1545
- # These kwargs are shared by all loaders
1546
- kwargs = {
1547
- "app": config.app,
1548
- "base_url": config.base_url,
1549
- "validate_schema": config.validate_schema,
1550
- "force_schema_version": config.force_schema_version,
1551
- "data_generation_methods": config.data_generation_methods,
1552
- "rate_limit": config.rate_limit,
1553
- "output_config": config.output_config,
1554
- "generation_config": config.generation_config,
1555
- }
1556
- if loader not in (oas_loaders.from_path, oas_loaders.from_dict):
1557
- kwargs["headers"] = config.headers
1558
- if loader in (oas_loaders.from_uri, oas_loaders.from_aiohttp):
1559
- _add_requests_kwargs(kwargs, config)
1560
- return kwargs
1561
-
1562
-
1563
- def get_graphql_loader_kwargs(
1564
- loader: Callable,
1565
- config: LoaderConfig,
1566
- ) -> dict[str, Any]:
1567
- """Detect the proper set of parameters for a loader."""
1568
- # These kwargs are shared by all loaders
1569
- kwargs = {
1570
- "app": config.app,
1571
- "base_url": config.base_url,
1572
- "data_generation_methods": config.data_generation_methods,
1573
- "rate_limit": config.rate_limit,
1574
- }
1575
- if loader not in (gql_loaders.from_path, gql_loaders.from_dict):
1576
- kwargs["headers"] = config.headers
1577
- if loader is gql_loaders.from_url:
1578
- _add_requests_kwargs(kwargs, config)
1579
- return kwargs
1580
-
1581
-
1582
- def _add_requests_kwargs(kwargs: dict[str, Any], config: LoaderConfig) -> None:
1583
- kwargs["verify"] = config.request_tls_verify
1584
- if config.request_cert is not None:
1585
- kwargs["cert"] = config.request_cert
1586
- if config.auth is not None:
1587
- kwargs["auth"] = get_requests_auth(config.auth, config.auth_type)
1588
- if config.wait_for_schema is not None:
1589
- kwargs["wait_for_schema"] = config.wait_for_schema
1590
-
1591
-
1592
- def is_probably_graphql(schema_or_location: str | dict[str, Any]) -> bool:
1593
- """Detect whether it is likely that the given location is a GraphQL endpoint."""
1594
- if isinstance(schema_or_location, str):
1595
- return schema_or_location.endswith(("/graphql", "/graphql/", ".graphql", ".gql"))
1596
- return "__schema" in schema_or_location or (
1597
- "data" in schema_or_location and "__schema" in schema_or_location["data"]
1598
- )
1599
-
1600
-
1601
- def check_auth(auth: tuple[str, str] | None, headers: dict[str, str], override: CaseOverride) -> None:
1602
- auth_is_set = auth is not None
1603
- header_is_set = "authorization" in {header.lower() for header in headers}
1604
- override_is_set = "authorization" in {header.lower() for header in override.headers}
1605
- if len([is_set for is_set in (auth_is_set, header_is_set, override_is_set) if is_set]) > 1:
1606
- message = "The "
1607
- used = []
1608
- if auth_is_set:
1609
- used.append("`--auth`")
1610
- if header_is_set:
1611
- used.append("`--header`")
1612
- if override_is_set:
1613
- used.append("`--set-header`")
1614
- message += " and ".join(used)
1615
- message += " options were both used to set the 'Authorization' header, which is not permitted."
1616
- raise click.BadParameter(message)
1617
-
1618
-
1619
- def get_output_handler(workers_num: int) -> EventHandler:
1620
- if workers_num > 1:
1621
- output_style = OutputStyle.short
1622
- else:
1623
- output_style = OutputStyle.default
1624
- return output_style.value()
1625
-
1626
-
1627
- def load_hook(module_name: str) -> None:
1628
- """Load the given hook by importing it."""
1629
- try:
1630
- sys.path.append(os.getcwd()) # fix ModuleNotFoundError module in cwd
1631
- __import__(module_name)
1632
- except Exception as exc:
1633
- click.secho("Unable to load Schemathesis extension hooks", fg="red", bold=True)
1634
- formatted_module_name = bold(f"'{module_name}'")
1635
- if isinstance(exc, ModuleNotFoundError) and exc.name == module_name:
1636
- click.echo(
1637
- f"\nAn attempt to import the module {formatted_module_name} failed because it could not be found."
1638
- )
1639
- click.echo("\nEnsure the module name is correctly spelled and reachable from the current directory.")
1640
- else:
1641
- click.echo(f"\nAn error occurred while importing the module {formatted_module_name}. Traceback:")
1642
- trace = extract_nth_traceback(exc.__traceback__, 1)
1643
- lines = traceback.format_exception(type(exc), exc, trace)
1644
- message = "".join(lines).strip()
1645
- click.secho(f"\n{message}", fg="red")
1646
- click.echo(f"\nFor more information on how to work with hooks, visit {EXTENSIONS_DOCUMENTATION_URL}")
1647
- raise click.exceptions.Exit(1) from None
1648
-
1649
-
1650
- class OutputStyle(Enum):
1651
- """Provide different output styles."""
1652
-
1653
- default = output.default.DefaultOutputStyleHandler
1654
- short = output.short.ShortOutputStyleHandler
1655
-
1656
-
1657
- def execute(
1658
- event_stream: Generator[events.ExecutionEvent, None, None],
1659
- *,
1660
- ctx: click.Context,
1661
- hypothesis_settings: hypothesis.settings,
1662
- workers_num: int,
1663
- rate_limit: str | None,
1664
- show_trace: bool,
1665
- wait_for_schema: float | None,
1666
- validate_schema: bool,
1667
- cassette_path: click.utils.LazyFile | None,
1668
- cassette_format: cassettes.CassetteFormat,
1669
- cassette_preserve_exact_body_bytes: bool,
1670
- junit_xml: click.utils.LazyFile | None,
1671
- verbosity: int,
1672
- code_sample_style: CodeSampleStyle,
1673
- data_generation_methods: tuple[DataGenerationMethod, ...],
1674
- debug_output_file: click.utils.LazyFile | None,
1675
- sanitize_output: bool,
1676
- host_data: service.hosts.HostData,
1677
- client: ServiceClient | None,
1678
- report: ReportToService | click.utils.LazyFile | None,
1679
- telemetry: bool,
1680
- api_name: str | None,
1681
- location: str,
1682
- base_url: str | None,
1683
- started_at: str,
1684
- output_config: OutputConfig,
1685
- ) -> None:
1686
- """Execute a prepared runner by drawing events from it and passing to a proper handler."""
1687
- handlers: list[EventHandler] = []
1688
- report_context: ServiceReportContext | FileReportContext | None = None
1689
- report_queue: Queue
1690
- if client:
1691
- # If API name is specified, validate it
1692
- report_queue = Queue()
1693
- report_context = ServiceReportContext(queue=report_queue, service_base_url=client.base_url)
1694
- handlers.append(
1695
- service.ServiceReportHandler(
1696
- client=client,
1697
- host_data=host_data,
1698
- api_name=api_name,
1699
- location=location,
1700
- base_url=base_url,
1701
- started_at=started_at,
1702
- out_queue=report_queue,
1703
- telemetry=telemetry,
1704
- )
1705
- )
1706
- elif isinstance(report, click.utils.LazyFile):
1707
- _open_file(report)
1708
- report_queue = Queue()
1709
- report_context = FileReportContext(queue=report_queue, filename=report.name)
1710
- handlers.append(
1711
- service.FileReportHandler(
1712
- file_handle=report,
1713
- api_name=api_name,
1714
- location=location,
1715
- base_url=base_url,
1716
- started_at=started_at,
1717
- out_queue=report_queue,
1718
- telemetry=telemetry,
1719
- )
1720
- )
1721
- if junit_xml is not None:
1722
- _open_file(junit_xml)
1723
- handlers.append(JunitXMLHandler(junit_xml))
1724
- if debug_output_file is not None:
1725
- _open_file(debug_output_file)
1726
- handlers.append(DebugOutputHandler(debug_output_file))
1727
- if cassette_path is not None:
1728
- # This handler should be first to have logs writing completed when the output handler will display statistic
1729
- _open_file(cassette_path)
1730
- handlers.append(
1731
- cassettes.CassetteWriter(
1732
- cassette_path, format=cassette_format, preserve_exact_body_bytes=cassette_preserve_exact_body_bytes
1733
- )
1734
- )
1735
- for custom_handler in CUSTOM_HANDLERS:
1736
- handlers.append(custom_handler(*ctx.args, **ctx.params))
1737
- handlers.append(get_output_handler(workers_num))
1738
- if sanitize_output:
1739
- handlers.insert(0, SanitizationHandler())
1740
- execution_context = ExecutionContext(
1741
- hypothesis_settings=hypothesis_settings,
1742
- workers_num=workers_num,
1743
- rate_limit=rate_limit,
1744
- show_trace=show_trace,
1745
- wait_for_schema=wait_for_schema,
1746
- validate_schema=validate_schema,
1747
- cassette_path=cassette_path.name if cassette_path is not None else None,
1748
- junit_xml_file=junit_xml.name if junit_xml is not None else None,
1749
- verbosity=verbosity,
1750
- code_sample_style=code_sample_style,
1751
- report=report_context,
1752
- output_config=output_config,
1753
- )
1754
-
1755
- def shutdown() -> None:
1756
- for _handler in handlers:
1757
- _handler.shutdown()
1758
-
1759
- GLOBAL_HOOK_DISPATCHER.dispatch("after_init_cli_run_handlers", HookContext(), handlers, execution_context)
1760
- event = None
1761
- try:
1762
- for event in event_stream:
1763
- for handler in handlers:
1764
- try:
1765
- handler.handle_event(execution_context, event)
1766
- except Exception as exc:
1767
- # `Abort` is used for handled errors
1768
- if not isinstance(exc, click.Abort):
1769
- display_handler_error(handler, exc)
1770
- raise
1771
- except Exception as exc:
1772
- if isinstance(exc, click.Abort):
1773
- # To avoid showing "Aborted!" message, which is the default behavior in Click
1774
- sys.exit(1)
1775
- raise
1776
- finally:
1777
- shutdown()
1778
- if event is not None and event.is_terminal:
1779
- exit_code = get_exit_code(event)
1780
- sys.exit(exit_code)
1781
- # Event stream did not finish with a terminal event. Only possible if the handler is broken
1782
- click.secho("Unexpected error", fg="red")
1783
- sys.exit(1)
1784
-
1785
-
1786
- def _open_file(file: click.utils.LazyFile) -> None:
1787
- from ..utils import _ensure_parent
1788
-
1789
- try:
1790
- _ensure_parent(file.name, fail_silently=False)
1791
- except OSError as exc:
1792
- raise click.BadParameter(f"'{file.name}': {exc.strerror}") from exc
1793
- try:
1794
- file.open()
1795
- except click.FileError as exc:
1796
- raise click.BadParameter(exc.format_message()) from exc
1797
-
1798
-
1799
- def is_built_in_handler(handler: EventHandler) -> bool:
1800
- # Look for exact instances, not subclasses
1801
- return any(
1802
- type(handler) is class_
1803
- for class_ in (
1804
- output.default.DefaultOutputStyleHandler,
1805
- output.short.ShortOutputStyleHandler,
1806
- service.FileReportHandler,
1807
- service.ServiceReportHandler,
1808
- DebugOutputHandler,
1809
- cassettes.CassetteWriter,
1810
- JunitXMLHandler,
1811
- SanitizationHandler,
1812
- )
1813
- )
1814
-
1815
-
1816
- def display_handler_error(handler: EventHandler, exc: Exception) -> None:
1817
- """Display error that happened within."""
1818
- is_built_in = is_built_in_handler(handler)
1819
- if is_built_in:
1820
- click.secho("Internal Error", fg="red", bold=True)
1821
- click.secho("\nSchemathesis encountered an unexpected issue.")
1822
- trace = exc.__traceback__
1823
- else:
1824
- click.secho("CLI Handler Error", fg="red", bold=True)
1825
- click.echo(f"\nAn error occurred within your custom CLI handler `{bold(handler.__class__.__name__)}`.")
1826
- trace = extract_nth_traceback(exc.__traceback__, 1)
1827
- lines = traceback.format_exception(type(exc), exc, trace)
1828
- message = "".join(lines).strip()
1829
- click.secho(f"\n{message}", fg="red")
1830
- if is_built_in:
1831
- click.echo(
1832
- f"\nWe apologize for the inconvenience. This appears to be an internal issue.\n"
1833
- f"Please consider reporting this error to our issue tracker:\n\n {ISSUE_TRACKER_URL}."
1834
- )
1835
- else:
1836
- click.echo(
1837
- f"\nFor more information on implementing extensions for Schemathesis CLI, visit {EXTENSIONS_DOCUMENTATION_URL}"
1838
- )
1839
-
1840
-
1841
- def handle_service_error(exc: requests.HTTPError, api_name: str) -> NoReturn:
1842
- import requests
1843
-
1844
- response = cast(requests.Response, exc.response)
1845
- if response.status_code == 403:
1846
- error_message(response.json()["detail"])
1847
- elif response.status_code == 404:
1848
- error_message(f"API with name `{api_name}` not found!")
1849
- else:
1850
- output.default.display_service_error(service.Error(exc), message_prefix="❌ ")
1851
- sys.exit(1)
1852
-
1853
-
1854
- def get_exit_code(event: events.ExecutionEvent) -> int:
1855
- if isinstance(event, events.Finished):
1856
- if event.has_failures or event.has_errors:
1857
- return 1
1858
- return 0
1859
- # Practically not possible. May occur only if the output handler is broken - in this case we still will have the
1860
- # right exit code.
1861
- return 1
1862
-
1863
-
1864
- @schemathesis.command(short_help="Replay requests from a saved cassette.")
1865
- @click.argument("cassette_path", type=click.Path(exists=True))
1866
- @click.option("--id", "id_", help="ID of interaction to replay", type=str)
1867
- @click.option("--status", help="Status of interactions to replay", type=str)
1868
- @click.option("--uri", help="A regexp that filters interactions by their request URI", type=str)
1869
- @click.option("--method", help="A regexp that filters interactions by their request method", type=str)
1870
- @click.option("--no-color", help="Disable ANSI color escape codes", type=bool, is_flag=True)
1871
- @click.option("--force-color", help="Explicitly tells to enable ANSI color escape codes", type=bool, is_flag=True)
1872
- @click.option("--verbosity", "-v", help="Increase verbosity of the output", count=True)
1873
- @with_request_tls_verify
1874
- @with_request_proxy
1875
- @with_request_cert
1876
- @with_request_cert_key
1877
- @click.pass_context
1878
- def replay(
1879
- ctx: click.Context,
1880
- cassette_path: str,
1881
- id_: str | None,
1882
- status: str | None = None,
1883
- uri: str | None = None,
1884
- method: str | None = None,
1885
- no_color: bool = False,
1886
- verbosity: int = 0,
1887
- request_tls_verify: bool = True,
1888
- request_cert: str | None = None,
1889
- request_cert_key: str | None = None,
1890
- request_proxy: str | None = None,
1891
- force_color: bool = False,
1892
- ) -> None:
1893
- """Replay a cassette.
1894
-
1895
- Cassettes in VCR-compatible format can be replayed.
1896
- For example, ones that are recorded with the ``--cassette-path`` option of the `st run` command.
1897
- """
1898
- if no_color and force_color:
1899
- raise click.UsageError(COLOR_OPTIONS_INVALID_USAGE_MESSAGE)
1900
- decide_color_output(ctx, no_color, force_color)
1901
-
1902
- click.secho(f"{bold('Replaying cassette')}: {cassette_path}")
1903
- with open(cassette_path, "rb") as fd:
1904
- cassette = load_yaml(fd)
1905
- click.secho(f"{bold('Total interactions')}: {len(cassette['http_interactions'])}\n")
1906
- for replayed in cassettes.replay(
1907
- cassette,
1908
- id_=id_,
1909
- status=status,
1910
- uri=uri,
1911
- method=method,
1912
- request_tls_verify=request_tls_verify,
1913
- request_cert=prepare_request_cert(request_cert, request_cert_key),
1914
- request_proxy=request_proxy,
1915
- ):
1916
- click.secho(f" {bold('ID')} : {replayed.interaction['id']}")
1917
- click.secho(f" {bold('URI')} : {replayed.interaction['request']['uri']}")
1918
- click.secho(f" {bold('Old status code')} : {replayed.interaction['response']['status']['code']}")
1919
- click.secho(f" {bold('New status code')} : {replayed.response.status_code}")
1920
- if verbosity > 0:
1921
- data = replayed.interaction["response"]
1922
- old_body = ""
1923
- # Body may be missing for 204 responses
1924
- if "body" in data:
1925
- if "base64_string" in data["body"]:
1926
- content = data["body"]["base64_string"]
1927
- if content:
1928
- old_body = base64.b64decode(content).decode(errors="replace")
1929
- else:
1930
- old_body = data["body"]["string"]
1931
- click.secho(f" {bold('Old payload')} : {old_body}")
1932
- click.secho(f" {bold('New payload')} : {replayed.response.text}")
1933
- click.echo()
1934
-
1935
-
1936
- @schemathesis.command(short_help="Upload report to Schemathesis.io.")
1937
- @click.argument("report", type=click.File(mode="rb"))
1938
- @click.option(
1939
- "--schemathesis-io-token",
1940
- help="Schemathesis.io authentication token",
1941
- type=str,
1942
- envvar=service.TOKEN_ENV_VAR,
1943
- )
1944
- @click.option(
1945
- "--schemathesis-io-url",
1946
- help="Schemathesis.io base URL",
1947
- default=service.DEFAULT_URL,
1948
- type=str,
1949
- envvar=service.URL_ENV_VAR,
1950
- )
1951
- @with_request_tls_verify
1952
- @with_hosts_file
1953
- def upload(
1954
- report: io.BufferedReader,
1955
- hosts_file: str,
1956
- request_tls_verify: bool = True,
1957
- schemathesis_io_url: str = service.DEFAULT_URL,
1958
- schemathesis_io_token: str | None = None,
1959
- ) -> None:
1960
- """Upload report to Schemathesis.io."""
1961
- from ..service.client import ServiceClient
1962
- from ..service.models import UploadResponse, UploadSource
1963
-
1964
- schemathesis_io_hostname = urlparse(schemathesis_io_url).netloc
1965
- host_data = service.hosts.HostData(schemathesis_io_hostname, hosts_file)
1966
- token = schemathesis_io_token or service.hosts.get_token(hostname=schemathesis_io_hostname, hosts_file=hosts_file)
1967
- client = ServiceClient(base_url=schemathesis_io_url, token=token, verify=request_tls_verify)
1968
- ci_environment = service.ci.environment()
1969
- provider = ci_environment.provider if ci_environment is not None else None
1970
- response = client.upload_report(
1971
- report=report.read(),
1972
- correlation_id=host_data.correlation_id,
1973
- ci_provider=provider,
1974
- source=UploadSource.UPLOAD_COMMAND,
1975
- )
1976
- if isinstance(response, UploadResponse):
1977
- host_data.store_correlation_id(response.correlation_id)
1978
- click.echo(f"{response.message}\n{response.next_url}")
1979
- else:
1980
- error_message(f"Failed to upload report to {schemathesis_io_hostname}: " + bold(response.detail))
1981
- sys.exit(1)
1982
-
1983
-
1984
- @schemathesis.group(short_help="Authenticate with Schemathesis.io.")
1985
- def auth() -> None:
1986
- pass
1987
-
1988
-
1989
- @auth.command(short_help="Authenticate with a Schemathesis.io host.")
1990
- @click.argument("token", type=str, envvar=service.TOKEN_ENV_VAR)
1991
- @click.option(
1992
- "--hostname",
1993
- help="The hostname of the Schemathesis.io instance to authenticate with",
1994
- type=str,
1995
- default=service.DEFAULT_HOSTNAME,
1996
- envvar=service.HOSTNAME_ENV_VAR,
1997
- )
1998
- @click.option(
1999
- "--protocol",
2000
- type=click.Choice(["https", "http"]),
2001
- default=service.DEFAULT_PROTOCOL,
2002
- envvar=service.PROTOCOL_ENV_VAR,
2003
- )
2004
- @with_request_tls_verify
2005
- @with_hosts_file
2006
- def login(token: str, hostname: str, hosts_file: str, protocol: str, request_tls_verify: bool = True) -> None:
2007
- """Authenticate with a Schemathesis.io host."""
2008
- import requests
2009
-
2010
- try:
2011
- username = service.auth.login(token, hostname, protocol, request_tls_verify)
2012
- service.hosts.store(token, hostname, hosts_file)
2013
- success_message(f"Logged in into {hostname} as " + bold(username))
2014
- except requests.HTTPError as exc:
2015
- response = cast(requests.Response, exc.response)
2016
- detail = response.json()["detail"]
2017
- error_message(f"Failed to login into {hostname}: " + bold(detail))
2018
- sys.exit(1)
2019
-
2020
-
2021
- @auth.command(short_help="Remove authentication for a Schemathesis.io host.")
2022
- @click.option(
2023
- "--hostname",
2024
- help="The hostname of the Schemathesis.io instance to authenticate with",
2025
- type=str,
2026
- default=service.DEFAULT_HOSTNAME,
2027
- envvar=service.HOSTNAME_ENV_VAR,
2028
- )
2029
- @with_hosts_file
2030
- def logout(hostname: str, hosts_file: str) -> None:
2031
- """Remove authentication for a Schemathesis.io host."""
2032
- result = service.hosts.remove(hostname, hosts_file)
2033
- if result == service.hosts.RemoveAuth.success:
2034
- success_message(f"Logged out of {hostname} account")
2035
- else:
2036
- if result == service.hosts.RemoveAuth.no_match:
2037
- warning_message(f"Not logged in to {hostname}")
2038
- if result == service.hosts.RemoveAuth.no_hosts:
2039
- warning_message("Not logged in to any hosts")
2040
- if result == service.hosts.RemoveAuth.error:
2041
- error_message(f"Failed to read the hosts file. Try to remove {hosts_file}")
2042
- sys.exit(1)
2043
-
2044
-
2045
- def success_message(message: str) -> None:
2046
- click.secho(click.style("✔️", fg="green") + f" {message}")
2047
-
2048
-
2049
- def warning_message(message: str) -> None:
2050
- click.secho(click.style("🟡️", fg="yellow") + f" {message}")
2051
-
2052
-
2053
- def error_message(message: str) -> None:
2054
- click.secho(f"❌ {message}")
2055
-
2056
-
2057
- def bold(message: str) -> str:
2058
- return click.style(message, bold=True)
2059
-
2060
-
2061
- def decide_color_output(ctx: click.Context, no_color: bool, force_color: bool) -> None:
2062
- if force_color:
2063
- ctx.color = True
2064
- elif no_color or "NO_COLOR" in os.environ:
2065
- ctx.color = False
2066
-
2067
-
2068
- def add_option(*args: Any, cls: type = click.Option, **kwargs: Any) -> None:
2069
- """Add a new CLI option to `st run`."""
2070
- run.params.append(cls(args, **kwargs))
2071
-
2072
-
2073
- @dataclass
2074
- class Group:
2075
- name: str
2076
-
2077
- def add_option(self, *args: Any, **kwargs: Any) -> None:
2078
- kwargs["cls"] = GroupedOption
2079
- kwargs["group"] = self.name
2080
- add_option(*args, **kwargs)
8
+ __all__ = ["schemathesis", "run", "EventHandler", "add_group", "handler"]
2081
9
 
2082
10
 
2083
11
  def add_group(name: str, *, index: int | None = None) -> Group:
@@ -2087,31 +15,3 @@ def add_group(name: str, *, index: int | None = None) -> Group:
2087
15
  else:
2088
16
  GROUPS.append(name)
2089
17
  return Group(name)
2090
-
2091
-
2092
- def handler() -> Callable[[type], None]:
2093
- """Register a new CLI event handler."""
2094
-
2095
- def _wrapper(cls: type) -> None:
2096
- CUSTOM_HANDLERS.append(cls)
2097
-
2098
- return _wrapper
2099
-
2100
-
2101
- @HookDispatcher.register_spec([HookScope.GLOBAL])
2102
- def after_init_cli_run_handlers(
2103
- context: HookContext, handlers: list[EventHandler], execution_context: ExecutionContext
2104
- ) -> None:
2105
- """Called after CLI hooks are initialized.
2106
-
2107
- Might be used to add extra event handlers.
2108
- """
2109
-
2110
-
2111
- @HookDispatcher.register_spec([HookScope.GLOBAL])
2112
- def process_call_kwargs(context: HookContext, case: Case, kwargs: dict[str, Any]) -> None:
2113
- """Called before every network call in CLI tests.
2114
-
2115
- Aims to modify the argument passed to `case.call`.
2116
- Note that you need to modify `kwargs` in-place.
2117
- """