Class | suppress_warnings |
Context manager and decorator doing much the same as warnings.catch_warnings. |
Constant | HAS_REFCOUNT |
Undocumented |
Constant | IS_PYPY |
Undocumented |
Constant | IS_PYSTON |
Undocumented |
Variable | verbose |
Undocumented |
Class | _Dummy |
Undocumented |
Class | clear_and_catch_warnings |
Context manager that resets warning registry for catching warnings |
Class | IgnoreException |
Ignoring this exception due to disabled feature |
Class | KnownFailureException |
Raise this exception to mark a test as a known failing test. |
Function | _assert_no_gc_cycles_context |
Undocumented |
Function | _assert_no_warnings_context |
Undocumented |
Function | _assert_valid_refcount |
Check that ufuncs don't mishandle refcount of object 1 . Used in a few regression tests. |
Function | _assert_warns_context |
Undocumented |
Function | _gen_alignment_data |
generator producing data with different alignment and offsets to test simd vectorization |
Function | _get_mem_available |
Return available memory in bytes, or None if unknown. |
Function | _integer_repr |
Undocumented |
Function | _no_tracing |
Decorator to temporarily turn off tracing for the duration of a test. Needed in tests that check refcounting, otherwise the tracing itself influences the refcounts |
Function | _parse_size |
Convert memory size strings ('12 GB' etc.) to float |
Function | assert_ |
Assert that works in release mode. Accepts callable msg to allow deferring evaluation until failure. |
Function | assert_allclose |
Raises an AssertionError if two objects are not equal up to desired tolerance. |
Function | assert_almost_equal |
Raises an AssertionError if two items are not equal up to desired precision. |
Function | assert_approx_equal |
Raises an AssertionError if two items are not equal up to significant digits. |
Function | assert_array_almost_equal |
Raises an AssertionError if two objects are not equal up to desired precision. |
Function | assert_array_almost_equal_nulp |
Compare two arrays relatively to their spacing. |
Function | assert_array_compare |
Undocumented |
Function | assert_array_equal |
Raises an AssertionError if two array_like objects are not equal. |
Function | assert_array_less |
Raises an AssertionError if two array_like objects are not ordered by less than. |
Function | assert_array_max_ulp |
Check that all items of arrays differ in at most N Units in the Last Place. |
Function | assert_equal |
Raises an AssertionError if two objects are not equal. |
Function | assert_no_gc_cycles |
Fail if the given callable produces any reference cycles. |
Function | assert_no_warnings |
Fail if the given callable produces any warnings. |
Function | assert_raises |
assert_raises(exception_class, callable, *args, **kwargs) assert_raises(exception_class) |
Function | assert_raises_regex |
assert_raises_regex(exception_class, expected_regexp, callable, *args, **kwargs) assert_raises_regex(exception_class, expected_regexp) |
Function | assert_string_equal |
Test if two strings are equal. |
Function | assert_warns |
Fail unless the given callable throws the specified warning. |
Function | break_cycles |
No summary |
Function | build_err_msg |
Undocumented |
Function | check_free_memory |
Check whether free_bytes amount of memory is currently free. Returns: None if enough memory available, otherwise error message |
Function | decorate_methods |
Apply a decorator to all methods in a class matching a regular expression. |
Function | GetPerformanceAttributes |
Undocumented |
Function | gisfinite |
like isfinite, but always raise an error if type not supported instead of returning a TypeError object. |
Function | gisinf |
like isinf, but always raise an error if type not supported instead of returning a TypeError object. |
Function | gisnan |
like isnan, but always raise an error if type not supported instead of returning a TypeError object. |
Function | integer_repr |
Return the signed-magnitude interpretation of the binary representation of x. |
Function | jiffies |
Return number of jiffies elapsed. |
Function | measure |
Return elapsed time for executing code in the namespace of the caller. |
Function | memusage |
Undocumented |
Function | nulp_diff |
For each item in x and y, return the number of representable floating points between them. |
Function | print_assert_equal |
Test if two objects are equal, and print an error message if test fails. |
Function | raises |
Decorator to check for raised exceptions. |
Function | requires_memory |
Decorator to skip a test if not enough memory is available |
Function | rundocs |
Run doctests found in the given file. |
Function | runstring |
Undocumented |
Function | tempdir |
Context manager to provide a temporary test folder. |
Function | temppath |
Context manager for temporary files. |
Variable | _d |
Undocumented |
1
.
Used in a few regression tests.generator producing data with different alignment and offsets to test simd vectorization
if type is 'unary' yields one output, one input array and a message containing information on the data if type is 'binary' yields one output array, two input array and a message containing information on the data
Assert that works in release mode. Accepts callable msg to allow deferring evaluation until failure.
The Python built-in assert does not work when executing code in optimized mode (the -O flag) - no byte-code is generated for it.
For documentation on usage, refer to the Python documentation.
Raises an AssertionError if two objects are not equal up to desired tolerance.
The test is equivalent to allclose(actual, desired, rtol, atol) (note
that allclose has different default values). It compares the difference
between actual
and desired
to atol + rtol * abs(desired).
assert_array_almost_equal_nulp, assert_array_max_ulp
>>> x = [1e-5, 1e-3, 1e-1] >>> y = np.arccos(np.cos(x)) >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
Raises an AssertionError if two items are not equal up to desired precision.
Note
It is recommended to use one of assert_allclose
,
assert_array_almost_equal_nulp
or assert_array_max_ulp
instead of this function for more consistent floating point
comparisons.
The test verifies that the elements of actual
and desired
satisfy.
abs(desired-actual) < 1.5 * 10**(-decimal)
That is a looser test than originally documented, but agrees with what the
actual implementation in assert_array_almost_equal
did up to rounding
vagaries. An exception is raised at conflicting values. For ndarrays this
delegates to assert_array_almost_equal
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
>>> from numpy.testing import assert_almost_equal >>> assert_almost_equal(2.3333333333333, 2.33333334) >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 10 decimals ACTUAL: 2.3333333333333 DESIRED: 2.33333334
>>> assert_almost_equal(np.array([1.0,2.3333333333333]), ... np.array([1.0,2.33333334]), decimal=9) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 9 decimals <BLANKLINE> Mismatched elements: 1 / 2 (50%) Max absolute difference: 6.66669964e-09 Max relative difference: 2.85715698e-09 x: array([1. , 2.333333333]) y: array([1. , 2.33333334])
Raises an AssertionError if two items are not equal up to significant digits.
Note
It is recommended to use one of assert_allclose
,
assert_array_almost_equal_nulp
or assert_array_max_ulp
instead of this function for more consistent floating point
comparisons.
Given two numbers, check that they are approximately equal. Approximately equal is defined as the number of significant digits that agree.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20, ... significant=8) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20, ... significant=8) Traceback (most recent call last): ... AssertionError: Items are not equal to 8 significant digits: ACTUAL: 1.234567e-21 DESIRED: 1.2345672e-21
the evaluated condition that raises the exception is
>>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1) True
Raises an AssertionError if two objects are not equal up to desired precision.
Note
It is recommended to use one of assert_allclose
,
assert_array_almost_equal_nulp
or assert_array_max_ulp
instead of this function for more consistent floating point
comparisons.
The test verifies identical shapes and that the elements of actual and desired satisfy.
abs(desired-actual) < 1.5 * 10**(-decimal)
That is a looser test than originally documented, but agrees with what the actual implementation did up to rounding vagaries. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
the first assert does not raise an exception
>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan], ... [1.0,2.333,np.nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33339,np.nan], decimal=5) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 5 decimals <BLANKLINE> Mismatched elements: 1 / 3 (33.3%) Max absolute difference: 6.e-05 Max relative difference: 2.57136612e-05 x: array([1. , 2.33333, nan]) y: array([1. , 2.33339, nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33333, 5], decimal=5) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 5 decimals <BLANKLINE> x and y nan location mismatch: x: array([1. , 2.33333, nan]) y: array([1. , 2.33333, 5. ])
Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude is variable.
None
x
and y
for one or more elements is larger
than nulp
.spacing : Return the distance between x and the nearest adjacent number.
An assertion is raised if the following condition is not met:
abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))
>>> x = np.array([1., 1e-10, 1e-20]) >>> eps = np.finfo(x.dtype).eps >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) Traceback (most recent call last): ... AssertionError: X and Y are not equal to 1 ULP (max is 2)
Undocumented
Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all elements of these objects are equal (but see the Notes for the special handling of a scalar). An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
The usual caution for verifying equality with floating point numbers is advised.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
When one of x
and y
is a scalar and the other is array_like, the
function checks that each element of the array_like object is equal to
the scalar.
The first assert does not raise an exception:
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan], ... [np.exp(0),2.33333, np.nan])
Assert fails with numerical imprecision with floats:
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan], ... [1, np.sqrt(np.pi)**2, np.nan]) Traceback (most recent call last): ... AssertionError: Arrays are not equal <BLANKLINE> Mismatched elements: 1 / 3 (33.3%) Max absolute difference: 4.4408921e-16 Max relative difference: 1.41357986e-16 x: array([1. , 3.141593, nan]) y: array([1. , 3.141593, nan])
Use assert_allclose
or one of the nulp (number of floating point values)
functions for these cases instead:
>>> np.testing.assert_allclose([1.0,np.pi,np.nan], ... [1, np.sqrt(np.pi)**2, np.nan], ... rtol=1e-10, atol=0)
As mentioned in the Notes section, assert_array_equal
has special
handling for scalars. Here the test checks that each value in x
is 3:
>>> x = np.full((2, 5), fill_value=3) >>> np.testing.assert_array_equal(x, 3)
Raises an AssertionError if two array_like objects are not ordered by less than.
Given two array_like objects, check that the shape is equal and all elements of the first object are strictly smaller than those of the second object. An exception is raised at shape mismatch or incorrectly ordered values. Shape mismatch does not raise if an object has zero dimension. In contrast to the standard usage in numpy, NaNs are compared, no assertion is raised if both objects have NaNs in the same positions.
assert_array_equal: tests objects for equality assert_array_almost_equal: test objects for equality up to precision
>>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan]) >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan]) Traceback (most recent call last): ... AssertionError: Arrays are not less-ordered <BLANKLINE> Mismatched elements: 1 / 3 (33.3%) Max absolute difference: 1. Max relative difference: 0.5 x: array([ 1., 1., nan]) y: array([ 1., 2., nan])
>>> np.testing.assert_array_less([1.0, 4.0], 3) Traceback (most recent call last): ... AssertionError: Arrays are not less-ordered <BLANKLINE> Mismatched elements: 1 / 2 (50%) Max absolute difference: 2. Max relative difference: 0.66666667 x: array([1., 4.]) y: array(3)
>>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4]) Traceback (most recent call last): ... AssertionError: Arrays are not less-ordered <BLANKLINE> (shapes (3,), (1,) mismatch) x: array([1., 2., 3.]) y: array([4])
Check that all items of arrays differ in at most N Units in the Last Place.
a
and
b
can differ. Default is 1.a
and b
to if given. Default is None.a
and b
.maxulp
.For computing the ULP difference, this API does not differentiate between various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 is zero).
>>> a = np.linspace(0., 1., 100) >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), check that all elements of these objects are equal. An exception is raised at the first conflicting values.
When one of actual
and desired
is a scalar and the other is array_like,
the function checks that each element of the array_like object is equal to
the scalar.
This function handles NaN comparisons as if NaN was a "normal" number. That is, AssertionError is not raised if both objects have NaNs in the same positions. This is in contrast to the IEEE standard on NaNs, which says that NaN compared to anything must return False.
>>> np.testing.assert_equal([4,5], [4,6]) Traceback (most recent call last): ... AssertionError: Items are not equal: item=1 ACTUAL: 5 DESIRED: 6
The following comparison does not raise an exception. There are NaNs in the inputs, but they are in the same positions.
>>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
Fail if the given callable produces any reference cycles.
If called with all arguments omitted, may be used as a context manager:
- with assert_no_gc_cycles():
- do_something()
func
.func
.Nothing. The result is deliberately discarded to ensure that all cycles are found.
Fail if the given callable produces any warnings.
If called with all arguments omitted, may be used as a context manager:
- with assert_no_warnings():
- do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
func
.func
.The value returned by func
.
assert_raises(exception_class, callable, *args, **kwargs) assert_raises(exception_class)
Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.
Alternatively, assert_raises
can be used as a context manager:
>>> from numpy.testing import assert_raises >>> with assert_raises(ZeroDivisionError): ... 1 / 0
is equivalent to
>>> def div(x, y): ... return x / y >>> assert_raises(ZeroDivisionError, div, 1, 0)
assert_raises_regex(exception_class, expected_regexp)
Fail unless an exception of class exception_class and with message that matches expected_regexp is thrown by callable when invoked with arguments args and keyword arguments kwargs.
Alternatively, can be used as a context manager like assert_raises
.
Name of this function adheres to Python 3.2+ reference, but should work in all versions down to 2.6.
Test if two strings are equal.
If the given strings are equal, assert_string_equal
does nothing.
If they are not equal, an AssertionError is raised, and the diff
between the strings is shown.
>>> np.testing.assert_string_equal('abc', 'abc') >>> np.testing.assert_string_equal('abc', 'abcd') Traceback (most recent call last): File "<stdin>", line 1, in <module> ... AssertionError: Differences in strings: - abc+ abcd? +
Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when invoked with arguments args and keyword arguments kwargs. If a different type of warning is thrown, it will not be caught.
If called with all arguments other than the warning class omitted, may be used as a context manager:
- with assert_warns(SomeWarning):
- do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
The value returned by func
.
>>> import warnings >>> def deprecated_func(num): ... warnings.warn("Please upgrade", DeprecationWarning) ... return num*num >>> with np.testing.assert_warns(DeprecationWarning): ... assert deprecated_func(4) == 16 >>> # or passing a func >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4) >>> assert ret == 16
Break reference cycles by calling gc.collect Objects can call other objects' methods (for instance, another object's
__del__) inside their own __del__. On PyPy, the interpreter only runs
between calls to gc.collect, so multiple calls are needed to completely release all cycles.
Undocumented
free_bytes
amount of memory is currently free.
Returns: None if enough memory available, otherwise error messageApply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of cls
that are
matched by the regular expression testmatch
(testmatch.search(methodname)). Methods that are private, i.e. start
with an underscore, are ignored.
testmatch
is a string, it is compiled to a regular expression
first.Undocumented
like isfinite, but always raise an error if type not supported instead of returning a TypeError object.
isfinite and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised.
This should be removed once this problem is solved at the Ufunc level.
like isinf, but always raise an error if type not supported instead of returning a TypeError object.
isinf and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised.
This should be removed once this problem is solved at the Ufunc level.
like isnan, but always raise an error if type not supported instead of returning a TypeError object.
isnan and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised.
This should be removed once this problem is solved at the Ufunc level.
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc.
Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin compile. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy.
code_str
with. This is passed into compile
as the second argument (for run-time error messages).code_str
times
times.>>> times = 10 >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times) >>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP Time for a single execution : 0.005 s
For each item in x and y, return the number of representable floating points between them.
x
and y
to if given. Default is None.For computing the ULP difference, this API does not differentiate between various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 is zero).
# By definition, epsilon is the smallest number such as 1 + eps != 1, so # there should be exactly one ULP between 1 and 1 + eps >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) 1.0
Test if two objects are equal, and print an error message if test fails.
The test is performed with actual == desired.
desired
.>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1]) >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2]) Traceback (most recent call last): ... AssertionError: Test XYZ of func xyz failed ACTUAL: [0, 1] DESIRED: [0, 2]
Decorator to check for raised exceptions.
The decorated test function must raise one of the passed exceptions to
pass. If you want to test many assertions about exceptions in a single
test, you may want to use assert_raises
instead.
Warning
This decorator is nose specific, do not use it if you are using a different test framework.
AssertionError
Usage:
@raises(TypeError, ValueError) def test_raises_type_error(): raise TypeError("This test passes") @raises(Exception) def test_that_fails_by_passing(): pass
Run doctests found in the given file.
By default rundocs
raises an AssertionError on failure.
The doctests can be run by the user/developer by adding the doctests
argument to the test() call. For example, to run all tests (including
doctests) for numpy.lib
:
>>> np.lib.test(doctests=True) # doctest: +SKIP
Context manager to provide a temporary test folder.
All arguments are passed as this to the underlying tempfile.mkdtemp function.
Context manager for temporary files.
Context manager that returns the path to a closed temporary file. Its parameters are the same as for tempfile.mkstemp and are passed directly to that function. The underlying file is removed when the context is exited, so it should be closed at that time.
Windows does not allow a temporary file to be opened if it is already open, so the underlying file must be closed after opening before it can be opened again.