|
| 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 strategies as st |
| 14 | + |
| 15 | +from tests.common.debug import assert_simple_property, find_any |
| 16 | +from tests.common.utils import temp_registered |
| 17 | + |
| 18 | + |
| 19 | +def test_resolves_simple_typealias(): |
| 20 | + type MyInt = int |
| 21 | + type AliasedInt = MyInt |
| 22 | + type MaybeInt = int | None |
| 23 | + |
| 24 | + assert_simple_property(st.from_type(MyInt), lambda x: isinstance(x, int)) |
| 25 | + assert_simple_property(st.from_type(AliasedInt), lambda x: isinstance(x, int)) |
| 26 | + assert_simple_property( |
| 27 | + st.from_type(MaybeInt), lambda x: isinstance(x, int) or x is None |
| 28 | + ) |
| 29 | + |
| 30 | + find_any(st.from_type(MaybeInt), lambda x: isinstance(x, int)) |
| 31 | + find_any(st.from_type(MaybeInt), lambda x: x is None) |
| 32 | + |
| 33 | + |
| 34 | +def test_resolves_nested(): |
| 35 | + type Point1 = int |
| 36 | + type Point2 = Point1 |
| 37 | + type Point3 = Point2 |
| 38 | + |
| 39 | + assert_simple_property(st.from_type(Point3), lambda x: isinstance(x, int)) |
| 40 | + |
| 41 | + |
| 42 | +def test_mutually_recursive_fails(): |
| 43 | + # example from |
| 44 | + # https://docs.python.org/3/library/typing.html#typing.TypeAliasType.__value__ |
| 45 | + type A = B |
| 46 | + type B = A |
| 47 | + |
| 48 | + # I guess giving a nicer error here would be good, but detecting this in general |
| 49 | + # is...complicated. |
| 50 | + with pytest.raises(RecursionError): |
| 51 | + find_any(st.from_type(A)) |
| 52 | + |
| 53 | + |
| 54 | +def test_can_register_typealias(): |
| 55 | + type A = int |
| 56 | + st.register_type_strategy(A, st.just("a")) |
| 57 | + assert_simple_property(st.from_type(A), lambda x: x == "a") |
| 58 | + |
| 59 | + |
| 60 | +def test_prefers_manually_registered_typealias(): |
| 61 | + # manually registering a `type A = ...` should override automatic detection |
| 62 | + type A = int |
| 63 | + |
| 64 | + assert_simple_property(st.from_type(A), lambda x: isinstance(x, int)) |
| 65 | + |
| 66 | + with temp_registered(A, st.booleans()): |
| 67 | + assert_simple_property(st.from_type(A), lambda x: isinstance(x, bool)) |
0 commit comments