Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/hypothesis/errors.py: 68%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

104 statements  

1# This file is part of Hypothesis, which may be found at 

2# https://github.com/HypothesisWorks/hypothesis/ 

3# 

4# Copyright the Hypothesis Authors. 

5# Individual contributors are listed in AUTHORS.rst and the git log. 

6# 

7# This Source Code Form is subject to the terms of the Mozilla Public License, 

8# v. 2.0. If a copy of the MPL was not distributed with this file, You can 

9# obtain one at https://mozilla.org/MPL/2.0/. 

10 

11from collections.abc import Iterable, Mapping, Sequence 

12from datetime import timedelta 

13from typing import TYPE_CHECKING, Any, Literal, Self 

14 

15if TYPE_CHECKING: 

16 from hypothesis.internal.conjecture.choice import ChoiceConstraintsT 

17 from hypothesis.internal.escalation import InterestingOrigin 

18else: 

19 ChoiceConstraintsT = Mapping 

20 

21 

22class HypothesisException(Exception): 

23 """Generic parent class for exceptions thrown by Hypothesis.""" 

24 

25 

26class _Trimmable(HypothesisException): 

27 """Hypothesis can trim these tracebacks even if they're raised internally.""" 

28 

29 

30class UnsatisfiedAssumption(HypothesisException): 

31 """An internal error raised by assume. 

32 

33 If you're seeing this error something has gone wrong. 

34 """ 

35 

36 reason: str | None 

37 location: str | None 

38 

39 def __init__( 

40 self, reason: str | None = None, *, location: str | None = None 

41 ) -> None: 

42 self.reason = reason 

43 # "filename:lineno" of the failing assume() or reject() call, if known 

44 self.location = location 

45 

46 

47class NoSuchExample(HypothesisException): 

48 """The condition we have been asked to satisfy appears to be always false. 

49 

50 This does not guarantee that no example exists, only that we were 

51 unable to find one. 

52 """ 

53 

54 def __init__(self, condition_string: str, extra: str = "") -> None: 

55 super().__init__(f"No examples found of condition {condition_string}{extra}") 

56 

57 

58class Unsatisfiable(_Trimmable): 

59 """We ran out of test cases before we could find enough which satisfy the 

60 assumptions of this hypothesis. 

61 

62 This could be because the function is using |assume| in a way that is 

63 too hard to satisfy. If so, try writing a custom strategy or using a 

64 better starting point (e.g if you are requiring a list has unique 

65 values you could instead filter out all duplicate values from the list) 

66 """ 

67 

68 

69class ChoiceTooLarge(HypothesisException): 

70 """An internal error raised by choice_from_index.""" 

71 

72 

73class CannotInvert(HypothesisException): 

74 """ 

75 Internal error raised by SearchStrategy._invert, either because the value 

76 is not produced by that strategy, or because we haven't implemented an 

77 inversion for it. 

78 """ 

79 

80 

81class Flaky(_Trimmable): 

82 """ 

83 Base class for indeterministic failures. Usually one of the more 

84 specific subclasses (|FlakyFailure| or |FlakyStrategyDefinition|) is raised. 

85 

86 .. seealso:: 

87 

88 See also the :doc:`flaky failures tutorial </tutorial/flaky>`. 

89 """ 

90 

91 

92class FlakyReplay(Flaky): 

93 """Internal error raised by the conjecture engine if flaky failures are 

94 detected during replay. 

95 

96 Carries information allowing the runner to reconstruct the flakiness as 

97 a FlakyFailure exception group for final presentation. 

98 """ 

99 

100 reason: str 

101 _interesting_origins: Sequence["InterestingOrigin | None"] 

102 

103 def __init__( 

104 self, 

105 reason: str, 

106 interesting_origins: Sequence["InterestingOrigin | None"] = (), 

107 ) -> None: 

108 super().__init__(reason) 

109 self.reason = reason 

110 self._interesting_origins = interesting_origins 

111 

112 

113def _render_constraints(show: Mapping[str, object], other: Mapping[str, object]) -> str: 

114 assert show.keys() == other.keys() 

115 return ", ".join( 

116 f"{k}={'...' if v == other[k] else repr(v)}" for k, v in show.items() 

117 ) 

118 

119 

120class FlakyStrategyDefinition(Flaky): 

121 """ 

122 This function appears to cause inconsistent data generation. 

123 

124 Common causes for this problem are: 

125 1. The strategy depends on external state. e.g. it uses an external 

126 random number generator. Try to make a version that passes all the 

127 relevant state in from Hypothesis. 

128 

129 .. seealso:: 

130 

131 See also the :doc:`flaky failures tutorial </tutorial/flaky>`. 

132 """ 

133 

134 _BASE_MESSAGE = ( 

135 "Inconsistent data generation! Data generation behaved differently " 

136 "between test cases. Is your data generation depending on external " 

137 "state?" 

138 ) 

139 

140 @classmethod 

141 def with_detail(cls, detail: str) -> "FlakyStrategyDefinition": 

142 return cls(f"{cls._BASE_MESSAGE}\n\n{detail}") 

