如何要求 Pytest 在 python 脚本中运行特定测试?

Chi*_*ala 3 pytest python-3.x

如果我在脚本中运行多个测试,例如:

import pytest

@pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8),
    ("2+4", 6),
    ("6*9", 42),
])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

@pytest.mark.parametrize('test_input,expected', [
        (1,1),
        (2,2),
        (2,3),
        ])
def test_equal(test_input,expected):
    assert test_input == expected


if __name__ == '__main__':
    '''
    Test Zone!
    '''
    #executing the tests
    pytest.main([__file__]) 
Run Code Online (Sandbox Code Playgroud)

如何使用最后一行pytest.main([__file__])一次运行一个测试,而不是一次运行所有测试?

eij*_*jen 5

根据 pytest文档,使用pytest.main()类似于从命令行调用 pytest 的行为。您可以向其传递命令和参数,从而允许您使用-k标志通过关键字表达式指定测试:

pytest.main(["-k", "test_func"])
Run Code Online (Sandbox Code Playgroud)

您还可以通过节点 id指定测试:

pytest.main(["test_mod.py::test_func"])
Run Code Online (Sandbox Code Playgroud)