简体   繁体   中英

nose2: run tests from an imported module

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:

from nose.loader import TestLoader
from nose import run

modules_to_test = [module_to_test]

test_loader = TestLoader()
context_suites = list(map(test_loader.loadTestsFromModule, modules_to_test))
run(suite=context_suites, argv=['-s', '-v'])

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 the modules_to_test list.

There are two ways to execute nose. There is a standalone program that comes with the distribution called nosetests. You can pass your file with the unittests in as an option:

nosetests unittests.py

Or specify a module:

nosetests mymodule.test

Or alternatively in your test module you can call the nose library and ask it to run by calling nose.main() or nose.run() in your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM