Nose2:从导入的模块运行测试



我生成并导入了一个模块,其中包含一个我想用nose2运行的测试。下面是创建和导入模块的代码:

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?

编辑:我通过使用临时文件解决了这个问题。它适用于我,但我仍然好奇如何通过动态生成一个模块。下面是使用临时文件执行此操作的代码:
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)

如果有人对如何用鼻子(不是nose2 -我还没有尝试过)做到这一点感兴趣,这里是:

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'])

,其中module_to_test为题中提到的包含测试的模块。我使用-s-v参数来演示如何像在命令行上那样传递额外的参数,但它们不是必需的。上述解决方案还可以通过在modules_to_test列表中放置额外的模块来处理多个模块。

执行nose有两种方法。该发行版附带了一个名为nosetests的独立程序。您可以将带有单元测试的文件作为选项传入:

nosetests unittests.py

或指定模块:

nosetests mymodule.test

或者在您的测试模块中,您可以调用nose库并通过在程序中调用nose.main()或nose.run()来要求它运行。

最新更新