Example #1
0
def assert_equal(actual,desired,err_msg='',verbose=True):
    """
    Raise an assertion if two objects are not equal.

    Given two objects (lists, tuples, dictionaries or numpy arrays), check
    that all elements of these objects are equal. An exception is raised at
    the first conflicting values.

    Parameters
    ----------
    actual : list, tuple, dict or ndarray
      The object to check.
    desired : list, tuple, dict or ndarray
      The expected object.
    err_msg : string
      The error message to be printed in case of failure.
    verbose : bool
      If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal.

    Examples
    --------
    >>> np.testing.assert_equal([4,5], [4,6])
    ...
    <type 'exceptions.AssertionError'>:
    Items are not equal:
    item=1
     ACTUAL: 5
     DESIRED: 6

    """
    if isinstance(desired, dict):
        if not isinstance(actual, dict) :
            raise AssertionError(repr(type(actual)))
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k,i in desired.items():
            if k not in actual :
                raise AssertionError(repr(k))
            assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg), verbose)
        return
    if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)):
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k in range(len(desired)):
            assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg), verbose)
        return
    from numpy.core import ndarray, isscalar, signbit
    from numpy.lib import iscomplexobj, real, imag
    if isinstance(actual, ndarray) or isinstance(desired, ndarray):
        return assert_array_equal(actual, desired, err_msg, verbose)
    msg = build_err_msg([actual, desired], err_msg, verbose=verbose)

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except ValueError:
        usecomplex = False

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            assert_equal(actualr, desiredr)
            assert_equal(actuali, desiredi)
        except AssertionError:
            raise AssertionError(msg)

    # Inf/nan/negative zero handling
    try:
        # isscalar test to check cases such as [np.nan] != np.nan
        if isscalar(desired) != isscalar(actual):
            raise AssertionError(msg)

        # If one of desired/actual is not finite, handle it specially here:
        # check that both are nan if any is a nan, and test for equality
        # otherwise
        if not (gisfinite(desired) and gisfinite(actual)):
            isdesnan = gisnan(desired)
            isactnan = gisnan(actual)
            if isdesnan or isactnan:
                if not (isdesnan and isactnan):
                    raise AssertionError(msg)
            else:
                if not desired == actual:
                    raise AssertionError(msg)
            return
        elif desired == 0 and actual == 0:
            if not signbit(desired) == signbit(actual):
                raise AssertionError(msg)
    # If TypeError or ValueError raised while using isnan and co, just handle
    # as before
    except (TypeError, ValueError, NotImplementedError):
        pass
    if desired != actual :
        raise AssertionError(msg)
Example #2
0
def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
    """
    Raise an assertion if two items are not equal up to desired precision.

    The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal)

    Given two objects (numbers or ndarrays), check that all elements of these
    objects are almost equal. An exception is raised at conflicting values.
    For ndarrays this delegates to assert_array_almost_equal

    Parameters
    ----------
    actual : number or ndarray
      The object to check.
    desired : number or ndarray
      The expected object.
    decimal : integer (decimal=7)
      desired precision
    err_msg : string
      The error message to be printed in case of failure.
    verbose : bool
      If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal up to specified precision.

    See Also
    --------
    assert_array_almost_equal: compares array_like objects
    assert_equal: tests objects for equality


    Examples
    --------
    >>> import numpy.testing as npt
    >>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
    >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
    ...
    <type 'exceptions.AssertionError'>:
    Items are not equal:
     ACTUAL: 2.3333333333333002
     DESIRED: 2.3333333399999998

    >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
    \t\t\tnp.array([1.0,2.33333334]), decimal=9)
    ...
    <type 'exceptions.AssertionError'>:
    Arrays are not almost equal
    <BLANKLINE>
    (mismatch 50.0%)
     x: array([ 1.        ,  2.33333333])
     y: array([ 1.        ,  2.33333334])

    """
    from numpy.core import ndarray
    from numpy.lib import iscomplexobj, real, imag

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except ValueError:
        usecomplex = False

    msg = build_err_msg([actual, desired], err_msg, verbose=verbose,
                         header='Arrays are not almost equal')

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            assert_almost_equal(actualr, desiredr, decimal=decimal)
            assert_almost_equal(actuali, desiredi, decimal=decimal)
        except AssertionError:
            raise AssertionError(msg)

    if isinstance(actual, (ndarray, tuple, list)) \
            or isinstance(desired, (ndarray, tuple, list)):
        return assert_array_almost_equal(actual, desired, decimal, err_msg)
    try:
        # If one of desired/actual is not finite, handle it specially here:
        # check that both are nan if any is a nan, and test for equality
        # otherwise
        if not (gisfinite(desired) and gisfinite(actual)):
            if gisnan(desired) or gisnan(actual):
                if not (gisnan(desired) and gisnan(actual)):
                    raise AssertionError(msg)
            else:
                if not desired == actual:
                    raise AssertionError(msg)
            return
    except (NotImplementedError, TypeError):
        pass
    if round(abs(desired - actual),decimal) != 0 :
        raise AssertionError(msg)