143 

144 @classmethod 

145 def from_mismatch( 

146 cls, 

147 expected_type: str, 

148 expected_constraints: ChoiceConstraintsT, 

149 actual_type: str, 

150 actual_constraints: ChoiceConstraintsT, 

151 ) -> "FlakyStrategyDefinition": 

152 if actual_type != expected_type: 

153 detail = ( 

154 "The second test case drew a different type of value than the first.\n" 

155 f" first: {expected_type}\n" 

156 f" second: {actual_type}\n" 

157 ) 

158 else: 

159 detail = ( 

160 f"The second test case drew type {actual_type} with different constraints " 

161 "than the first.\n" 

162 f" first: {_render_constraints(expected_constraints, actual_constraints)}\n" 

163 f" second: {_render_constraints(actual_constraints, expected_constraints)}\n" 

164 ) 

165 return cls.with_detail(detail) 

166 

167 

168class _WrappedBaseException(Exception): 

169 """Used internally for wrapping BaseExceptions as components of FlakyFailure.""" 

170 

171 

172class FlakyFailure(ExceptionGroup, Flaky): 

173 """ 

174 This function appears to fail non-deterministically: We have seen it 

175 fail when passed this value at least once, but a subsequent invocation 

176 did not fail, or caused a distinct error. 

177 

178 Common causes for this problem are: 

179 1. The function depends on external state. e.g. it uses an external 

180 random number generator. Try to make a version that passes all the 

181 relevant state in from Hypothesis. 

182 2. The function is suffering from too much recursion and its failure 

183 depends sensitively on where it's been called from. 

184 3. The function is timing sensitive and can fail or pass depending on 

185 how long it takes. Try breaking it up into smaller functions which 

186 don't do that and testing those instead. 

187 

188 .. seealso:: 

189 

190 See also the :doc:`flaky failures tutorial </tutorial/flaky>`. 

191 """ 

192 

193 def __new__(cls, msg: str, group: Iterable[BaseException]) -> Self: 

194 # The Exception mixin forces this an ExceptionGroup (only accepting 

195 # Exceptions, not BaseException). Usually BaseException is raised 

196 # directly and will hence not be part of a FlakyFailure, but I'm not 

197 # sure this assumption holds everywhere. So wrap any BaseExceptions. 

198 group = list(group) 

199 for i, exc in enumerate(group): 

200 if not isinstance(exc, Exception): 

201 err = _WrappedBaseException() 

202 err.__cause__ = err.__context__ = exc 

203 group[i] = err 

204 return ExceptionGroup.__new__(cls, msg, group) # type: ignore[type-var] 

205 

206 # defining `derive` is required for `split` to return an instance of FlakyFailure 

207 # instead of ExceptionGroup. See https://github.com/python/cpython/issues/119287 

208 # and https://docs.python.org/3/library/exceptions.html#BaseExceptionGroup.derive 

209 def derive(self, excs: Sequence[Exception]) -> Self: # type: ignore[override] 

210 return type(self)(self.message, excs) 

211 

212 

213class FlakyBackendFailure(FlakyFailure): 

214 """ 

215 A failure was reported by an |alternative backend|, 

216 but this failure did not reproduce when replayed under the Hypothesis backend. 

217 

218 When an alternative backend reports a failure, Hypothesis first replays it 

219 under the standard Hypothesis backend to check for flakiness. If the failure 

220 does not reproduce, Hypothesis raises this exception. 

221 """ 

222 

223 

224class InvalidArgument(_Trimmable, TypeError): 

225 """Used to indicate that the arguments to a Hypothesis function were in 

226 some manner incorrect.""" 

227 

228 

229class ResolutionFailed(InvalidArgument): 

230 """Hypothesis had to resolve a type to a strategy, but this failed. 

231 

232 Type inference is best-effort, so this only happens when an 

233 annotation exists but could not be resolved for a required argument 

234 to the target of ``builds()``, or where the user passed ``...``. 

235 """ 

236 

237 

238class InvalidState(HypothesisException): 

239 """The system is not in a state where you were allowed to do that.""" 

240 

241 

242class InvalidDefinition(_Trimmable, TypeError): 

243 """Used to indicate that a class definition was not well put together and 

244 has something wrong with it.""" 

245 

246 

247class HypothesisWarning(HypothesisException, Warning): 

248 """A generic warning issued by Hypothesis.""" 

249 

250 

251class FailedHealthCheck(_Trimmable): 

252 """Raised when a test fails a health check. See |HealthCheck|.""" 

253 

254 

255class NonInteractiveExampleWarning(HypothesisWarning): 

256 """ 

257 Emitted when |.example| is used outside of interactive use. 

258 

259 |.example| is intended for exploratory and interactive work, not to be run as 

260 part of a test suite. 

261 """ 

262 

263 

264class HypothesisDeprecationWarning(HypothesisWarning, FutureWarning): 

