Source code for nnsa.utils.testing

"""
General functions useful for testing.
"""
import numpy as np

__all__ = [
    'assert_equal',
    'beep',
]


[docs]def assert_equal(actual, desired): """ Tests if two objects are equal (like numpy's assert_equal). Recursive algorithm. Base case is when the desired object is an object accepted by numpy's assert_equal (scalars, lists, tuples, dictionaries, numpy arrays and None). In that case, assert_equal will be called to compare the objects. In the other cases, where the desired object is some custom, arbitrary object, the function will be called recursively on the objects' attributes. Args: actual (object): the object to check. desired (object): the expected object. Returns: """ if np.isscalar(desired) or desired is None: # Base case: use numpy's assert equal for scalars, lists, tuples, dictionaries, numpy arrays and None. np.testing.assert_equal(actual=actual, desired=desired) elif isinstance(desired, (list, tuple, dict, np.ndarray)): # Check each item in the collection. try: np.testing.assert_equal(actual=actual, desired=desired) except AssertionError: # Possibly, the items are custom objects -> recursively compare each object. if isinstance(desired, dict): for key in desired.keys(): assert_equal(actual=actual[key], desired=desired[key]) else: for i_desired, i_actual in zip(desired, actual): assert_equal(actual=i_actual, desired=i_desired) else: # Attributes of actual and desired objects. a_attrs = actual.__dict__ d_attrs = desired.__dict__ # Test for every attribute recursively. for key in a_attrs.keys(): assert_equal(actual=a_attrs[key], desired=d_attrs[key])
[docs]def beep(duration=100): """ Make a beep sound on Windows systems. NOTE: only works on windows. Args: duration (int, optional): duration of beep in miliseconds. """ import winsound frequency = 1420 winsound.Beep(frequency, duration)