Example #3
0
def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
    """
    Raise an assertion if two items are not equal up to desired precision.

    The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal)

    Given two objects (numbers or ndarrays), check that all elements of these
    objects are almost equal. An exception is raised at conflicting values.
    For ndarrays this delegates to assert_array_almost_equal

    Parameters
    ----------
    actual : number or ndarray
      The object to check.
    desired : number or ndarray
      The expected object.
    decimal : integer (decimal=7)
      desired precision
    err_msg : string
      The error message to be printed in case of failure.
    verbose : bool
      If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal up to specified precision.

    See Also
    --------
    assert_array_almost_equal: compares array_like objects
    assert_equal: tests objects for equality


    Examples
    --------
    >>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
    >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
    ...
    <type 'exceptions.AssertionError'>:
    Items are not equal:
     ACTUAL: 2.3333333333333002
     DESIRED: 2.3333333399999998

    >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
    \t\t\tnp.array([1.0,2.33333334]), decimal=9)
    ...
    <type 'exceptions.AssertionError'>:
    Arrays are not almost equal
    <BLANKLINE>
    (mismatch 50.0%)
     x: array([ 1.        ,  2.33333333])
     y: array([ 1.        ,  2.33333334])

    """
    from numpy.core import ndarray
    from numpy.lib import iscomplexobj, real, imag

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except ValueError:
        usecomplex = False

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            assert_almost_equal(actualr, desiredr, decimal=decimal)
            assert_almost_equal(actuali, desiredi, decimal=decimal)
        except AssertionError:
            raise AssertionError("Items are not equal:\n" \
                    "ACTUAL: %s\n" \
                    "DESIRED: %s\n" % (str(actual), str(desired)))

    if isinstance(actual, (ndarray, tuple, list)) \
            or isinstance(desired, (ndarray, tuple, list)):
        return assert_array_almost_equal(actual, desired, decimal, err_msg)
    msg = build_err_msg([actual, desired], err_msg, verbose=verbose,
                         header='Arrays are not almost equal')
    try:
        # If one of desired/actual is not finite, handle it specially here:
        # check that both are nan if any is a nan, and test for equality
        # otherwise
        if not (gisfinite(desired) and gisfinite(actual)):
            if gisnan(desired) or gisnan(actual):
                if not (gisnan(desired) and gisnan(actual)):
                    raise AssertionError(msg)
            else:
                if not desired == actual:
                    raise AssertionError(msg)
            return
    except TypeError:
        pass
    if round(abs(desired - actual),decimal) != 0 :
        raise AssertionError(msg)
