用python实现接口测试自动化(使用pytest、requests)

import pytest
import requests
import json
import hashlib
import random
import webbrowser

#@pytest.fixture装饰器传递测试数据,函数间传递
@pytest.fixture(scope='function')
#不以test_开头,不作为用例
def a():
    #生成一个1234567到9999999之间的随机数并转换成字符串
    rand = str(random.randrange(1234567,9999999))
    #拼接需要md5加密的字符串,指定编码是utf-8,转换成字节
    md5_1 = bytes(rand + 'XX',encoding='utf-8')
    #md5加密,要求传入的是字节,hexdigest十六进制
    sign = hashlib.md5(md5_1).hexdigest()
    #拼接url
    url = 'url?sign='+sign+'&randomStr='+rand
    print(url)
    #用浏览器打开url
    webbrowser.open(url,new=0)
    #函数返回传递给下一个函数
    return rand

#@pytest.mark.parametrize装饰器实现参数化,@pytest.mark.parametrize(元组,列表)元组指明变量名,列表为变量值
@pytest.mark.parametrize(('communityId','companyId','visitTime'),[('14336334','52','2020-05-18'),('14336334','78','2020-05-19')])
#a为a()的返回
def test_b(a,communityId,companyId,visitTime):

    visitors = """[{"name": "新注册账号", "phone": "16020002021", "idcard": "610321199208245019",
                    "idcardPic": "文件服务器url.png"}]"""
    #加密
    md5_m = bytes(communityId + companyId + visitTime + visitors,encoding='utf-8')
    m = hashlib.md5(md5_m).hexdigest()
    #指定url
    url = 'url'
    #指定data
    data = {
        'communityId': communityId,
        'companyId': companyId,
        'visitTime': visitTime,
        'visitors': visitors,
        'sign': m,
        'randomStr': a,
    }
    print(data)
    #使用requests模块发送post请求
    req = requests.post(url,data)
    #打印返回
    print(req.json())
    #断言,判断结果是否正确
    assert req.json()['status'] == 200
    assert req.json()['data']['visitors'][0]['phone'] == '16020002021'

def test_c(a):
    print(a)

#通过main方法运行测试
if __name__ == '__main__':
    pytest.main(['-s','./test_case'])
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页