如何在使用metafunc添加的测试中添加标记?

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年8月10日 16:22:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定