菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
208
0

pytest-fixture 的使用

原创
05/13 14:22
阅读数 15866

 unittest 有自己的setup 和teardown 功能,起到前置处理和后续清理的作用  ,pytest 有自己的方法单独做这些工作 -----这就引入了fixture  

  1. 给函数打个标记 ,实现前置处理和后续清理的作用    @pytest.fixture  
  2. 如何使用这个函数呢  有三种方式  

           2.1函数名称作为参数传入

   2.2 使用usefixture (fixture 名称) 

 

1 import pytest
2 @pytest.fixture()
3 def before():
4     print('这是before')
5 
6 #第一种方法:把函数名称直接作为参数传入
7 def test_fun(before):
8     print('test_fun')
1 @pytest.mark.usefixtures('before')
2 def test_fun1():
3     print('test_fun1')

 

运行结果

 

注意:但是有的时候fixture 是需要有返回值的,那么就只能用传参的方式,这样才能接收返回值

 1 @pytest.fixture()
 2 def before_3():
 3     a=1
 4     b=2
 5     yield a,b
 6     c=3
 7     print('这是后置处理工作')
 8 
 9 def test_fun3(before_3):
10     print(before_3)
11     print(before_3[0])    
12     print('这里省略函数内部处理')

运行结果 

 

 2.3 使用auto=True      这种方法会对所有的test 函数起作用

1 @pytest.fixture(autouse=True)
2 def before_auto():
3     print('before_auto')
4 
5 def test_fun2():
6     print('test_fun2')

运行结果 

 

3.fixture 参数化     使用params 传入参数,在函数内部用request.param  接收参数 

1 @pytest.fixture(params=[2,3])
2 def before_2(request):
3     print('before_2')
4     print(request.param)
5 
6 
7 #@pytest.mark.usefixtures('before_2')
8 def test_fun3(before_2):
9     print('test_fun3')
 运行结果

 

发表评论

0/200
208 点赞
0 评论
收藏