欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python接口测试

程序员文章站 2022-06-04 16:22:01
...

干了4年左右测试,闲着没事干瞎写点最近项目的接口自动化测试,主要功能是把接口测试结果写入文件,并发送邮件,自己搭建了一个小框架,很简单,总共4个文件,将就着参考吧
思路:
1、配置邮件模板
2、写测试case
3、测试结果写入文件
4、发送邮件
我的项目结构是这样的,4个文件加一个txt报告
python接口测试
1、邮件模板:mail.py

from email.mime.text import MIMEText
import smtplib
import datetime
# from email.mime.multipart import MIMEMultipart
#读取测试结果文件
def read_file():
    path='C:\\test\\python_code\\api_test\\report\\report.txt'
    f=open(path,'rb')
    fp=f.read()
    f.close()
    return fp
#发送邮件
def send():
    smtpserver='smtp.qq.com'#邮件服务器
    sender = 'aaa@qq.com'  # 发件人邮箱
    pwd = 'xxxxxxx'  # 授权码
    receiver = ['aaa@qq.com','aaa@qq.com']  # 接收人邮箱
    subject=u'接口自动化测试报告'#邮件标题
    # 非附件邮件构造
    msg = MIMEText(read_file(), 'plain', 'utf-8')
    msg['From'] = sender
    msg['To'] = ','.join(receiver)
    msg['Subject'] = subject
    # 附件邮件构造
    # msg=MIMEMultipart()
    # msg.attach(MIMEText('邮件正文',_subtype='txt',_charset='utf-8'))
    # msg['From']=sender
    # msg['To']=receiver
    # msg['Subject']=subject
    # att=MIMEText(read_file(),'base64', 'utf-8')
    # att["Content-Type"] = 'application/octet-stream'
    # att.add_header("Content-Disposition", "attachment", filename='测试报告.txt')
    # msg.attach(att)

    # 发送邮件
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)  # 邮箱服务器
    smtp.login(sender, pwd)  # 登录邮箱
    smtp.sendmail(sender, receiver, msg.as_string())  # 发送者和接收者
    smtp.quit()
    print("邮件已发出!注意查收。"+str(datetime.datetime.now()))


2、写测试用例:api_case.py

import requests
import json
https = 'https://xxxxxxxxxxx.com.cn'
RT = []#总的测试结果
STATU_CODE = 200
# 测试结果集,这个函数保存单个用例的测试结果
def check_result(point, result, desc=None):
    return [point, result, desc]
#因为都是post请求,封装了post请求并判断测试结果
def post(url, data, point, headers=None):
    r = requests.post(url, json.dumps(data), headers)
    if r.status_code == STATU_CODE:
        RT.append(check_result(point, 'PASS', ''))
    else:
        RT.append(check_result(point, 'FAIL', '接口状态:{}' .format(r.status_code)))
    return RT
#下面是测试用例
# 国内机票用例
class CH_Tickets:
    def __init__(self):
        self.header = {
            'token': 'xxxxxxx'
        }
        self.fligh_search_url = https + '/v1/domestic-flight/fligh-search'  # 航班查询
        self.price_search_url = https + '/v1/domestic-flight/price-search'  # 航班价格查询
        self.order_list_url = https + '/v1/domestic-flight/order-list'  # 订单列表查询
        self.bk_url = https + '/v1/domestic-flight/bk'  # BK接口

    # 航班查询
    def fligh_search(self):
        data = {
            "data": {
                "dpt_airport": "",
                "arr_airport": "",
                '"price_sort': "asc"
            }
        }
        post(self.fligh_search_url,data,'国内航班查询')
    # 报价查询
    def price_search(self):
        data = {
            "data": {
                "dpt_code": "PEK",
                "dpt_date": "2019-09-24",
                "arr_code": "SHA",
                "flight_num": "MU5160",
            }
        }
        #直接调用post函数,结果自动保存到TR里面
        post(self.price_search_url,data,'国内航班报价查询')
    # 订单列表
    def order_list(self):
        data = {
            "data": {"page_index": 1,
                     "page_size": 20
                     }
        }
        post(self.order_list_url,data,'订单列表',self.header)

    # BK接口
    def flight_bk(self):
        data = {
            "data": {
                "policyId": "40625582",
                "policyType": "1",
                "wrapperId": "ttsgndm1114"
            }
        }
        post(self.bk_url,data,'国内机票BK接口',self.header)

# 国际机票用例
class Inter_Tickets:
    def __init__(self):
        # 航班查询url
        self.fligh_search_url = https + '/v1/inter-flight/flight-search'

    # 航班查询接口
    def inter_fligh_search(self):
        data = {
            "data": {
                "dpt_airport": "",
                "arr_airport": "",
                "cabin_leavel": ""
            }
        }
        post(self.fligh_search_url,data,'国际航班查询')

3、执行测试并把测试结果写入文件:write_file.py

from api_test import api_case
report_file='C:\\test\\python_code\\api_test\\report\\report.txt'
#执行测试用例
def run_result():
	#怎么批量执行用例,还没想到,目前笨办法,一个个执行
    inter = api_case.Inter_Tickets()
    ch = api_case.CH_Tickets()
    inter.inter_fligh_search()
    ch.fligh_search()
    ch.price_search()
    ch.order_list()
    ch.flight_bk()
#测试结果写入txt
def wirte_result():
    run_result()#调用执行用例函数
    total = len(api_case.RT)#用例总数
    pass_count = 0  # 成功用例数
    fail_count = 0  # 失败用例数
    for j in api_case.RT:
        for n in j:
            if n=='PASS':
                pass_count+=1
            elif n=='FAIL':
                fail_count+=1
    f = open(report_file, 'w', encoding='utf-8')
    #用例统计也写入文件
    f.writelines('总共执行用例:{0}'.format(total)+'\t'+'PASS:{0}'.format(pass_count)+'\t'+'FAIL:{0}'.format(fail_count)+'\n\n')
    for i in api_case.RT:
        f.writelines(str(i) + '\n')
    f.close()

4、发送邮件:send_mail.py
判断测试结果是否有fail的,如果有,则发送邮件报告,并中断代码,如果没有,不发送报告,我加了一个定时执行用例,代码放到服务器,可以每隔2个小时执行一次用例,如果没有fail的,会一直循环下去,并打印次数

from api_test import write_file
from api_test import api_case
from api_test import mail
import time
# import os
def rt_data():
    i = 0
    # suc_report = 'C:\\test\\python_code\\api_test\\report\\suc_report.txt'
    while True:
        write_file.wirte_result()
        i+=1
        if api_case.RT:
            for j in api_case.RT:
                for n in j:
                    if 'FAIL' in n:
                        mail.send()
                        return
        else:
            return '测试报告为空'
        api_case.RT=[]#每次用例执行完rt置为空,不然每次测试结果会不清空而追加到后面
        print(str(i)+'、'+'第'+str(i)+'遍测试结果正常,邮件未发送!')#打印这句话
        # if os.path.exists(suc_report):# 判断文件是否存在,存在就删除
        #     os.remove(suc_report)
        # f = open(suc_report, 'a+', encoding='utf-8')
        # f.writelines(str(i)+'、'+'邮件未发送,测试结果正常!' + '\n')#这句话写入文件
        # f.close()
        time.sleep(7200)
rt_data()#调用一下

发邮件的测试结果
python接口测试
测试结果没有失败的,不发送邮件
python接口测试
第一次写博客,写的不好,将就看吧,这框架写的有点乱,没仔细规划,因为着急用,就想到哪写到哪,有好的方法欢迎交流