tags:

views:

73

answers:

1

I'd like to run doctests for a set of modules (glob: invenio.webtag*) from a single module, but I'll need a way to import all these (and only these) modules and run doctest.testmod() on all of them. Any ideas?

Edit: The solution:

import doctest
import glob
import os
import pkgutil
pkgpath = pkgutil.extend_path([], 'invenio')[0]
for module_path in glob.glob(pkgpath + '/webtag*.py'):
    module_name = os.path.splitext(os.path.basename(module_path))[0]
    module = __import__('invenio.' + module_name)
    doctest.testmod(module)
+1  A: 

A module can be dynamically loaded using __import__ e.g.

my_module = __import__("mymodule")

and then passed to testmod e.g.

doctest.testmod(my_module)

Assuming you can build a list of the matching modules using either glob.glob or filtering the results from os.listdir you should be able to use this approach.

Update:

To import invenio.webtag try using a fromlist:

module = __import__('invenio.webtag', globals(), locals(), ['invenio'], -1)

see this documentation for the explanation.

mikej
Cool, thanks. Now I just have to figure out why this piece of code imports `invenio` instead of `invenio.webtag`: `module = __import__('invenio.webtag')`
l0b0
@l0b0: From the `__import__` docs: "When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty."
Pär Wieslander
I have updated the answer to show how to import a submodule. Pär added a comment saying the same thing whilst I was doing the edit.
mikej