| 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 functools |
| 12 |
import warnings |
| 13 |
from copy import copy |
| 14 |
from types import SimpleNamespace |
| 15 |
|
| 16 |
import pytest |
| 17 |
|
| 18 |
from hypothesis import given, strategies as st |
| 19 |
from hypothesis.errors import HypothesisWarning, InvalidArgument |
| 20 |
from hypothesis.extra.array_api import ( |
| 21 |
COMPLEX_NAMES, |
| 22 |
DTYPE_NAMES, |
| 23 |
FLOAT_NAMES, |
| 24 |
INT_NAMES, |
| 25 |
UINT_NAMES, |
| 26 |
make_strategies_namespace, |
| 27 |
mock_xp, |
| 28 |
) |
| 29 |
|
| 30 |
from tests.common.debug import check_can_generate_examples |
| 31 |
|
| 32 |
MOCK_WARN_MSG = f"determine.*{mock_xp.__name__}.*Array API" |
| 33 |
|
| 34 |
|
| 35 |
class MockedArray: |
| 36 |
def __init__(self, wrapped, *, exclude=()): |
| 37 |
self.wrapped = wrapped |
| 38 |
self.exclude = exclude |
| 39 |
|
| 40 |
def __getattr__(self, name): |
| 41 |
if name in self.exclude: |
| 42 |
raise AttributeError(f"removed on the mock: {name}") |
| 43 |
|
| 44 |
return object.__getattr__(self, name) |
| 45 |
|
| 46 |
|
| 47 |
def wrap_array(func: callable, exclude: tuple[str, ...] = ()) -> callable: |
| 48 |
@functools.wraps(func) |
| 49 |
def wrapped(*args, **kwargs): |
| 50 |
result = func(*args, **kwargs) |
| 51 |
|
| 52 |
if isinstance(result, tuple): |
| 53 |
return tuple(MockedArray(arr, exclude=exclude) for arr in result) |
| 54 |
|
| 55 |
return MockedArray(result, exclude=exclude) |
| 56 |
|
| 57 |
return wrapped |
| 58 |
|
| 59 |
|
| 60 |
def make_mock_xp( |
| 61 |
*, exclude: tuple[str, ...] = (), exclude_methods: tuple[str, ...] = () |
| 62 |
) -> SimpleNamespace: |
| 63 |
xp = copy(mock_xp) |
| 64 |
assert isinstance(exclude, tuple) # sanity check |
| 65 |
assert isinstance(exclude_methods, tuple) # sanity check |
| 66 |
for attr in exclude: |
| 67 |
delattr(xp, attr) |
| 68 |
|
| 69 |
array_returning_funcs = ( |
| 70 |
"astype", |
| 71 |
"broadcast_arrays", |
| 72 |
"arange", |
| 73 |
"asarray", |
| 74 |
"empty", |
| 75 |
"zeros", |
| 76 |
"ones", |
| 77 |
"reshape", |
| 78 |
"isnan", |
| 79 |
"isfinite", |
| 80 |
"logical_or", |
| 81 |
"sum", |
| 82 |
"nonzero", |
| 83 |
"sort", |
| 84 |
"unique_values", |
| 85 |
"any", |
| 86 |
"all", |
| 87 |
) |
| 88 |
|
| 89 |
for name in array_returning_funcs: |
| 90 |
func = getattr(xp, name, None) |
| 91 |
if func is None: |
| 92 |
# removed in the step before |
| 93 |
continue |
| 94 |
setattr(xp, name, wrap_array(func, exclude=exclude_methods)) |
| 95 |
|
| 96 |
return xp |
| 97 |
|
| 98 |
|
| 99 |
def test_warning_on_noncompliant_xp(): |
| 100 |
"""Using non-compliant array modules raises helpful warning""" |
| 101 |
xp = make_mock_xp(exclude_methods=("__array_namespace__",)) |
| 102 |
with pytest.warns(HypothesisWarning, match=MOCK_WARN_MSG): |
| 103 |
make_strategies_namespace(xp, api_version="draft") |
| 104 |
|
| 105 |
|
| 106 |
@pytest.mark.filterwarnings(f"ignore:.*{MOCK_WARN_MSG}.*") |
| 107 |
@pytest.mark.parametrize( |
| 108 |
"stratname, args, attr", |
| 109 |
[("from_dtype", ["int8"], "iinfo"), ("arrays", ["int8", 5], "asarray")], |
| 110 |
) |
| 111 |
def test_error_on_missing_attr(stratname, args, attr): |
| 112 |
"""Strategies raise helpful error when using array modules that lack |
| 113 |
required attributes.""" |
| 114 |
xp = make_mock_xp(exclude=(attr,)) |
| 115 |
xps = make_strategies_namespace(xp, api_version="draft") |
| 116 |
func = getattr(xps, stratname) |
| 117 |
with pytest.raises(InvalidArgument, match=f"{mock_xp.__name__}.*required.*{attr}"): |
| 118 |
check_can_generate_examples(func(*args)) |
| 119 |
|
| 120 |
|
| 121 |
dtypeless_xp = make_mock_xp(exclude=tuple(DTYPE_NAMES)) |
| 122 |
with warnings.catch_warnings(): |
| 123 |
warnings.filterwarnings("ignore", category=HypothesisWarning) |
| 124 |
dtypeless_xps = make_strategies_namespace(dtypeless_xp, api_version="draft") |
| 125 |
|
| 126 |
|
| 127 |
@pytest.mark.parametrize( |
| 128 |
"stratname", |
| 129 |
[ |
| 130 |
"scalar_dtypes", |
| 131 |
"boolean_dtypes", |
| 132 |
"numeric_dtypes", |
| 133 |
"integer_dtypes", |
| 134 |
"unsigned_integer_dtypes", |
| 135 |
"floating_dtypes", |
| 136 |
"real_dtypes", |
| 137 |
"complex_dtypes", |
| 138 |
], |
| 139 |
) |
| 140 |
def test_error_on_missing_dtypes(stratname): |
| 141 |
"""Strategies raise helpful error when using array modules that lack |
| 142 |
required dtypes.""" |
| 143 |
func = getattr(dtypeless_xps, stratname) |
| 144 |
with pytest.raises(InvalidArgument, match=f"{mock_xp.__name__}.*dtype.*namespace"): |
| 145 |
check_can_generate_examples(func()) |
| 146 |
|
| 147 |
|
| 148 |
@pytest.mark.filterwarnings(f"ignore:.*{MOCK_WARN_MSG}.*") |
| 149 |
@pytest.mark.parametrize( |
| 150 |
"stratname, keep_anys", |
| 151 |
[ |
| 152 |
("scalar_dtypes", [INT_NAMES, UINT_NAMES, FLOAT_NAMES]), |
| 153 |
("numeric_dtypes", [INT_NAMES, UINT_NAMES, FLOAT_NAMES, COMPLEX_NAMES]), |
| 154 |
("integer_dtypes", [INT_NAMES]), |
| 155 |
("unsigned_integer_dtypes", [UINT_NAMES]), |
| 156 |
("floating_dtypes", [FLOAT_NAMES]), |
| 157 |
("real_dtypes", [INT_NAMES, UINT_NAMES, FLOAT_NAMES]), |
| 158 |
("complex_dtypes", [COMPLEX_NAMES]), |
| 159 |
], |
| 160 |
) |
| 161 |
@given(st.data()) |
| 162 |
def test_warning_on_partial_dtypes(stratname, keep_anys, data): |
| 163 |
"""Strategies using array modules with at least one of a dtype in the |
| 164 |
necessary category/categories execute with a warning.""" |
| 165 |
exclude = [] |
| 166 |
for keep_any in keep_anys: |
| 167 |
exclude.extend( |
| 168 |
data.draw( |
| 169 |
st.lists( |
| 170 |
st.sampled_from(keep_any), |
| 171 |
min_size=1, |
| 172 |
max_size=len(keep_any) - 1, |
| 173 |
unique=True, |
| 174 |
) |
| 175 |
) |
| 176 |
) |
| 177 |
xp = make_mock_xp(exclude=tuple(exclude)) |
| 178 |
xps = make_strategies_namespace(xp, api_version="draft") |
| 179 |
func = getattr(xps, stratname) |
| 180 |
with pytest.warns(HypothesisWarning, match=f"{mock_xp.__name__}.*dtype.*namespace"): |
| 181 |
data.draw(func()) |
| 182 |
|
| 183 |
|
| 184 |
def test_raises_on_inferring_with_no_dunder_version(): |
| 185 |
"""When xp has no __array_api_version__, inferring api_version raises |
| 186 |
helpful error.""" |
| 187 |
xp = make_mock_xp(exclude=("__array_api_version__",)) |
| 188 |
with pytest.raises(InvalidArgument, match="has no attribute"): |
| 189 |
make_strategies_namespace(xp) |
| 190 |
|
| 191 |
|
| 192 |
def test_raises_on_invalid_dunder_version(): |
| 193 |
"""When xp has invalid __array_api_version__, inferring api_version raises |
| 194 |
helpful error.""" |
| 195 |
xp = make_mock_xp() |
| 196 |
xp.__array_api_version__ = None |
| 197 |
with pytest.raises(InvalidArgument): |
| 198 |
make_strategies_namespace(xp) |