pytest 用 @pytest.mark.usefixtures("fixtureName")或@pytest.fixture(scope="function", autouse=True)装饰,实现类似setup和TearDown的功能

conftest.py

import pytest

@pytest.fixture(scope="class")
def class_auto():
    print("")
    print("class-begin")
    yield
    print("class-end")

test_autouse.py

 1 import pytest
 2 
 3 
 4 @pytest.mark.usefixtures("class_auto")
 5 class TestClass(object):
 6 
 7     @pytest.fixture(scope="function", autouse=True)
 8     def funcion_auto(self):
 9         print("begin")
10         yield
11         print("end")
12 
13     def test_case1(self):
14         print("test_case1:")
15         assert 0 == 0
16 
17     def test_case2(self):
18         print("test_case2:")
19         assert 0 == 0

执行命令

pytest -s test_autouse.py

执行结果:

注意:

1.fixture中的yield需要注意,不能缺

2.上面conftest.py中的fixture,也可以放在test_autouse.py中。效果是一样的

原文地址:https://www.cnblogs.com/moonpool/p/11393661.html