gpt4 book ai didi

python - 如何在每次测试后用 pytest 重复测试?

转载 作者:行者123 更新时间:2023-11-28 21:22:04 26 4
gpt4 key购买 nike

我的测试用例很少,如下所述。但我想在每个其他测试用例之后重复 test1() 。我怎样才能做到这一点?

@pytest.mark.test1()
@pytest.mark.parametrize(a,b,c)
def test_test1():
......
......

@pytest.mark.test2()
def test_test2():
......
......

@pytest.mark.test3()
def test_test3():
......
......

run test1() again

最佳答案

您可以通过实现 pytest_collection_modifyitems 来修改要执行的测试列表钩。示例:在您的根目录中,创建一个名为 conftest.py 的文件并向其添加 Hook :

def pytest_collection_modifyitems(session, config, items):
test1s = [item for item in items if item.function.__name__ == 'test_test1']
items.extend(test1s)

现在 test_test1 将附加到已收集测试的列表中,执行两次:

$ pytest -v
============================= test session starts =============================
platform darwin -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-49213392, inifile:
plugins: celery-4.1.0, forked-0.2, cov-2.5.1, asyncio-0.8.0, xdist-1.22.0, mock-1.6.3, hypothesis-3.44.4
collected 5 items

test_spam.py::test_test1[a] PASSED [ 12%]
test_spam.py::test_test1[b] PASSED [ 25%]
test_spam.py::test_test1[c] PASSED [ 37%]
test_spam.py::test_test2 PASSED [ 50%]
test_spam.py::test_test3 PASSED [ 62%]
test_spam.py::test_test1[a] PASSED [ 62%]
test_spam.py::test_test1[b] PASSED [ 62%]
test_spam.py::test_test1[c] PASSED [ 62%]

========================== 8 passed in 0.02 seconds ===========================

一个更优雅的解决方案是使用自定义标记,我们将其命名为my_repeat:

@pytest.mark.my_repeat
@pytest.mark.parametrize(a,b,c)
def test_test1():
...

conftest.py 中的适配钩子(Hook):

def pytest_collection_modifyitems(session, config, items):
repeats = [item for item in items if item.get_marker('my_repeat')]
items.extend(repeats)

关于python - 如何在每次测试后用 pytest 重复测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49213392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com