pytest接口测试(五)parametrize参数化

pytest接口测试(五)parametrize参数化

parametrize装饰器

pytest.mark.parametrize装饰器可以实现用例参数化,里面写两个参数

  • 第1个参数是字符串,多个参数中间用逗号隔开
  • 第2个参数是list,多组数组用元组类型

1、以下是一个实现一定输入和期望输出测试功能的典型例子

import pytest

@pytest.mark.parametrize('test_input, expected', [('3+5', 8), ('4-1',3), ('4*5', 27)])
def test_demo(test_input, expected):
    assert eval(test_input) == expected   # 因为'3+5'是一个字符串,需要用eval方法将其转为原本格式,即整数相加
'''
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.6.6, pytest-4.5.0, py-1.8.0, pluggy-0.13.1
rootdir: F:\python work\youyou_class\study_pytest\class_11collected 3 items

test_parametrize.py ..F
test_parametrize.py:7 (test_demo[4*5-27])
20 != 27

Expected :27
Actual   :20
 <Click to see difference>

test_input = '4*5', expected = 27

    @pytest.mark.parametrize('test_input, expected', [('3+5', 8), ('4-1',3), ('4*5', 27)])
    def test_demo(test_input, expected):
>       assert eval(test_input) == expected   # 因为'3+5'是一个字符串,需要用eval方法将其转为原本格式,即整数相加
E       AssertionError: assert 20 == 27
E        +  where 20 = eval('4*5')
'''

2、多个输入参数和期望结果

import pytest
from study_pytest.class_10.login import login

@pytest.mark.parametrize('test_input, expected', [
    ({'name':'test','password':'123456'},{"msg":"login success!","code":0}),
    ({'name':'xxxyyy','password':'123456'},{"msg":"账号或密码不正确","code":3003})
])
def test_login(test_input, expected):
    name = test_input['name']
    pwd = test_input['password']
    re = login(name, pwd)
    assert re[0]['msg'] == expected['msg']
    assert re[0]['code'] == expected['code']

3、参数组合

参数组合,适用于多组输入得到一个测试结果的情况。

@pytest.mark.parametrize('x', [0, -1, -6])
@pytest.mark.parametrize('y', [-6, -2, -1])

def test_demo(x, y):
    expected = 0
    assert x + y < expected
'''
============================= test session starts =============================
platform win32 -- Python 3.6.6, pytest-4.5.0, py-1.8.0, pluggy-0.13.1
rootdir: F:\python work\youyou_class\study_pytest\class_11collected 9 items

test_parametrize.py .........                                            [100%]

========================== 9 passed in 0.14 seconds ===========================
'''

4、用例阻塞(已提交bug但未解决)

@pytest.mark.skip(‘阻塞bug’)
标记后,此条用例自动跳过不会被执行

5、mark标记

@pytest.mark.appapi
标记后,在命令行输入:pytest xxxx.py -m appapi
只会执行appapi标记的测试用例

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值