Test case execution order in pytest

↘锁芯ラ 提交于 2019-11-27 05:14:15
Frank T

In general you can configure the behavior of basically any part of pytest using its well-specified hooks.

In your case, you want the "pytest_collection_modifyitems" hook, which lets you re-order collected tests in place.

That said, it does seem like ordering your tests should be easier -- this is Python after all! So I wrote a plugin for ordering tests: "pytest-ordering". Check out the docs or install it from pypi. Right now I recommend using @pytest.mark.first and @pytest.mark.second, or one of the @pytest.mark.order# markers, but I have some ideas about more useful APIs. Suggestions welcome :)

It looks like pytest runs tests in alphabetical order. So you can try this way:

def test_a_first_test():
    pass

def test_b_second_test():
    pass

def test_o_middle_test():
    pass

There's also a plugin pytest-ordering that seems to meet your requirements.

Maybe you can consider using dependency pytest plugin, where you can set the test dependencies easily:

@pytest.mark.dependency()
def test_long():
    pass

@pytest.mark.dependency(depends=['test_long'])
def test_short():
    pass

This way test_short will only execute if test_long is success and force the execution sequence as well.

Ali Zwd

Try this:

@pytest.fixture(xxx)
def test_A():
    pass
    yield
    pass

@pytest.mark.usefixtures('test_A')
def test_B():
    pass

main.py:

import functools
import pytest
from demo import test_foo,test_hi

def check_depends(depends):
    try:
        for dep in depends:
            dep()
    except Exception as e:
        return dep
    else:
        return True

def pytest_depend(depends):
    def pytest_depend_decorator(func):
        stat = check_depends(depends)
        if stat is True:
            return func
        else:
            return pytest.mark.skip(True, reason="%s[skip] --> %s[Failed]" % (func.__name__, stat.__name__))(func)
    return pytest_depend_decorator


@pytest_depend([test_foo,test_hi])
def test_bar():
    pass

@pytest_depend([test_foo,test_hi])
def test_bar2():
    pass

demo.py:

def test_hi():
    pass
def test_foo():
    assert False

platform linux -- Python 3.5.2, pytest-3.8.2, py-1.6.0, pluggy-0.7.1 -- /usr/bin/python3

pytest -vrsx ./plugin.py

Make Sure you have installed pytest-ordering package. To confirm go to Pycharm settings>>Project Interpreter >> and look for pytest-ordering : If it is not available install it. Pycharm settings>>Project Interpreter >> Click on + button and search pytest-ordering install it. Voila!! It will definitely work.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!