运行生成的鼻子测试

Kei*_*hip 6 python nose

假设我定义了一个testFile.pypython模块,如下所示.

def test_evens():
    for i in range(0, 5):
        yield check_even, i, i*3

def check_even(n, nn):
    assert n % 2 == 0 or nn % 2 == 0
Run Code Online (Sandbox Code Playgroud)

当我让鼻子在仅收集模式中识别测试时,我得到了

testFile.test_evens(0, 0) ... ok
testFile.test_evens(1, 3) ... ok
testFile.test_evens(2, 6) ... ok
testFile.test_evens(3, 9) ... ok
testFile.test_evens(4, 12) ... ok
Run Code Online (Sandbox Code Playgroud)

我可以使用运行所有测试

nosetests -v testFile:test_evens

但是,如果我只想运行testFile.test_evens(2,6)(即,不是所有测试),该怎么办?

有没有办法从命令行执行此操作?

sam*_*ias 7

据我所知,默认情况下,鼻子不能这样做.以下是一些选项:

1.从命令行伪造它

可能不是你想要的,但我必须提到它.您还可以创建一个包装器脚本来简化此操作:

python -c 'import testFile; testFile.check_even(2, 6)'
Run Code Online (Sandbox Code Playgroud)

2.创建自定义鼻子测试加载器

这稍微复杂一些,但您可以创建一个自定义测试加载器,它将命令行参数解释为指定要加载的生成器,从生成器中提取测试和参数,并返回包含测试的套件.匹配参数.

下面是一些示例代码,它应该足以构建(runner.py):

import ast
import nose

class CustomLoader(nose.loader.TestLoader):

    def loadTestsFromName(self, name, module=None):
        # parse the command line arg
        parts = name.split('(', 1)
        mod_name, func_name = parts[0].split('.')
        args = ast.literal_eval('(' + parts[1])

        # resolve the module and function - you'll probably want to
        # replace this with nose's internal discovery methods.
        mod = __import__(mod_name)
        func = getattr(mod, func_name)

        # call the generator and gather all matching tests
        tests = []
        if nose.util.isgenerator(func):
            for test in func():
                _func, _args = self.parseGeneratedTest(test)
                if _args == args:
                    tests.append(nose.case.FunctionTestCase(_func, arg=_args))
        return self.suiteClass(tests)

nose.main(testLoader=CustomLoader)
Run Code Online (Sandbox Code Playgroud)

执行它:

% python runner.py 'testFile.test_evens(2, 6)' -v
testFile.check_even(2, 6) ... ok

% python runner.py 'testFile.test_evens(2, 6)' 'testFile.test_evens(4, 12)' -v
testFile.check_even(2, 6) ... ok
testFile.check_even(4, 12) ... ok

% python runner.py 'testFile.test_evens(1, 3)' -v
testFile.check_even(1, 3) ... FAIL
Run Code Online (Sandbox Code Playgroud)