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