英文:
How to add marks to tests added using metafunc?
问题
然而,我的一些测试失败了。因此,我想将其中一些标记为xfail。我该如何做到这一点?
英文:
I have some code that generates one test for each .yaml file in a folder.
def pytest_generate_tests(metafunc):
    if "yamlpath" in metafunc.fixturenames:
        files = []
        names = []
        for filename in os.listdir(YAML_FILES_FOLDER):
            if filename.endswith('.yaml') or filename.endswith('.yml'):
                testname = filename.split('.')[0]
                files.append(YAML_FILES_FOLDER / filename)
                names.append(testname)
        metafunc.parametrize("yamlpath", files, ids=names)
However, a few of my tests are failing. Therefore, I would like to mark some of them as xfail. How can I do this?
答案1
得分: 1
一种方法是向您的测试函数添加一个额外的参数,表示测试预期失败,然后在测试的开头添加一个分支:
if fails:
    pytest.xfail()
然后在生成测试时传递 fails 参数。
我创建了一个更简单的示例,只是检查一个数字是否为偶数:
# conftest.py
def pytest_generate_tests(metafunc):
    if "number" in metafunc.fixturenames:
        names = ["number", "fails"]
        values = []
        for i in range(1, 3):
            values.append([i, not (i % 2 == 0)])
        metafunc.parametrize(names, values)
# test_1.py
import pytest
@pytest.fixture
def number():
    pass
def test_1(number, fails):
    if fails:
        pytest.xfail(reason="Should fail")
    assert number % 2 == 0
def test_2():
    assert True
def test_3():
    assert False
这应该适用于大多数其他标记,因为它们中的大多数似乎都有等效的函数。
英文:
One way could do it is add one more parameter to your test function that indicates that the test is expected to fail and then you add a
if fails:
    pytest.xfail()
branch to the start of the test to mark the test using code. You then pass the fails argument when generating tests.
I made a simpler example with where I just check if a number is even
# conftest.py
def pytest_generate_tests(metafunc):
    if "number" in metafunc.fixturenames:
        names = ["number", "fails"]
        values = []
        for i in range(1, 3):
            values.append([i, not (i % 2 == 0)])
        metafunc.parametrize(names, values)
# test_1.py
import pytest
@pytest.fixture
def number():
    pass
def test_1(number, fails):
    if fails:
        pytest.xfail(reason="Should fail")
    assert number % 2 == 0
def test_2():
    assert True
def test_3():
    assert False
This should work for most other marks as well, since most of them seem to have an equivalent function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论