我生成并导入了一个模块,该模块包含我希望使用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)发布于 2021-04-09 02:16:59
如果有人对如何使用鼻子(不是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列表中放置其他模块来处理多个模块。
发布于 2015-07-28 10:32:19
执行鼻子有两种方法。有一个独立的程序,与发行版一起被称为nosetest。您可以将带有unittest的文件作为选项传递:
鼻测试unittests.py
或指定一个模块:
鼻测试mymodule.test
或者,在您的测试模块中,您可以调用鼻子库,并通过调用程序中的nose.main()或nose.run()来运行它。
https://stackoverflow.com/questions/31673610
复制相似问题