tags:

views:

597

answers:

4

Hello people,

I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the __init__ file of the package.

So here is the script I have so far:

import os

for dirpath, dirnames, filenames in os.walk('tests'):
    for filename in filenames:
        if filename.lower().endswith(('.pyc', '__init__.py')): continue

        module = ".".join([dirpath, filename.split('.')[0]])

        print module

If I use modulename = __import__(module) the classes get added to the module 'modulename' and not the main namespace.

My question is, how do I import them to the current namespace?

So I can do things like:

testcase = TestCase()
testcase.run()
results = testcase.results()

or whatever in the main script without explicitly importing the classes.

Thanks in advance!

Thank you all for replying and trying to help me out.

+1  A: 

I do not fully understand the need because you can collect all the modules and iterate thru test case classes

but if you do want to get all names in current scope use something like

execfile("mod.py")

it will get all classed defined in mod.py into scope

Anurag Uniyal
How can I iterate trough the test case classes? I don't know how to do that. I guess that's what I'm looking for?
I have put a sample in another answer, as i can't put code in comment
Anurag Uniyal
+1  A: 

I'm not sure I exactly understand your question, but you might try nose to discover your test suites.

Noah
definitely, use nose and problem solved.
David Cournapeau
A: 

to get classes from some module, there can be better way but here is quick one to get you started

mod = __import__("mod")
for klass in vars(mod):
    o =  getattr(mod, klass)
    if type(o) == type:
        print o
Anurag Uniyal
A: 

you could use the exec on a formatted string for each module name in your scanned directory:

exec "from %s import *" % moduleName
Sean