Example #4
0
def assert_equal(actual,desired,err_msg='',verbose=True):
    """
    Raise an assertion if two objects are not equal.

    Given two objects (lists, tuples, dictionaries or numpy arrays), check
    that all elements of these objects are equal. An exception is raised at
    the first conflicting values.

    Parameters
    ----------
    actual : list, tuple, dict or ndarray
      The object to check.
    desired : list, tuple, dict or ndarray
      The expected object.
    err_msg : string
      The error message to be printed in case of failure.
    verbose : bool
      If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal.

    Examples
    --------
    >>> np.testing.assert_equal([4,5], [4,6])
    ...
    <type 'exceptions.AssertionError'>:
    Items are not equal:
    item=1
     ACTUAL: 5
     DESIRED: 6

    """
    if isinstance(desired, dict):
        if not isinstance(actual, dict) :
            raise AssertionError(repr(type(actual)))
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k,i in desired.items():
            if k not in actual :
                raise AssertionError(repr(k))
            assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg), verbose)
        return
    if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)):
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k in range(len(desired)):
            assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg), verbose)
        return
    from numpy.core import ndarray, isscalar, signbit
    from numpy.lib import iscomplexobj, real, imag
    if isinstance(actual, ndarray) or isinstance(desired, ndarray):
        return assert_array_equal(actual, desired, err_msg, verbose)
    msg = build_err_msg([actual, desired], err_msg, verbose=verbose)

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except ValueError:
        usecomplex = False

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            assert_equal(actualr, desiredr)
            assert_equal(actuali, desiredi)
        except AssertionError:
            raise AssertionError("Items are not equal:\n" \
                    "ACTUAL: %s\n" \
                    "DESIRED: %s\n" % (str(actual), str(desired)))

    # Inf/nan/negative zero handling
    try:
        # isscalar test to check cases such as [np.nan] != np.nan
        if isscalar(desired) != isscalar(actual):
            raise AssertionError(msg)

        # If one of desired/actual is not finite, handle it specially here:
        # check that both are nan if any is a nan, and test for equality
        # otherwise
        if not (gisfinite(desired) and gisfinite(actual)):
            isdesnan = gisnan(desired)
            isactnan = gisnan(actual)
            if isdesnan or isactnan:
                if not (isdesnan and isactnan):
                    raise AssertionError(msg)
            else:
                if not desired == actual:
                    raise AssertionError(msg)
            return
        elif desired == 0 and actual == 0:
            if not signbit(desired) == signbit(actual):
                raise AssertionError(msg)
    # If TypeError or ValueError raised while using isnan and co, just handle
    # as before
    except TypeError:
        pass
    except ValueError:
        pass
    if desired != actual :
        raise AssertionError(msg)
Example #5
0
def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
    """
    Raise an assertion 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 is equivalent to ``abs(desired-actual) < 0.5 * 10**(-decimal)``.

    Given two objects (numbers or ndarrays), check that all elements of these
    objects are almost equal. An exception is raised at conflicting values.
    For ndarrays this delegates to assert_array_almost_equal

    Parameters
    ----------
    actual : array_like
        The object to check.
    desired : array_like
        The expected object.
    decimal : int, optional
        Desired precision, default is 7.
    err_msg : str, optional
        The error message to be printed in case of failure.
    verbose : bool, optional
        If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal up to specified precision.

    See Also
    --------
    assert_allclose: Compare two array_like objects for equality with desired
                     relative and/or absolute precision.
    assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

    Examples
    --------
    >>> import numpy.testing as npt
    >>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
    >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
    ...
    <type 'exceptions.AssertionError'>:
    Items are not equal:
     ACTUAL: 2.3333333333333002
     DESIRED: 2.3333333399999998

    >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
    ...                         np.array([1.0,2.33333334]), decimal=9)
    ...
    <type 'exceptions.AssertionError'>:
    Arrays are not almost equal
    <BLANKLINE>
    (mismatch 50.0%)
     x: array([ 1.        ,  2.33333333])
     y: array([ 1.        ,  2.33333334])

    """
    from numpy.core import ndarray
    from numpy.lib import iscomplexobj, real, imag

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except ValueError:
        usecomplex = False

    msg = build_err_msg([actual, desired], err_msg, verbose=verbose,
             header=('Arrays are not almost equal to %d decimals' % decimal))

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            assert_almost_equal(actualr, desiredr, decimal=decimal)
            assert_almost_equal(actuali, desiredi, decimal=decimal)
        except AssertionError:
            raise AssertionError(msg)

    if isinstance(actual, (ndarray, tuple, list)) \
            or isinstance(desired, (ndarray, tuple, list)):
        return assert_array_almost_equal(actual, desired, decimal, err_msg)
    try:
        # If one of desired/actual is not finite, handle it specially here:
        # check that both are nan if any is a nan, and test for equality
        # otherwise
        if not (gisfinite(desired) and gisfinite(actual)):
            if gisnan(desired) or gisnan(actual):
                if not (gisnan(desired) and gisnan(actual)):
                    raise AssertionError(msg)
            else:
                if not desired == actual:
                    raise AssertionError(msg)
            return
    except (NotImplementedError, TypeError):
        pass
    if round(abs(desired - actual),decimal) != 0 :
        raise AssertionError(msg)
