简体   繁体   English

添加自定义 pytest 标记以根据输入跳过测试

[英]Adding custom pytest marker to skip test based on input

I would like to add a custom pytest marker which skips a test whenever a specific file is found in the directory:我想添加一个自定义 pytest 标记,只要在目录中找到特定文件,它就会跳过测试:

@pytest.mark.file_exists("my_file.txt")
def test_mytest():
    assert True

I want test_mytest to execute only when "my_file.txt" is in the root directory.我希望test_mytest仅在“my_file.txt”位于根目录中时执行。 The documentation specifies how to register a custom marker, but not how to define its behavior.该文档指定了如何注册自定义标记,但没有指定如何定义其行为。 How would I define the behavior of file_exists ?我将如何定义file_exists的行为? Any help is appreciated.任何帮助表示赞赏。

The logic must be implemented in pytest_runtest_setup, you must also declare for example in pytest_configure.逻辑必须在 pytest_runtest_setup 中实现,您还必须在例如 pytest_configure 中声明。 For more information check https://docs.pytest.org/en/stable/how-to/mark.html :有关更多信息,请查看https://docs.pytest.org/en/stable/how-to/mark.html

conftest.py conftest.py

from pathlib import Path

import pytest


def pytest_configure(config):
    config.addinivalue_line("markers", "file_exists(filename): description")


def pytest_runtest_setup(item):
    filenames = [mark.args[0] for mark in item.iter_markers(name="file_exists")]
    package_dir = Path(__file__).parent

    for filename in filenames:
        path = package_dir / filename
        if not path.is_file():
            pytest.skip("test requires {!r}".format(filename))
            return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM