2016-06-09 57 views
2

我知道我可以用下面的命令指定一個測試在PyTest中運行:我可以在PyTest中顯式指定多個測試嗎?

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

有沒有辦法顯式指定多個測試運行,而無需運行所有的測試?

我可以在for循環中運行py.test命令,每次指定一個不同的測試,但有沒有更好的解決方案?

回答

2

你可以把你的測試放在一個文件中,實現修飾符鉤子來根據它們是否存在於文件中來過濾要執行的測試。下面是一個例子:含有

測試文件#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 
$ 

修飾符鉤

$ 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 
$ 
相關問題