""" Test testing utilities
"""

import sys

from warnings import warn, simplefilter

from ..testing import catch_warn_reset

from nose.tools import assert_equal


def assert_warn_len_equal(mod, n_in_context):
    mod_warns = mod.__warningregistry__
    # Python 3.4 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:
        assert_equal(len(mod_warns), 2)  # including 'version'
    else:
        assert_equal(len(mod_warns), n_in_context)


def test_catch_warn_reset():
    # Initial state of module, no warnings
    my_mod = sys.modules[__name__]
    assert_equal(getattr(my_mod, '__warningregistry__', None), None)
    with catch_warn_reset(modules=[my_mod]):
        simplefilter('ignore')
        warn('Some warning')
    assert_equal(my_mod.__warningregistry__, {})
    # Without specified modules, don't clear warnings during context
    with catch_warn_reset():
        simplefilter('ignore')
        warn('Some warning')
    assert_warn_len_equal(my_mod, 1)
    # Confirm that specifying module keeps old warning, does not add new
    with catch_warn_reset(modules=[my_mod]):
        simplefilter('ignore')
        warn('Another warning')
    assert_warn_len_equal(my_mod, 1)
    # Another warning, no module spec does add to warnings dict, except on
    # Python 3.4 (see comments in `assert_warn_len_equal`)
    with catch_warn_reset():
        simplefilter('ignore')
        warn('Another warning')
    assert_warn_len_equal(my_mod, 2)
