| 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 |
|
| 11 |
import pytest |
| 12 |
|
| 13 |
from hypothesis import given, settings, strategies as st |
| 14 |
from hypothesis.internal.compat import ExceptionGroup |
| 15 |
|
| 16 |
from tests.common.utils import flaky |
| 17 |
|
| 18 |
|
| 19 |
def go_wrong_naive(a, b): |
| 20 |
try: |
| 21 |
assert a + b < 100 |
| 22 |
a / b |
| 23 |
except Exception: |
| 24 |
# Hiding the actual problem is terrible, but this pattern can make sense |
| 25 |
# if you're raising a library-specific or semantically meaningful error. |
| 26 |
raise ValueError("Something went wrong") # noqa |
| 27 |
|
| 28 |
|
| 29 |
def go_wrong_with_cause(a, b): |
| 30 |
try: |
| 31 |
assert a + b < 100 |
| 32 |
a / b |
| 33 |
except Exception as err: |
| 34 |
# Explicit chaining is the *right way* to change exception type. |
| 35 |
raise ValueError("Something went wrong") from err |
| 36 |
|
| 37 |
|
| 38 |
def go_wrong_coverup(a, b): |
| 39 |
try: |
| 40 |
assert a + b < 100 |
| 41 |
a / b |
| 42 |
except Exception: |
| 43 |
# This pattern SHOULD be local enough that it never distinguishes |
| 44 |
# errors in practice... but if it does, we're ready. |
| 45 |
raise ValueError("Something went wrong") from None |
| 46 |
|
| 47 |
|
| 48 |
@pytest.mark.parametrize( |
| 49 |
"function", |
| 50 |
[go_wrong_naive, go_wrong_with_cause, go_wrong_coverup], |
| 51 |
ids=lambda f: f.__name__, |
| 52 |
) |
| 53 |
@flaky(max_runs=3, min_passes=1) |
| 54 |
def test_can_generate_specified_version(function): |
| 55 |
@given(st.integers(), st.integers()) |
| 56 |
@settings(database=None, report_multiple_bugs=True) |
| 57 |
def test_fn(x, y): |
| 58 |
# Indirection to fix https://github.com/HypothesisWorks/hypothesis/issues/2888 |
| 59 |
return function(x, y) |
| 60 |
|
| 61 |
with pytest.raises(ExceptionGroup): |
| 62 |
test_fn() |