From d1d7245636e8023136c00bef688db61485c3256a Mon Sep 17 00:00:00 2001 From: boulea7 Date: Mon, 26 Oct 2026 21:59:20 +0800 Subject: [PATCH 1/3] TST: cover reflected operators with arrays --- ...est_operators_and_elementwise_functions.py | 91 ++++++++++++++++--- 1 file changed, 76 insertions(+), 15 deletions(-) diff --git a/array_api_tests/test_operators_and_elementwise_functions.py b/array_api_tests/test_operators_and_elementwise_functions.py index 89480a90..cf73fc35 100644 --- a/array_api_tests/test_operators_and_elementwise_functions.py +++ b/array_api_tests/test_operators_and_elementwise_functions.py @@ -2104,22 +2104,24 @@ def test_subtract(ctx, data): raise +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 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 method, func_name, op, dtypes in reflected_operator_cases: for dtype in dtypes: if isinstance(dtype, xp._UndefinedStub): continue @@ -2165,6 +2167,65 @@ def test_reflected_scalar_operator(method, func_name, op, dtype, data): 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 + ], +) +@pytest.mark.parametrize( + "left_shape, right_shape", + [ + pytest.param((), (), id="0d"), + pytest.param((), (2,), id="0d-left"), + pytest.param((2,), (), id="0d-right"), + pytest.param((2,), (2,), id="same-shape"), + pytest.param((2, 1), (1, 3), id="broadcast"), + ], +) +@given(data=st.data()) +def test_reflected_array_operator(method, func_name, dtypes, left_shape, right_shape, data): + dtype = data.draw( + st.sampled_from([d for d in dtypes if not isinstance(d, xp._UndefinedStub)]), + label="dtype", + ) + # Small positive values avoid division by zero, invalid powers, and overflow. + if dtype == xp.bool: + elements = st.booleans() + elif dtype in dh.complex_dtypes: + elements = st.builds(complex, st.integers(1, 3), st.integers(1, 3)) + else: + elements = st.integers(1, 3).map(dh.get_scalar_type(dtype)) + left_elements = elements + if func_name == "subtract" and dtype in dh.uint_dtypes: + left_elements = st.integers(3, 7) + x1 = data.draw( + hh.arrays_no_scalars(dtype=dtype, shape=left_shape, elements=left_elements), + label="x1", + ) + x2 = data.draw( + hh.arrays_no_scalars(dtype=dtype, shape=right_shape, elements=elements), + label="x2", + ) + 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) + ph.assert_array_elements(method, out=out, expected=expected) + except Exception as exc: + ph.add_note(exc, repro_snippet) + raise + + @given(hh.arrays(dtype=hh.all_floating_dtypes(), shape=hh.shapes())) def test_tan(x): repro_snippet = ph.format_snippet(f"xp.tan({x!r})") From be9876885a706545e15c26def69ba4a0fe2baa12 Mon Sep 17 00:00:00 2001 From: Boulea7 <145515129+Boulea7@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:47:46 +0800 Subject: [PATCH 2/3] TST: use shared input strategies for reflected operators --- array_api_tests/hypothesis_helpers.py | 9 +- ...est_operators_and_elementwise_functions.py | 96 +++++++------------ meta_tests/test_hypothesis_helpers.py | 11 +++ 3 files changed, 50 insertions(+), 66 deletions(-) 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 cf73fc35..ae403222 100644 --- a/array_api_tests/test_operators_and_elementwise_functions.py +++ b/array_api_tests/test_operators_and_elementwise_functions.py @@ -2120,48 +2120,41 @@ def test_subtract(ctx, data): ) -def make_reflected_scalar_params(): - for method, func_name, op, dtypes in reflected_operator_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]}", - ) +def assert_reflected_values(method, out, expected): + if out.dtype in dh.all_float_dtypes: + # Scalar and array kernels can round floating-point results differently. + 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 @@ -2174,40 +2167,15 @@ def test_reflected_scalar_operator(method, func_name, op, dtype, data): for method, func_name, _, dtypes in reflected_operator_cases ], ) -@pytest.mark.parametrize( - "left_shape, right_shape", - [ - pytest.param((), (), id="0d"), - pytest.param((), (2,), id="0d-left"), - pytest.param((2,), (), id="0d-right"), - pytest.param((2,), (2,), id="same-shape"), - pytest.param((2, 1), (1, 3), id="broadcast"), - ], -) -@given(data=st.data()) -def test_reflected_array_operator(method, func_name, dtypes, left_shape, right_shape, data): - dtype = data.draw( - st.sampled_from([d for d in dtypes if not isinstance(d, xp._UndefinedStub)]), - label="dtype", - ) - # Small positive values avoid division by zero, invalid powers, and overflow. - if dtype == xp.bool: - elements = st.booleans() - elif dtype in dh.complex_dtypes: - elements = st.builds(complex, st.integers(1, 3), st.integers(1, 3)) - else: - elements = st.integers(1, 3).map(dh.get_scalar_type(dtype)) - left_elements = elements +@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: - left_elements = st.integers(3, 7) - x1 = data.draw( - hh.arrays_no_scalars(dtype=dtype, shape=left_shape, elements=left_elements), - label="x1", - ) - x2 = data.draw( - hh.arrays_no_scalars(dtype=dtype, shape=right_shape, elements=elements), - label="x2", - ) + 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)" @@ -2220,7 +2188,7 @@ def test_reflected_array_operator(method, func_name, dtypes, left_shape, right_s 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) - 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 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()) From 81d0ceb614d55f85cf22750d09b434909880c6c3 Mon Sep 17 00:00:00 2001 From: Boulea7 <145515129+Boulea7@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:53:43 +0800 Subject: [PATCH 3/3] TST: keep exact comparisons for reflected subtraction --- array_api_tests/test_operators_and_elementwise_functions.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/array_api_tests/test_operators_and_elementwise_functions.py b/array_api_tests/test_operators_and_elementwise_functions.py index ae403222..99a56f48 100644 --- a/array_api_tests/test_operators_and_elementwise_functions.py +++ b/array_api_tests/test_operators_and_elementwise_functions.py @@ -2121,8 +2121,9 @@ def test_subtract(ctx, data): def assert_reflected_values(method, out, expected): - if out.dtype in dh.all_float_dtypes: - # Scalar and array kernels can round floating-point results differently. + 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)