Example #6
0
    def assert_almost_equal(actual,
                            desired,
                            decimal=7,
                            err_msg='',
                            verbose=True):
        """
        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 is equivalent to ``abs(desired-actual) < 0.5 * 10**(-decimal)``.
        Given two objects (numbers or ndarrays), check that all elements of these
        objects are almost equal. An exception is raised at conflicting values.
        For ndarrays this delegates to assert_array_almost_equal
        Parameters
        ----------
        actual : array_like
            The object to check.
        desired : array_like
            The expected object.
        decimal : int, optional
            Desired precision, default is 7.
        err_msg : str, optional
            The error message to be printed in case of failure.
        verbose : bool, optional
            If True, the conflicting values are appended to the error message.
        Raises
        ------
        AssertionError
          If actual and desired are not equal up to specified precision.
        See Also
        --------
        assert_allclose: Compare two array_like objects for equality with desired
                         relative and/or absolute precision.
        assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
        Examples
        --------
        >>> import numpy.testing as npt
        >>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
        >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
        ...
        <type 'exceptions.AssertionError'>:
        Items are not equal:
         ACTUAL: 2.3333333333333002
         DESIRED: 2.3333333399999998
        >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
        ...                         np.array([1.0,2.33333334]), decimal=9)
        ...
        <type 'exceptions.AssertionError'>:
        Arrays are not almost equal
        <BLANKLINE>
        (mismatch 50.0%)
         x: array([ 1.        ,  2.33333333])
         y: array([ 1.        ,  2.33333334])
        """
        __tracebackhide__ = True  # Hide traceback for py.test
        from numpy.core import ndarray
        from numpy.lib import iscomplexobj, real, imag
        from numpy.testing.utils import (assert_array_almost_equal,
                                         build_err_msg, gisfinite, gisnan)

        # Handle complex numbers: separate into real/imag to handle
        # nan/inf/negative zero correctly
        # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
        try:
            usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
        except ValueError:
            usecomplex = False

        def _build_err_msg():
            header = ('Arrays are not almost equal to %d decimals' % decimal)
            return build_err_msg([actual, desired],
                                 err_msg,
                                 verbose=verbose,
                                 header=header)

        if usecomplex:
            if iscomplexobj(actual):
                actualr = real(actual)
                actuali = imag(actual)
            else:
                actualr = actual
                actuali = 0
            if iscomplexobj(desired):
                desiredr = real(desired)
                desiredi = imag(desired)
            else:
                desiredr = desired
                desiredi = 0
            try:
                assert_almost_equal(actualr, desiredr, decimal=decimal)
                assert_almost_equal(actuali, desiredi, decimal=decimal)
            except AssertionError:
                raise AssertionError(_build_err_msg())

        if isinstance(actual, (ndarray, tuple, list)) \
                or isinstance(desired, (ndarray, tuple, list)):
            return assert_array_almost_equal(actual, desired, decimal, err_msg)
        try:
            # If one of desired/actual is not finite, handle it specially here:
            # check that both are nan if any is a nan, and test for equality
            # otherwise
            if not (gisfinite(desired) and gisfinite(actual)):
                if gisnan(desired) or gisnan(actual):
                    if not (gisnan(desired) and gisnan(actual)):
                        raise AssertionError(_build_err_msg())
                else:
                    if not desired == actual:
                        raise AssertionError(_build_err_msg())
                return
        except (NotImplementedError, TypeError):
            pass
        if round(abs(desired - actual), decimal) != 0:
            raise AssertionError(_build_err_msg())
