Testing for non-strict inequality with np.testing

Viewed 88

np.testing.assert_array_less() tests for strict inequality:

In [1]: np.testing.assert_array_less(1., 1.)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-1-ea8ee0b762c3> in <module>()
----> 1 np.testing.assert_array_less(1., 1.)

AssertionError: 
Arrays are not less-ordered

apparently there is no parameter to test for non-strict inequality.

How would one test this by still relying on np.testing for its interpretable error messages? (I'd like to avoid assert (a <= b).all())

1 Answers

As you note, apparently non-strict inequality is not among the defined test cases in numpy.testing. Also, there is no documented way to extend numpy.testing with more test cases.

Looking at the source, it is clear that it is possible to roll your own test cases, using assert_array_compare:

import operator

def assert_array_less_equal(x, y, err_msg='', verbose=True):
    from numpy.testing import assert_array_compare
    __tracebackhide__ = True  # Hide traceback for py.test
    assert_array_compare(operator.__le__, x, y, err_msg=err_msg,
                         verbose=verbose,
                         header='Arrays are not equal or less-ordered')

>>> assert_array_less_equal(1., 1.)
>>> assert_array_less_equal(1.1, 1.)
.
.
.
AssertionError: 
Arrays are not equal or less-ordered

(mismatch 100.0%)
 x: array(1.1)
 y: array(1.)

However, as stated, assert_array_compare is not documented, but rather a helper function within numpy.testing. Therefore I guess it can be subject to changes and updates without any notification when numpy is updated. This could potentially, silently break your code.

Related