san*_*o98 12 python testing unit-testing pytest pytest-markers
我用于@pytest.mark唯一地标识特定测试,因此我创建了自定义标记。
@pytest.mark.key
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
@pytest.mark.key("test-001")
def test_simple(self):
self.passing_step()
self.passing_step()
self.passing_step()
self.passing_step()
assert True
Run Code Online (Sandbox Code Playgroud)
现在,我想从控制台运行带有标记键“test-001”的所有测试。我怎样才能实现这个目标?
我正在寻找的是这样的:
pypi.org/project/pytest-jira/0.3.6
Run Code Online (Sandbox Code Playgroud)
其中测试可以映射到 Jira 键。我查看了链接的源代码,但我不确定如何实现它以便我运行特定的测试。假设我只想使用键“test-001”运行测试。
MrB*_*men 11
Pytest 不提供开箱即用的功能。您可以使用选项按标记名称-m进行过滤,但不能按标记属性进行过滤。
不过,您可以添加自己的选项来按键进行过滤。这是一个例子:
测试.py
def pytest_configure(config):
# register your new marker to avoid warnings
config.addinivalue_line(
"markers",
"key: specify a test key"
)
def pytest_addoption(parser):
# add your new filter option (you can name it whatever you want)
parser.addoption('--key', action='store')
def pytest_collection_modifyitems(config, items):
# check if you got an option like --key=test-001
filter = config.getoption("--key")
if filter:
new_items = []
for item in items:
mark = item.get_closest_marker("key")
if mark and mark.args and mark.args[0] == filter:
# collect all items that have a key marker with that value
new_items.append(item)
items[:] = new_items
Run Code Online (Sandbox Code Playgroud)
现在你运行类似的东西
pytest --key=test-001
Run Code Online (Sandbox Code Playgroud)
仅运行具有该标记属性的测试。
请注意,这仍将显示收集的测试总数,但仅运行过滤后的测试。这是一个例子:
测试密钥.py
pytest --key=test-001
Run Code Online (Sandbox Code Playgroud)
$ python -m pytest -v --key=test-001 test_key.py
...
collected 4 items
test_key.py::test_simple1 PASSED
test_key.py::test_simple3 PASSED
================================================== 2 passed in 0.26s ==================================================
Run Code Online (Sandbox Code Playgroud)
你可以使用pytest选项-mc运行
检查以下命令:
pytest -m 'test-001' <your test file>
Run Code Online (Sandbox Code Playgroud)