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)