pytest 中fixture传递参数到case中

2022-08-25 13:39:38 浏览数 (1)

fixture结合yield可以完美的替代setup和teardown,并且使用例更加简洁。

代码语言:javascript复制
import pytest

#pytest中利用fixture完成setup和teardown,测试用例中常常需要传递参数到case中,yeild返回参数即可
class Test_pro():
    @pytest.fixture()
    def init_project(self):
        print("set up")
        project_id = 123
        yield project_id
        print("teardown")
    def test_pro(self,init_project):
        print(init_project)
#返回多个参数时怎么处理? yield 多个参数返回时是以元组的形式(123, 999),通过下标index访问即可
class Test_pro1():
    @pytest.fixture()
    def init_project(self):
        print("set up")
        project_id = 123
        project_id2 = 999
        yield project_id,project_id2
        print("teardown")
    def test_pro(self,init_project):
        print(init_project)
        print(init_project[0])
============================== 1 passed in 0.01s ===============================
Process finished with exit code 0
set up
PASSED                                    [100%](123, 999)
123
teardown

0 人点赞