繁体   English   中英

鼻子 2:从导入的模块运行测试

[英]nose2: run tests from an imported module

我生成并导入了一个模块,该模块包含一个我想用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列表中放置其他模块来处理多个模块。

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

鼻子测试 unittests.py

或者指定一个模块:

鼻子测试 mymodule.test

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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