Example #7
0
def assert_almost_equal(actual,
                        desired,
                        rtol=1e-7,
                        atol=0,
                        ignored_values=None,
                        err_msg='',
                        verbose=True):
    """
    Function imported from numpy.testing: assert_equal. Version 16.2.
    Two key modifications compared to the original implementation:
    1) allow comparison of numbers with a tolerance on the difference (other functions
        in numpy that allow a tolerance as an argument do not support comparison
        between dictionaries).
    2) allow to skip the explicit comparison of some attributes in dictionaries.

    Raises an AssertionError if two objects are not equal within the required tolerances.
    Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
    check that all elements of these objects are almost equal. An exception is raised
    at the first conflicting values.
    Comparison for numerical values is performed with assert_allclose

    Args:
        actual: the object to check.
        desired : the expected object.
        rtol (float): relative tolerance.
        atol (float): absolute tolerance.
        ignored_values (list): if a comparison between two dictionaries, keywords contained
            in this list will not be compared (the key should still exist in both the
            dictionaries though).
        err_msg (str): the error message to be printed in case of failure.
        verbose (bool): if True, the conflicting values are appended to the error message.

    Raises:
        AssertionError: if actual and desired are not equal.
    """
    __tracebackhide__ = True  # Hide traceback for py.test
    if isinstance(desired, dict):
        if not isinstance(actual, dict):
            raise AssertionError(repr(type(actual)))
        assert_almost_equal(len(actual), len(desired), rtol, atol,
                            ignored_values, err_msg, verbose)

        if ignored_values is None:
            ignored_values = []

        for k, i in desired.items():
            if k not in actual:
                raise AssertionError(repr(k))

            # don't check nested values if the key belong to the list to skip
            if k in ignored_values:
                continue

            assert_almost_equal(actual[k], desired[k], rtol, atol,
                                ignored_values, 'key=%r\n%s' % (k, err_msg),
                                verbose)
        return
    if isinstance(desired,
                  (list, tuple)) and isinstance(actual, (list, tuple)):
        assert_almost_equal(len(actual), len(desired), rtol, atol,
                            ignored_values, err_msg, verbose)
        for k in range(len(desired)):
            assert_almost_equal(actual[k], desired[k], rtol, atol,
                                ignored_values, 'item=%r\n%s' % (k, err_msg),
                                verbose)
        return
    from numpy.core import ndarray, isscalar, signbit
    from numpy.lib import iscomplexobj, real, imag
    if isinstance(actual, ndarray) or isinstance(desired, ndarray):
        return np.testing.assert_allclose(actual,
                                          desired,
                                          rtol=rtol,
                                          atol=atol,
                                          err_msg=err_msg,
                                          verbose=verbose)
    msg = np.testing.build_err_msg([actual, desired], err_msg, verbose=verbose)

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except (ValueError, TypeError):
        usecomplex = False

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            np.testing.assert_allclose(actualr, desiredr, rtol=rtol, atol=atol)
            np.testing.assert_allclose(actuali, desiredi, rtol=rtol, atol=atol)
        except AssertionError:
            raise AssertionError(msg)

    # isscalar test to check cases such as [np.nan] != np.nan
    if isscalar(desired) != isscalar(actual):
        raise AssertionError(msg)

    a_is_number = isinstance(actual, numbers.Number)
    d_is_number = isinstance(desired, numbers.Number)

    if a_is_number != d_is_number:
        raise AssertionError(msg)

    if a_is_number:
        if np.isclose(actual, desired, rtol=rtol, atol=atol):
            return
        else:
            raise AssertionError(msg)

    # Inf/nan/negative zero handling
    try:
        isdesnan = gisnan(desired)
        isactnan = gisnan(actual)
        if isdesnan and isactnan:
            return  # both nan, so equal

        # allow 0.0 and -0.0 to match
        if desired == 0 and actual == 0:
            return
            # if not signbit(desired) == signbit(actual):
            #     raise AssertionError(msg)

    except (TypeError, ValueError, NotImplementedError):
        pass

    try:
        isdesnat = np.core.isnat(desired)
        isactnat = np.core.isnat(actual)
        dtypes_match = np.array(desired).dtype.type == np.array(
            actual).dtype.type
        if isdesnat and isactnat:
            # If both are NaT (and have the same dtype -- datetime or
            # timedelta) they are considered equal.
            if dtypes_match:
                return
            else:
                raise AssertionError(msg)

    except (TypeError, ValueError, NotImplementedError):
        pass

    try:
        # First check if they are equal with ==. If not Use assert allclose instead of __eq__
        if not (desired == actual):
            raise AssertionError(msg)
            # try:
            #     np.testing.assert_allclose(actual, desired, rtol=rtol, atol=atol)
            # except (AssertionError, TypeError):
            #     raise AssertionError(msg)

    except (DeprecationWarning, FutureWarning) as e:
        # this handles the case when the two types are not even comparable
        if 'elementwise == comparison' in e.args[0]:
            raise AssertionError(msg)
        else:
            raise