Search code examples
pythonnosedoctest

python doctest default namespace


In the doctests of my module I would like to reference my module with the full namespace, for example:

  hp.myfunc(1)

And I would like to avoid cluttering the doctests by writing:

  import healpy as hp

in each of the doctests.

if I run doctest.testmod, I know I can use the globs keyword to provide this, while if I run nose, I can use the setup function.

Is there another standard way that could work with both?


Solution

  • How are you running the doctests (without nose, that is)? If you are cd'd into the package directory when you attempt to run them, you will run into problems (if you are doing a full import, that is).

    I was able to get a simple doctest (with fully-qualified imports) running with both nosetests and the builtin doctest runner. Here's my setup:

    Project structure:

    .
    └── mypackage
        ├── __init__.py
        └── mod.py
    

    Here are the contents of my 'mod.py' file:

    """foo() providing module
    
    Example:
        >>> import mypackage.mod
        >>> mypackage.mod.foo()
        'bar'
    """
    
    def foo():
        return "bar"
    

    from the '.' directory (project root), I can now run tests:

    $ python -m doctest -v mypackage/*.py
    1 items had no tests:
        __init__
    0 tests in 1 items.
    0 passed and 0 failed.
    Test passed.
    Trying:
        import mypackage.mod
    Expecting nothing
    ok
    Trying:
        mypackage.mod.foo()
    Expecting:
        'bar'
    ok
    1 items had no tests:
        mod.foo
    1 items passed all tests:
       2 tests in mod
    2 tests in 2 items.
    2 passed and 0 failed.
    Test passed.
    

    And now the nosetests:

    $ nosetests --with-doctest
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.008s
    
    OK
    

    If I try to run the doctest from within the 'mypackage' directory, I get an error (which is, I suspect, what's happening in your case).

    Finally, I don't think this should make a difference, but I'm running Python 2.7.2