Skip to main content
 首页 » 编程设计

python之我可以在 PyTest 中明确指定多个测试吗

2024年10月17日7kevingrace

我知道我可以使用以下命令指定要在 PyTest 中运行的单个测试:

py.test test.py::my_test_class::my_test_function。

有没有办法明确指定要运行的多个测试,而不是运行所有测试?

我可以在 for 循环中运行 py.test 命令,每次指定不同的测试,但是有更好的解决方案吗?

请您参考如下方法:

您可以将测试放在一个文件中,实现修饰符 Hook 以根据文件中是否存在测试来过滤要执行的测试。这是一个例子:

测试文件#1

$ cat test_foo.py  
def test_001(): 
    pass 
def test_002(): 
    pass 
$  

测试文件#2

$ cat test_bar.py  
def test_001(): 
    pass 
def test_003(): 
    pass 
$  

包含要执行的测试的源文件

$ cat my_tests  
test_001 
test_002 
$  

修饰符 Hook

$ cat conftest.py  
import pytest 
 
def pytest_addoption(parser): 
    parser.addoption("--testsource", action="store", default=None, 
                     help="File containing tests to run") 
 
def pytest_collection_modifyitems(session, config, items): 
    testsource = config.getoption("--testsource") 
    if not testsource: 
        return 
 
    my_tests = [] 
    with open(testsource) as ts: 
        my_tests = list(map(lambda x: x.strip(),ts.readlines())) 
 
    selected = [] 
    deselected = [] 
    for item in items: 
        deselected.append(item) if item.name not in my_tests else selected.append(item) 
 
    if deselected: 
        config.hook.pytest_deselected(items=deselected) 
        items[:] = selected 
    print('Deselected: {}'.format(deselected)) 
    print('Selected: {}'.format(items)) 
$  

执行输出

$ py.test -vs --testsource my_tests 
Test session starts (platform: linux, Python 3.5.1, pytest 2.8.7, pytest-sugar 0.5.1) 
cachedir: .cache 
rootdir: /home/sharad/tmp, inifile:  
plugins: cov-2.2.1, timeout-1.0.0, sugar-0.5.1, json-0.4.0, html-1.8.0, spec-1.0.1 
Deselected: [<Function 'test_003'>] 
Selected: [<Function 'test_001'>, <Function 'test_001'>, <Function 'test_002'>] 
 
 test_bar.pytest_001 ✓                                                                                                                                                                                33% ███▍       
 test_foo.pytest_001 ✓                                                                                                                                                                                67% ██████▋    
 test_foo.pytest_002 ✓                                                                                                                                                                               100% ██████████ 
 
Results (0.05s): 
       3 passed 
       1 deselected 
$