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
@@ -0,0 +1,387 @@
1
+ from __future__ import annotations
2
+
3
+ import textwrap
4
+ from dataclasses import dataclass, field
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from schemathesis.core.failures import Failure, Severity
8
+ from schemathesis.core.output import OutputConfig, truncate_json
9
+
10
+ if TYPE_CHECKING:
11
+ from jsonschema import ValidationError
12
+
13
+
14
+ @dataclass
15
+ class NegativeDataRejectionConfig:
16
+ # 5xx will pass through
17
+ allowed_statuses: list[str] = field(default_factory=lambda: ["400", "401", "403", "404", "422", "428", "5xx"])
18
+
19
+
20
+ @dataclass
21
+ class PositiveDataAcceptanceConfig:
22
+ allowed_statuses: list[str] = field(default_factory=lambda: ["2xx", "401", "403", "404"])
23
+
24
+
25
+ @dataclass
26
+ class MissingRequiredHeaderConfig:
27
+ allowed_statuses: list[str] = field(default_factory=lambda: ["406"])
28
+
29
+
30
+ class UndefinedStatusCode(Failure):
31
+ """Response has a status code that is not defined in the schema."""
32
+
33
+ __slots__ = (
34
+ "operation",
35
+ "status_code",
36
+ "defined_status_codes",
37
+ "allowed_status_codes",
38
+ "message",
39
+ "title",
40
+ "case_id",
41
+ "severity",
42
+ )
43
+
44
+ def __init__(
45
+ self,
46
+ *,
47
+ operation: str,
48
+ status_code: int,
49
+ defined_status_codes: list[str],
50
+ allowed_status_codes: list[int],
51
+ message: str,
52
+ title: str = "Undocumented HTTP status code",
53
+ case_id: str | None = None,
54
+ ) -> None:
55
+ self.operation = operation
56
+ self.status_code = status_code
57
+ self.defined_status_codes = defined_status_codes
58
+ self.allowed_status_codes = allowed_status_codes
59
+ self.message = message
60
+ self.title = title
61
+ self.case_id = case_id
62
+ self.severity = Severity.MEDIUM
63
+
64
+ @property
65
+ def _unique_key(self) -> str:
66
+ return str(self.status_code)
67
+
68
+
69
+ class MissingHeaders(Failure):
70
+ """Some required headers are missing."""
71
+
72
+ __slots__ = ("operation", "missing_headers", "message", "title", "case_id", "severity")
73
+
74
+ def __init__(
75
+ self,
76
+ *,
77
+ operation: str,
78
+ missing_headers: list[str],
79
+ message: str,
80
+ title: str = "Missing required headers",
81
+ case_id: str | None = None,
82
+ ) -> None:
83
+ self.operation = operation
84
+ self.missing_headers = missing_headers
85
+ self.message = message
86
+ self.title = title
87
+ self.case_id = case_id
88
+ self.severity = Severity.MEDIUM
89
+
90
+
91
+ class JsonSchemaError(Failure):
92
+ """Additional information about JSON Schema validation errors."""
93
+
94
+ __slots__ = (
95
+ "operation",
96
+ "validation_message",
97
+ "schema_path",
98
+ "schema",
99
+ "instance_path",
100
+ "instance",
101
+ "message",
102
+ "title",
103
+ "case_id",
104
+ "severity",
105
+ )
106
+
107
+ def __init__(
108
+ self,
109
+ *,
110
+ operation: str,
111
+ validation_message: str,
112
+ schema_path: list[str | int],
113
+ schema: dict[str, Any] | bool,
114
+ instance_path: list[str | int],
115
+ instance: None | bool | float | str | list | dict[str, Any],
116
+ message: str,
117
+ title: str = "Response violates schema",
118
+ case_id: str | None = None,
119
+ ) -> None:
120
+ self.operation = operation
121
+ self.validation_message = validation_message
122
+ self.schema_path = schema_path
123
+ self.schema = schema
124
+ self.instance_path = instance_path
125
+ self.instance = instance
126
+ self.message = message
127
+ self.title = title
128
+ self.case_id = case_id
129
+ self.severity = Severity.HIGH
130
+
131
+ @property
132
+ def _unique_key(self) -> str:
133
+ return "/".join(map(str, self.schema_path))
134
+
135
+ @classmethod
136
+ def from_exception(
137
+ cls,
138
+ *,
139
+ title: str = "Response violates schema",
140
+ operation: str,
141
+ exc: ValidationError,
142
+ output_config: OutputConfig | None = None,
143
+ ) -> JsonSchemaError:
144
+ output_config = OutputConfig.from_parent(output_config, max_lines=20)
145
+ schema = textwrap.indent(truncate_json(exc.schema, config=output_config), prefix=" ")
146
+ value = textwrap.indent(truncate_json(exc.instance, config=output_config), prefix=" ")
147
+ schema_path = list(exc.absolute_schema_path)
148
+ if len(schema_path) > 1:
149
+ # Exclude the last segment, which is already in the schema
150
+ schema_title = "Schema at "
151
+ for segment in schema_path[:-1]:
152
+ schema_title += f"/{segment}"
153
+ else:
154
+ schema_title = "Schema"
155
+ message = f"{exc.message}\n\n{schema_title}:\n\n{schema}\n\nValue:\n\n{value}"
156
+ return cls(
157
+ operation=operation,
158
+ title=title,
159
+ message=message,
160
+ validation_message=exc.message,
161
+ schema_path=schema_path,
162
+ schema=exc.schema,
163
+ instance_path=list(exc.absolute_path),
164
+ instance=exc.instance,
165
+ )
166
+
167
+
168
+ class MissingContentType(Failure):
169
+ """Content type header is missing."""
170
+
171
+ __slots__ = ("operation", "media_types", "message", "title", "case_id", "severity")
172
+
173
+ def __init__(
174
+ self,
175
+ *,
176
+ operation: str,
177
+ media_types: list[str],
178
+ message: str,
179
+ title: str = "Missing Content-Type header",
180
+ case_id: str | None = None,
181
+ ) -> None:
182
+ self.operation = operation
183
+ self.media_types = media_types
184
+ self.message = message
185
+ self.title = title
186
+ self.case_id = case_id
187
+ self.severity = Severity.MEDIUM
188
+
189
+ @property
190
+ def _unique_key(self) -> str:
191
+ return ""
192
+
193
+
194
+ class MalformedMediaType(Failure):
195
+ """Media type name is malformed."""
196
+
197
+ __slots__ = ("operation", "actual", "defined", "message", "title", "case_id", "severity")
198
+
199
+ def __init__(
200
+ self,
201
+ *,
202
+ operation: str,
203
+ actual: str,
204
+ defined: str,
205
+ message: str,
206
+ title: str = "Malformed media type",
207
+ case_id: str | None = None,
208
+ ) -> None:
209
+ self.operation = operation
210
+ self.actual = actual
211
+ self.defined = defined
212
+ self.message = message
213
+ self.title = title
214
+ self.case_id = case_id
215
+ self.severity = Severity.MEDIUM
216
+
217
+
218
+ class UndefinedContentType(Failure):
219
+ """Response has Content-Type that is not documented in the schema."""
220
+
221
+ __slots__ = (
222
+ "operation",
223
+ "content_type",
224
+ "defined_content_types",
225
+ "message",
226
+ "title",
227
+ "case_id",
228
+ "severity",
229
+ )
230
+
231
+ def __init__(
232
+ self,
233
+ *,
234
+ operation: str,
235
+ content_type: str,
236
+ defined_content_types: list[str],
237
+ message: str,
238
+ title: str = "Undocumented Content-Type",
239
+ case_id: str | None = None,
240
+ ) -> None:
241
+ self.operation = operation
242
+ self.content_type = content_type
243
+ self.defined_content_types = defined_content_types
244
+ self.message = message
245
+ self.title = title
246
+ self.case_id = case_id
247
+ self.severity = Severity.MEDIUM
248
+
249
+ @property
250
+ def _unique_key(self) -> str:
251
+ return self.content_type
252
+
253
+
254
+ class UseAfterFree(Failure):
255
+ """Resource was used after a successful DELETE operation on it."""
256
+
257
+ __slots__ = ("operation", "message", "free", "usage", "title", "case_id", "severity")
258
+
259
+ def __init__(
260
+ self,
261
+ *,
262
+ operation: str,
263
+ message: str,
264
+ free: str,
265
+ usage: str,
266
+ title: str = "Use after free",
267
+ case_id: str | None = None,
268
+ ) -> None:
269
+ self.operation = operation
270
+ self.message = message
271
+ self.free = free
272
+ self.usage = usage
273
+ self.title = title
274
+ self.case_id = case_id
275
+ self.severity = Severity.CRITICAL
276
+
277
+ @property
278
+ def _unique_key(self) -> str:
279
+ return ""
280
+
281
+
282
+ class EnsureResourceAvailability(Failure):
283
+ """Resource is not available immediately after creation."""
284
+
285
+ __slots__ = ("operation", "message", "created_with", "not_available_with", "title", "case_id", "severity")
286
+
287
+ def __init__(
288
+ self,
289
+ *,
290
+ operation: str,
291
+ message: str,
292
+ created_with: str,
293
+ not_available_with: str,
294
+ title: str = "Resource is not available after creation",
295
+ case_id: str | None = None,
296
+ ) -> None:
297
+ self.operation = operation
298
+ self.message = message
299
+ self.created_with = created_with
300
+ self.not_available_with = not_available_with
301
+ self.title = title
302
+ self.case_id = case_id
303
+ self.severity = Severity.MEDIUM
304
+
305
+ @property
306
+ def _unique_key(self) -> str:
307
+ return ""
308
+
309
+
310
+ class IgnoredAuth(Failure):
311
+ """The API operation does not check the specified authentication."""
312
+
313
+ __slots__ = ("operation", "message", "title", "case_id", "severity")
314
+
315
+ def __init__(
316
+ self,
317
+ *,
318
+ operation: str,
319
+ message: str,
320
+ title: str = "Authentication declared but not enforced",
321
+ case_id: str | None = None,
322
+ ) -> None:
323
+ self.operation = operation
324
+ self.message = message
325
+ self.title = title
326
+ self.case_id = case_id
327
+ self.severity = Severity.CRITICAL
328
+
329
+ @property
330
+ def _unique_key(self) -> str:
331
+ return ""
332
+
333
+
334
+ class AcceptedNegativeData(Failure):
335
+ """Response with negative data was accepted."""
336
+
337
+ __slots__ = ("operation", "message", "status_code", "allowed_statuses", "title", "case_id", "severity")
338
+
339
+ def __init__(
340
+ self,
341
+ *,
342
+ operation: str,
343
+ message: str,
344
+ status_code: int,
345
+ allowed_statuses: list[str],
346
+ title: str = "Accepted negative data",
347
+ case_id: str | None = None,
348
+ ) -> None:
349
+ self.operation = operation
350
+ self.message = message
351
+ self.status_code = status_code
352
+ self.allowed_statuses = allowed_statuses
353
+ self.title = title
354
+ self.case_id = case_id
355
+ self.severity = Severity.MEDIUM
356
+
357
+ @property
358
+ def _unique_key(self) -> str:
359
+ return str(self.status_code)
360
+
361
+
362
+ class RejectedPositiveData(Failure):
363
+ """Response with positive data was rejected."""
364
+
365
+ __slots__ = ("operation", "message", "status_code", "allowed_statuses", "title", "case_id", "severity")
366
+
367
+ def __init__(
368
+ self,
369
+ *,
370
+ operation: str,
371
+ message: str,
372
+ status_code: int,
373
+ allowed_statuses: list[str],
374
+ title: str = "Rejected positive data",
375
+ case_id: str | None = None,
376
+ ) -> None:
377
+ self.operation = operation
378
+ self.message = message
379
+ self.status_code = status_code
380
+ self.allowed_statuses = allowed_statuses
381
+ self.title = title
382
+ self.case_id = case_id
383
+ self.severity = Severity.MEDIUM
384
+
385
+ @property
386
+ def _unique_key(self) -> str:
387
+ return str(self.status_code)
File without changes
@@ -0,0 +1,63 @@
1
+ from collections.abc import Mapping
2
+
3
+ from schemathesis.core import NOT_SET
4
+ from schemathesis.core.validation import contains_unicode_surrogate_pair, has_invalid_characters, is_latin_1_encodable
5
+
6
+ __all__ = [
7
+ "is_valid_path",
8
+ "is_valid_header",
9
+ "is_valid_urlencoded",
10
+ "is_valid_query",
11
+ ]
12
+
13
+
14
+ def is_valid_path(parameters: dict[str, object]) -> bool:
15
+ """Empty strings ("") are excluded from path by urllib3.
16
+
17
+ A path containing to "/" or "%2F" will lead to ambiguous path resolution in
18
+ many frameworks and libraries, such behaviour have been observed in both
19
+ WSGI and ASGI applications.
20
+
21
+ In this case one variable in the path template will be empty, which will lead to 404 in most of the cases.
22
+ Because of it this case doesn't bring much value and might lead to false positives results of Schemathesis runs.
23
+ """
24
+ return not any(
25
+ (
26
+ value in ("/", "")
27
+ or contains_unicode_surrogate_pair(value)
28
+ or isinstance(value, str)
29
+ and ("/" in value or "}" in value or "{" in value)
30
+ )
31
+ for value in parameters.values()
32
+ )
33
+
34
+
35
+ def is_valid_header(headers: dict[str, object]) -> bool:
36
+ for name, value in headers.items():
37
+ if not is_latin_1_encodable(value):
38
+ return False
39
+ if has_invalid_characters(name, value):
40
+ return False
41
+ return True
42
+
43
+
44
+ def is_valid_query(query: dict[str, object]) -> bool:
45
+ for name, value in query.items():
46
+ if contains_unicode_surrogate_pair(name) or contains_unicode_surrogate_pair(value):
47
+ return False
48
+ return True
49
+
50
+
51
+ def is_valid_urlencoded(data: object) -> bool:
52
+ # TODO: write a test that will check if `requests` can send it
53
+ if data is NOT_SET or isinstance(data, Mapping):
54
+ return True
55
+
56
+ if hasattr(data, "__iter__"):
57
+ try:
58
+ for _, _ in data:
59
+ pass
60
+ return True
61
+ except (TypeError, ValueError):
62
+ return False
63
+ return False
@@ -0,0 +1,178 @@
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import json
5
+ import re
6
+ from os import PathLike
7
+ from pathlib import Path
8
+ from typing import IO, TYPE_CHECKING, Any, Mapping
9
+
10
+ from schemathesis.core import media_types
11
+ from schemathesis.core.deserialization import deserialize_yaml
12
+ from schemathesis.core.errors import LoaderError, LoaderErrorKind
13
+ from schemathesis.core.loaders import load_from_url, prepare_request_kwargs, raise_for_status, require_relative_url
14
+ from schemathesis.hooks import HookContext, dispatch
15
+ from schemathesis.python import asgi, wsgi
16
+
17
+ if TYPE_CHECKING:
18
+ from schemathesis.specs.openapi.schemas import BaseOpenAPISchema
19
+
20
+
21
+ def from_asgi(path: str, app: Any, **kwargs: Any) -> BaseOpenAPISchema:
22
+ require_relative_url(path)
23
+ client = asgi.get_client(app)
24
+ response = load_from_url(client.get, url=path, **kwargs)
25
+ content_type = detect_content_type(headers=response.headers, path=path)
26
+ schema = load_content(response.text, content_type)
27
+ return from_dict(schema=schema).configure(app=app, location=path)
28
+
29
+
30
+ def from_wsgi(path: str, app: Any, **kwargs: Any) -> BaseOpenAPISchema:
31
+ require_relative_url(path)
32
+ prepare_request_kwargs(kwargs)
33
+ client = wsgi.get_client(app)
34
+ response = client.get(path=path, **kwargs)
35
+ raise_for_status(response)
36
+ content_type = detect_content_type(headers=response.headers, path=path)
37
+ schema = load_content(response.text, content_type)
38
+ return from_dict(schema=schema).configure(app=app, location=path)
39
+
40
+
41
+ def from_url(url: str, *, wait_for_schema: float | None = None, **kwargs: Any) -> BaseOpenAPISchema:
42
+ """Load from URL."""
43
+ import requests
44
+
45
+ response = load_from_url(requests.get, url=url, wait_for_schema=wait_for_schema, **kwargs)
46
+ content_type = detect_content_type(headers=response.headers, path=url)
47
+ schema = load_content(response.text, content_type)
48
+ return from_dict(schema=schema).configure(location=url)
49
+
50
+
51
+ def from_path(path: PathLike | str, *, encoding: str = "utf-8") -> BaseOpenAPISchema:
52
+ """Load from a filesystem path."""
53
+ with open(path, encoding=encoding) as file:
54
+ content_type = detect_content_type(headers=None, path=str(path))
55
+ schema = load_content(file.read(), content_type)
56
+ return from_dict(schema=schema).configure(location=Path(path).absolute().as_uri())
57
+
58
+
59
+ def from_file(file: IO[str] | str) -> BaseOpenAPISchema:
60
+ """Load from file-like object or string."""
61
+ if isinstance(file, str):
62
+ data = file
63
+ else:
64
+ data = file.read()
65
+ try:
66
+ schema = json.loads(data)
67
+ except json.JSONDecodeError:
68
+ schema = _load_yaml(data)
69
+ return from_dict(schema)
70
+
71
+
72
+ def from_dict(schema: dict[str, Any]) -> BaseOpenAPISchema:
73
+ """Base loader that others build upon."""
74
+ from schemathesis.specs.openapi.schemas import OpenApi30, SwaggerV20
75
+
76
+ if not isinstance(schema, dict):
77
+ raise LoaderError(LoaderErrorKind.OPEN_API_INVALID_SCHEMA, SCHEMA_INVALID_ERROR)
78
+ hook_context = HookContext()
79
+ dispatch("before_load_schema", hook_context, schema)
80
+
81
+ if "swagger" in schema:
82
+ instance = SwaggerV20(schema)
83
+ elif "openapi" in schema:
84
+ version = schema["openapi"]
85
+ if not OPENAPI_VERSION_RE.match(version):
86
+ raise LoaderError(
87
+ LoaderErrorKind.OPEN_API_UNSUPPORTED_VERSION,
88
+ f"The provided schema uses Open API {version}, which is currently not supported.",
89
+ )
90
+ instance = OpenApi30(schema)
91
+ else:
92
+ raise LoaderError(
93
+ LoaderErrorKind.OPEN_API_UNSPECIFIED_VERSION,
94
+ "Unable to determine the Open API version as it's not specified in the document.",
95
+ )
96
+ dispatch("after_load_schema", hook_context, instance)
97
+ return instance
98
+
99
+
100
+ class ContentType(enum.Enum):
101
+ """Known content types for schema files."""
102
+
103
+ JSON = enum.auto()
104
+ YAML = enum.auto()
105
+ UNKNOWN = enum.auto()
106
+
107
+
108
+ def detect_content_type(*, headers: Mapping[str, str] | None = None, path: str | None = None) -> ContentType:
109
+ """Detect content type from various sources."""
110
+ if headers is not None and (content_type := _detect_from_headers(headers)) != ContentType.UNKNOWN:
111
+ return content_type
112
+ if path is not None and (content_type := _detect_from_path(path)) != ContentType.UNKNOWN:
113
+ return content_type
114
+ return ContentType.UNKNOWN
115
+
116
+
117
+ def _detect_from_headers(headers: Mapping[str, str]) -> ContentType:
118
+ """Detect content type from HTTP headers."""
119
+ content_type = headers.get("Content-Type", "").lower()
120
+ try:
121
+ if content_type and media_types.is_json(content_type):
122
+ return ContentType.JSON
123
+ if content_type and media_types.is_yaml(content_type):
124
+ return ContentType.YAML
125
+ except ValueError:
126
+ pass
127
+ return ContentType.UNKNOWN
128
+
129
+
130
+ def _detect_from_path(path: str) -> ContentType:
131
+ """Detect content type from file path."""
132
+ suffix = Path(path).suffix.lower()
133
+ if suffix == ".json":
134
+ return ContentType.JSON
135
+ if suffix in (".yaml", ".yml"):
136
+ return ContentType.YAML
137
+ return ContentType.UNKNOWN
138
+
139
+
140
+ def load_content(content: str, content_type: ContentType) -> dict[str, Any]:
141
+ """Load content using appropriate parser."""
142
+ if content_type == ContentType.JSON:
143
+ return _load_json(content)
144
+ if content_type == ContentType.YAML:
145
+ return _load_yaml(content)
146
+ # If type is unknown, try JSON first, then YAML
147
+ try:
148
+ return _load_json(content)
149
+ except json.JSONDecodeError:
150
+ return _load_yaml(content)
151
+
152
+
153
+ def _load_json(content: str) -> dict[str, Any]:
154
+ try:
155
+ return json.loads(content)
156
+ except json.JSONDecodeError as exc:
157
+ raise LoaderError(
158
+ LoaderErrorKind.SYNTAX_ERROR,
159
+ SCHEMA_SYNTAX_ERROR,
160
+ extras=[entry for entry in str(exc).splitlines() if entry],
161
+ ) from exc
162
+
163
+
164
+ def _load_yaml(content: str) -> dict[str, Any]:
165
+ import yaml
166
+
167
+ try:
168
+ return deserialize_yaml(content)
169
+ except yaml.YAMLError as exc:
170
+ kind = LoaderErrorKind.SYNTAX_ERROR
171
+ message = SCHEMA_SYNTAX_ERROR
172
+ extras = [entry for entry in str(exc).splitlines() if entry]
173
+ raise LoaderError(kind, message, extras=extras) from exc
174
+
175
+
176
+ SCHEMA_INVALID_ERROR = "The provided API schema does not appear to be a valid OpenAPI schema"
177
+ SCHEMA_SYNTAX_ERROR = "API schema does not appear syntactically valid"
178
+ OPENAPI_VERSION_RE = re.compile(r"^3\.[01]\.[0-9](-.+)?$")
@@ -0,0 +1,5 @@
1
+ from schemathesis.pytest.loaders import from_fixture
2
+
3
+ __all__ = [
4
+ "from_fixture",
5
+ ]
@@ -0,0 +1,7 @@
1
+ from typing import NoReturn
2
+
3
+ import pytest
4
+
5
+
6
+ def fail_on_no_matches(node_id: str) -> NoReturn: # type: ignore
7
+ pytest.fail(f"Test function {node_id} does not match any API operations and therefore has no effect")