| 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 |
"""Checks that @given, @mock.patch, and pytest fixtures work as expected.""" |
| 12 |
|
| 13 |
|
| 14 |
import math |
| 15 |
from unittest import mock |
| 16 |
|
| 17 |
try: |
| 18 |
from pytest import Config |
| 19 |
except ImportError: # pytest<7.0.0 |
| 20 |
from _pytest.config import Config |
| 21 |
|
| 22 |
from hypothesis import given, strategies as st |
| 23 |
|
| 24 |
from tests.common.utils import skipif_threading |
| 25 |
|
| 26 |
|
| 27 |
@given(thing=st.text()) |
| 28 |
@mock.patch("math.atan") |
| 29 |
# mock.patch is thread-unsafe. pytest-run-parallel normally detects this and skips |
| 30 |
# the test, but because we set it inside of @given it can't (or doesn't?) peek |
| 31 |
# inside the AST, resulting in a false negative. |
| 32 |
@skipif_threading |
| 33 |
def test_can_mock_inside_given_without_fixture(atan, thing): |
| 34 |
assert isinstance(atan, mock.MagicMock) |
| 35 |
assert isinstance(math.atan, mock.MagicMock) |
| 36 |
|
| 37 |
|
| 38 |
@mock.patch("math.atan") |
| 39 |
@given(thing=st.text()) |
| 40 |
def test_can_mock_outside_given_with_fixture(atan, pytestconfig, thing): |
| 41 |
assert isinstance(atan, mock.MagicMock) |
| 42 |
assert isinstance(math.atan, mock.MagicMock) |
| 43 |
assert isinstance(pytestconfig, Config) |
| 44 |
|
| 45 |
|
| 46 |
@given(thing=st.text()) |
| 47 |
def test_can_mock_within_test_with_fixture(pytestconfig, thing): |
| 48 |
assert isinstance(pytestconfig, Config) |
| 49 |
assert not isinstance(math.atan, mock.MagicMock) |
| 50 |
with mock.patch("math.atan") as atan: |
| 51 |
assert isinstance(atan, mock.MagicMock) |
| 52 |
assert isinstance(math.atan, mock.MagicMock) |
| 53 |
assert not isinstance(math.atan, mock.MagicMock) |