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

一个人想着一个人 提交于 2019-11-28 05:17:55

 

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中。效果是一样的

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