2015-07-28 42 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',''''。')',但是這會通過導入模塊加載測試,而我想從已經是導入器的模塊加載測試。 –

相關問題