Debian Codegraph @

brian2/tests/utils.py

raw
1 import numpy as np
2 from numpy.testing import assert_allclose as numpy_allclose
3
4 from brian2 import prefs
5 from brian2.units.fundamentalunits import have_same_dimensions
6
7
8 def assert_allclose(actual, desired, rtol=4.5e8, atol=1e-9, **kwds):
9 """
10 Thin wrapper around numpy's `~numpy.testing.utils.assert_allclose` function. The tolerance depends on the floating
11 point precision as defined by the `core.default_float_dtype` preference.
12
13 Parameters
14 ----------
15 actual : `numpy.ndarray`
16 The results to check.
17 desired : `numpy.ndarray`
18 The expected results.
19 rtol : float, optional
20 The relative tolerance which will be multiplied with the machine epsilon of the type set as
21 `core.default_float_type`.
22 atol : float, optional
23 The absolute tolerance
24 """
25 assert have_same_dimensions(actual, desired)
26 eps = np.finfo(prefs["core.default_float_dtype"]).eps
27 rtol = eps * rtol
28 numpy_allclose(
29 np.asarray(actual), np.asarray(desired), rtol=rtol, atol=atol, **kwds
30 )
31
32
33 def exc_isinstance(exc_info, expected_exception, raise_not_implemented=False):
34 """
35 Simple helper function as an alternative to calling
36 `~.pytest.ExceptionInfo.errisinstance` which will take into account all
37 the "causing" exceptions in an exception chain.
38
39 Parameters
40 ----------
41 exc_info : `pytest.ExceptionInfo` or `Exception`
42 The exception info as returned by `pytest.raises`.
43 expected_exception : `type`
44 The expected exception class
45 raise_not_implemented : bool, optional
46 Whether to re-raise a `NotImplementedError` – necessary for tests that
47 should be skipped with ``@skip_if_not_implemented``. Defaults to
48 ``False``.
49
50 Returns
51 -------
52 correct_exception : bool
53 Whether the exception itself or one of the causing exceptions is of the
54 expected type.
55 """
56 if exc_info is None:
57 return False
58 if hasattr(exc_info, "value"):
59 exc_info = exc_info.value
60
61 if isinstance(exc_info, expected_exception):
62 return True
63 elif raise_not_implemented and isinstance(exc_info, NotImplementedError):
64 raise exc_info
65
66 return exc_isinstance(
67 exc_info.__cause__,
68 expected_exception,
69 raise_not_implemented=raise_not_implemented,
70 )