首页 > 其他 > 详细

pytest之fixture初识

时间:2021-03-17 17:22:30      阅读:24      评论:0      收藏:0      [点我收藏+]

简介:

前面我们说到过setup和teardown系列可以作为测试用例的前后置操作。
对于pytest,提供了更为灵活的前后置操作:fixture
我们先看一个最简单的例子:

文件:test_a.py

import
pytest def test_1(login): assert 3 == 3 print("this is test_1") class TestA(object): def test_a(self, login): assert 1 == 1 print("this is test_a") def test_b(self): assert 2 == 2 print("this is test_b")
文件:conftest.py

import
pytest @pytest.fixture(scope="function") def login(): print("this is login ")

上例中,有一个test_a.py文件,里面有测试函数,测试类(类中有测试方法),还有一个conftest.py文件,里面有一个被@pytest.fixture()装饰的函数,这样
这个函数就成为了一个前置函数。
运行结果如下:

test_a.py::test_1
this is login 
PASSED                                                
                                 [ 33%]
this is test_1

test_a.py::TestA::test_a 
this is login 
PASSED                                         
                                 [ 66%]
this is test_a

test_a.py::TestA::test_b 
PASSED                                          
                                 [100%]
this is test_b        

我们可以看到:
测试函数test_1由于传入了前置函数名login,在其执行前执行了login函数。
测试方法test_a由于传入了前置函数名login,在其执行前执行了login函数。
测试方法test_b没有传入前置函数名login,在其执行前未执行login函数。

从简单的例子中,我们可以看到,@pytest.fixture这种方法实现用例前置操作非常方便。

 

pytest之fixture初识

原文:https://www.cnblogs.com/ctltest/p/14538955.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!