#!/usr/bin/env python3
# vim: ft=python
""" Run nosetests for dipy while patching nose

Use as ``nosetests`` except we always run the doctests, and we patch the doctest
plugin to deal with a bug in nose at least <= 1.2.1

To reproduce a standard test run::

    dipnost /path/to/dipy/dipy

"""

import sys
import nose
from nose.plugins import doctests

# We were getting errors for the extension modules.  See:
# https://github.com/nose-devs/nose/pull/661
# and
# https://github.com/nose-devs/nose/issues/447
def id(self):
    name = self._dt_test.name
    filename = self._dt_test.filename
    if filename is not None:
        pk = doctests.getpackage(filename)
        if pk is None:
            return name
        if not name.startswith(pk):
            name = f"{pk}.{name}"
    return name

def prepare_imports():
    # Set matplotlib backend as 'agg'
    try:
        import matplotlib as mpl
    except ImportError:
        pass
    else:
        mpl.use('agg')

if __name__ == '__main__':
    # Monkeypatch.  Yes, it's nasty
    doctests.DocTestCase.id = id
    # Set mpl backend
    prepare_imports()
    # Enable doctests
    argv = sys.argv + ['--with-doctest']
    nose.core.TestProgram(argv=argv, addplugins=[doctests.Doctest()])
