I generated and imported a module that contains a test that I want to run with nose2
. Here is the code that creates and import the module:
import sys
import imp
import nose2
def import_code(code, name):
module = imp.new_module(name)
exec code in module.__dict__
sys.modules[name] = module
return module
code_to_test = ("""
def test_foo():
print "hello test_foo"
""")
module_to_test = import_code(code_to_test, 'moduletotest')
# now how can I tell nose2 to run the test?
Edit: I worked around the issue by using temporary files. It works for me but I'm still curious about how to do by dynamically generating a module. Here is the code to do it with a temporary file:
import tempfile
import nose2
import os
def run_test_from_temp_file():
(_, temp_file) = tempfile.mkstemp(prefix='test_', suffix='.py')
code = ("""
def test_foo():
print 'hello foo'
""")
with open(temp_file, 'w') as f:
f.write(code)
path_to_temp_file = os.path.dirname(temp_file)
module = os.path.splitext(os.path.basename(temp_file))[0]
nose2_args = ['fake_arg_to_fool_nose', module, '--verbose', '-s',
path_to_temp_file]
nose2.discover(argv=nose2_args, exit=False)
In case anyone is interested in how to do this with nose (not nose2–I haven't tried that), here it is:
where
module_to_test
is the test-containing module mentioned in the question. I have used the-s
and-v
arguments as a demonstration of how to pass additional arguments as you would on the command line, but they are not required. The above solution can also work with multiple modules by placing additional modules in themodules_to_test
list.