2015-07-28 64 views
1

我生成并导入了一个模块,其中包含我想用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) 

回答

-1

有两种执行鼻子的方法。有一个独立程序与称为nosetests的发行版一起提供。你可以通过与单元测试文件中作为一个选项:

nosetests unittests.py

或指定模块:

nosetests mymodule.test

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

+2

这是鼻子,但我使用nose2。我知道如何从脚本运行nose2:'nose2.discover(argv = ['fake_arg','mypkg.mymod.test_foo',''''。')',但是这会通过导入模块加载测试,而我想从已经是导入器的模块加载测试。 –