265 """A deprecation warning issued by Hypothesis. 

266 

267 Actually inherits from FutureWarning, because DeprecationWarning is 

268 hidden by the default warnings filter. 

269 

270 You can configure the :mod:`python:warnings` module to handle these 

271 warnings differently to others, either turning them into errors or 

272 suppressing them entirely. Obviously we would prefer the former! 

273 """ 

274 

275 

276class HypothesisSideeffectWarning(HypothesisWarning): 

277 """A warning issued by Hypothesis when it sees actions that are 

278 discouraged at import or initialization time because they are 

279 slow or have user-visible side effects. 

280 """ 

281 

282 

283class Frozen(HypothesisException): 

284 """Raised when a mutation method has been called on a ConjectureData object 

285 after freeze() has been called.""" 

286 

287 

288def __getattr__(name: str) -> Any: 

289 if name == "MultipleFailures": 

290 from hypothesis.utils.deprecation import note_deprecation 

291 

292 note_deprecation( 

293 "MultipleFailures is deprecated; use the builtin `BaseExceptionGroup` type instead", 

294 since="2022-08-02", 

295 has_codemod=False, # This would be a great PR though! 

296 stacklevel=1, 

297 ) 

298 return BaseExceptionGroup 

299 

300 raise AttributeError(f"Module 'hypothesis.errors' has no attribute {name}") 

301 

302 

303class DeadlineExceeded(_Trimmable): 

304 """ 

305 Raised when an input takes too long to run, relative to the |settings.deadline| 

306 setting. 

307 """ 

308 

309 runtime: timedelta 

310 deadline: timedelta 

311 

312 def __init__(self, runtime: timedelta, deadline: timedelta) -> None: 

313 super().__init__( 

314 f"Test took {runtime.total_seconds() * 1000:.2f}ms, which exceeds " 

315 f"the deadline of {deadline.total_seconds() * 1000:.2f}ms. If you " 

316 "expect test cases to take this long, you can use @settings(deadline=...) " 

317 "to either set a higher deadline, or to disable it with deadline=None." 

318 ) 

319 self.runtime = runtime 

320 self.deadline = deadline 

321 

322 def __reduce__(self) -> tuple[type["Self"], tuple[timedelta, timedelta]]: 

323 return (type(self), (self.runtime, self.deadline)) 

324 

325 

326class StopTest(BaseException): 

327 """Raised when a test should stop running and return control to 

328 the Hypothesis engine, which should then continue normally. 

329 """ 

330 

331 testcounter: int 

332 

333 def __init__(self, testcounter: int) -> None: 

334 super().__init__(repr(testcounter)) 

335 self.testcounter = testcounter 

336 

337 

338class DidNotReproduce(HypothesisException): 

339 pass 

340 

341 

342class Found(HypothesisException): 

343 """Signal that the example matches condition. Internal use only.""" 

344 

345 

346class RewindRecursive(Exception): 

347 """Signal that the type inference should be rewound due to recursive types. Internal use only.""" 

348 

349 target: object 

350 

351 def __init__(self, target: object) -> None: 

352 self.target = target 

353 

354 

355class SmallSearchSpaceWarning(HypothesisWarning): 

356 """Indicates that an inferred strategy does not span the search space 

357 in a meaningful way, for example by only creating default instances.""" 

358 

359 

360class NonRoundTrippableCharactersWarning(HypothesisWarning): 

361 """Issued when the ``codec`` argument to 

362 :func:`~hypothesis.strategies.characters` allows generating characters 

363 which encode successfully, but do not decode back to the same character. 

364 

365 Pass each such character in either ``include_characters`` or 

366 ``exclude_characters`` to silence this warning. 

367 """ 

368 

369 

370CannotProceedScopeT = Literal["verified", "exhausted", "discard_test_case", "other"] 

371_valid_cannot_proceed_scopes = CannotProceedScopeT.__args__ # type: ignore 

372 

373 

374class BackendCannotProceed(HypothesisException): 

375 """ 

376 Raised by alternative backends when a |PrimitiveProvider| cannot proceed. 

377 This is expected to occur inside one of the ``.draw_*()`` methods, or for 

378 symbolic execution perhaps in |PrimitiveProvider.realize|. 

379 

380 The optional ``scope`` argument can enable smarter integration: 

381 

382 verified: 

383 Do not request further |test cases| from this backend. We *may* 

384 generate more test cases with other backends; if one fails then 

385 Hypothesis will report unsound verification in the backend too. 

386 

387 exhausted: 

388 Do not request further test cases from this backend; finish testing 

389 with test cases generated with the default backend. Common if e.g. 

390 native code blocks symbolic reasoning very early. 

391 

392 discard_test_case: 

393 This particular test case could not be converted to concrete values; 

394 skip any further processing and continue with another test case from 

395 this backend. 

396 """ 

397 

398 scope: CannotProceedScopeT 

399 

400 def __init__(self, scope: CannotProceedScopeT = "other", /) -> None: 

401 if scope not in _valid_cannot_proceed_scopes: 

402 raise InvalidArgument( 

403 f"Got scope={scope}, but expected one of " 

404 f"{_valid_cannot_proceed_scopes!r}" 

405 ) 

406 self.scope = scope