diff --git a/array_api_tests/hypothesis_helpers.py b/array_api_tests/hypothesis_helpers.py index 185aea93..4f038fc5 100644 --- a/array_api_tests/hypothesis_helpers.py +++ b/array_api_tests/hypothesis_helpers.py @@ -605,11 +605,16 @@ def array_and_py_scalar(draw, dtypes, **kwds): scalar_strategy = sampled_from([xp.int32, dtype]) else: scalar_strategy = just(dtype) - scalar_var = draw(scalars(scalar_strategy, finite=True, **kwds)) + bounds = {key: kwds[key] for key in ("min_value", "max_value") if key in kwds} + if dtype in dh.complex_dtypes and bounds: + # For complex inputs the bounds apply to each component, as in arrays(). + scalar_var = draw(from_dtype(dtype, allow_nan=False, allow_infinity=False, **kwds)) + else: + scalar_var = draw(scalars(scalar_strategy, finite=True, **kwds)) # draw the array. # XXX artificially limit the range of values for floats, otherwise value testing is flaky - elements={} + elements = bounds if dtype in dh.real_float_dtypes: elements = { 'allow_nan': False, diff --git a/array_api_tests/test_operators_and_elementwise_functions.py b/array_api_tests/test_operators_and_elementwise_functions.py index 89480a90..99a56f48 100644 --- a/array_api_tests/test_operators_and_elementwise_functions.py +++ b/array_api_tests/test_operators_and_elementwise_functions.py @@ -2104,62 +2104,92 @@ def test_subtract(ctx, data): raise -def make_reflected_scalar_params(): - cases = ( - ("__radd__", "add", operator.add, dh.numeric_dtypes), - ("__rsub__", "subtract", operator.sub, dh.numeric_dtypes), - ("__rmul__", "multiply", operator.mul, dh.numeric_dtypes), - ("__rtruediv__", "divide", operator.truediv, dh.all_float_dtypes), - ("__rfloordiv__", "floor_divide", operator.floordiv, dh.real_dtypes), - ("__rpow__", "pow", operator.pow, dh.numeric_dtypes), - ("__rmod__", "remainder", operator.mod, dh.real_dtypes), - ("__rand__", "bitwise_and", operator.and_, dh.bool_and_all_int_dtypes), - ("__ror__", "bitwise_or", operator.or_, dh.bool_and_all_int_dtypes), - ("__rxor__", "bitwise_xor", operator.xor, dh.bool_and_all_int_dtypes), - ("__rlshift__", "bitwise_left_shift", operator.lshift, dh.all_int_dtypes), - ("__rrshift__", "bitwise_right_shift", operator.rshift, dh.all_int_dtypes), - ) - for method, func_name, op, dtypes in cases: - for dtype in dtypes: - if isinstance(dtype, xp._UndefinedStub): - continue - yield pytest.param( - method, func_name, op, dtype, - id=f"{method}-{dh.dtype_to_name[dtype]}", - ) +reflected_operator_cases = ( + ("__radd__", "add", operator.add, dh.numeric_dtypes), + ("__rsub__", "subtract", operator.sub, dh.numeric_dtypes), + ("__rmul__", "multiply", operator.mul, dh.numeric_dtypes), + ("__rtruediv__", "divide", operator.truediv, dh.all_float_dtypes), + ("__rfloordiv__", "floor_divide", operator.floordiv, dh.real_dtypes), + ("__rpow__", "pow", operator.pow, dh.numeric_dtypes), + ("__rmod__", "remainder", operator.mod, dh.real_dtypes), + ("__rand__", "bitwise_and", operator.and_, dh.bool_and_all_int_dtypes), + ("__ror__", "bitwise_or", operator.or_, dh.bool_and_all_int_dtypes), + ("__rxor__", "bitwise_xor", operator.xor, dh.bool_and_all_int_dtypes), + ("__rlshift__", "bitwise_left_shift", operator.lshift, dh.all_int_dtypes), + ("__rrshift__", "bitwise_right_shift", operator.rshift, dh.all_int_dtypes), +) + + +def assert_reflected_values(method, out, expected): + if method == "__rtruediv__" or (method == "__rmul__" and out.dtype in dh.complex_dtypes): + # Division may multiply by a reciprocal, and complex multiplication may + # fuse operations in a different order when its operands are swapped. + ph.assert_shape(method, out_shape=out.shape, expected=expected.shape) + tol = 8 * xp.finfo(out.dtype).eps + error = xp.abs(out - expected) + assert xp.all(error <= (xp.abs(expected) + 1) * tol), ( + f"{out=}, but should be close to {expected} [{method}()]" + ) + else: + ph.assert_array_elements(method, out=out, expected=expected) -# XXX: this test is parametrized over lists of dtypes not dtype strategies. -# Therefore adding `--max-examples` to the test run does not improve coverage. @pytest.mark.parametrize( - "method, func_name, op, dtype", list(make_reflected_scalar_params()) + "method, func_name, op, dtypes", + [pytest.param(*case, id=case[0]) for case in reflected_operator_cases], ) @given(data=st.data()) -def test_reflected_scalar_operator(method, func_name, op, dtype, data): - # Small positive values avoid division by zero, invalid powers, and overflow. - if dtype == xp.bool: - elements = st.booleans() - else: - elements = st.integers(1, 3).map(dh.get_scalar_type(dtype)) - scalar_strategy = elements - if func_name == "subtract" and dtype in dh.uint_dtypes: - scalar_strategy = st.integers(3, 7) - scalar = data.draw(scalar_strategy, label="scalar") - x = data.draw( - hh.arrays( - dtype=dtype, shape=hh.shapes(min_dims=1, min_side=1), elements=elements - ), - label="x", +def test_reflected_scalar_operator(method, func_name, op, dtypes, data): + scalar, x = data.draw( + hh.array_and_py_scalar(dtypes, min_value=1, max_value=3), label="operands" ) + if not dh.is_scalar(scalar): + scalar, x = x, scalar + if func_name == "subtract" and x.dtype in dh.uint_dtypes: + assume(xp.all(x <= scalar)) # unsigned underflow is unspecified op_sym = dh.binary_op_to_symbol[func_to_op[func_name]] repro_snippet = ph.format_snippet(f"{scalar!r} {op_sym} {x!r} # {method}") try: out = op(scalar, x) - expected = getattr(xp, func_name)(xp.asarray(scalar, dtype=dtype), x) + expected = getattr(xp, func_name)(xp.asarray(scalar, dtype=x.dtype), x) - ph.assert_dtype(method, in_dtype=dtype, out_dtype=out.dtype) + ph.assert_dtype(method, in_dtype=x.dtype, out_dtype=out.dtype) ph.assert_result_shape(method, in_shapes=[x.shape], out_shape=out.shape) - ph.assert_array_elements(method, out=out, expected=expected) + assert_reflected_values(method, out, expected) + except Exception as exc: + ph.add_note(exc, repro_snippet) + raise + + +@pytest.mark.parametrize( + "method, func_name, dtypes", + [ + pytest.param(method, func_name, dtypes, id=method) + for method, func_name, _, dtypes in reflected_operator_cases + ], +) +@given(dtype=hh.all_dtypes, shapes=hh.two_mutually_broadcastable_shapes, data=st.data()) +def test_reflected_array_operator(method, func_name, dtypes, dtype, shapes, data): + assume(dtype in dtypes) + # Keep powers and shifts in range, and divisors nonzero. + elements = {"min_value": 1, "max_value": 3} + x1 = data.draw(hh.arrays(dtype, shape=shapes[0], elements=elements), label="x1") + x2 = data.draw(hh.arrays(dtype, shape=shapes[1], elements=elements), label="x2") + if func_name == "subtract" and dtype in dh.uint_dtypes: + assume(xp.all(x1 >= x2)) # unsigned underflow is unspecified + op_name = func_to_op[func_name] + repro_snippet = ph.format_snippet( + f"x1 = {x1!r}\nx2 = {x2!r}\nx2.{method}(x1) # x1.{op_name}(x2)" + ) + try: + expected = getattr(x1, op_name)(x2) + out = getattr(x2, method)(x1) + + ph.assert_dtype( + method, in_dtype=dtype, out_dtype=out.dtype, expected=expected.dtype + ) + ph.assert_result_shape(method, in_shapes=[x1.shape, x2.shape], out_shape=out.shape) + assert_reflected_values(method, out, expected) except Exception as exc: ph.add_note(exc, repro_snippet) raise diff --git a/meta_tests/test_hypothesis_helpers.py b/meta_tests/test_hypothesis_helpers.py index b14b728c..3dc35b02 100644 --- a/meta_tests/test_hypothesis_helpers.py +++ b/meta_tests/test_hypothesis_helpers.py @@ -72,6 +72,17 @@ def test_two_mutual_arrays(x1, x2): assert (x1.dtype, x2.dtype) in dh.promotion_table.keys() +@pytest.mark.parametrize("dtype", dh.uint_dtypes + dh.complex_dtypes) +@given(data=st.data()) +def test_array_and_py_scalar_bounds(dtype, data): + x, scalar = data.draw(hh.array_and_py_scalar([dtype], min_value=2, max_value=2), label="pair") + if dh.is_scalar(x): + x, scalar = scalar, x + expected = 2 + 2j if dtype in dh.complex_dtypes else 2 + assert scalar == expected + assert xp.all(x == expected) + + def test_two_mutual_arrays_raises_on_bad_dtypes(): with pytest.raises(TypeError): hh.two_mutual_arrays(dtypes=xps.scalar_dtypes())