"""Testing file unit test."""

import sys
import warnings
import numpy as np

import dipy.testing as dt
import numpy.testing as npt


def test_assert():
    npt.assert_raises(AssertionError, dt.assert_false, True)
    npt.assert_raises(AssertionError, dt.assert_true, False)
    npt.assert_raises(AssertionError, dt.assert_less, 2, 1)
    npt.assert_raises(AssertionError, dt.assert_less_equal, 2, 1)
    npt.assert_raises(AssertionError, dt.assert_greater, 1, 2)
    npt.assert_raises(AssertionError, dt.assert_greater_equal, 1, 2)
    npt.assert_raises(AssertionError, dt.assert_not_equal, 5, 5)
    npt.assert_raises(AssertionError, dt.assert_operator, 2, 1)

    arr = [np.arange(k) for k in range(2, 12, 3)]
    arr2 = [np.arange(k) for k in range(2, 12, 4)]
    npt.assert_raises(AssertionError, dt.assert_arrays_equal, arr, arr2)


def assert_warn_len_equal(mod, n_in_context):
    mod_warns = mod.__warningregistry__
    # Python 3 appears to clear any pre-existing warnings of the same type,
    # when raising warnings inside a catch_warnings block. So, there is a
    # warning generated by the tests within the context manager, but no
    # previous warnings.
    if 'version' in mod_warns:
        # including 'version'
        npt.assert_equal(len(mod_warns), 2)
    else:
        npt.assert_equal(len(mod_warns), n_in_context)


def test_clear_and_catch_warnings():
    warnings.simplefilter("default", category=UserWarning)
    # Initial state of module, no warnings
    my_mod = sys.modules[__name__]
    try:
        my_mod.__warningregistry__.clear()
    except AttributeError:
        pass

    npt.assert_equal(getattr(my_mod, '__warningregistry__', {}), {})
    with dt.clear_and_catch_warnings(modules=[my_mod]):
        warnings.simplefilter('ignore')
        warnings.warn('Some warning')
    npt.assert_equal(my_mod.__warningregistry__, {})
    # Without specified modules, don't clear warnings during context
    with dt.clear_and_catch_warnings():
        warnings.warn('Some warning')
    assert_warn_len_equal(my_mod, 1)
    # Confirm that specifying module keeps old warning, does not add new
    with dt.clear_and_catch_warnings(modules=[my_mod]):
        warnings.warn('Another warning')
    assert_warn_len_equal(my_mod, 1)
    # Another warning, no module spec does add to warnings dict, except on
    # Python 3 (see comments in `assert_warn_len_equal`)
    with dt.clear_and_catch_warnings():
        warnings.warn('Another warning')
    assert_warn_len_equal(my_mod, 2)
    warnings.simplefilter("always", category=UserWarning)
