python+requests+excel+pytest+allure接口自动化框架搭建

文章目录

今天整理了一下之前搭建的接口自动化框架,本项目是由python+requests+excel+pytest+allure框架构成的,针对于工作中项目搭建的。

提示:本项目通过excel编写接口测试用例,使用openpyxl库获取excel数据,封装请求方式,通过requests库发送http协议请求,使用pytest管理测试用例,生成allure报告,通过jenkins构建并定时执行脚本。



提示:以下是本篇文章正文内容,下面案例可供参考

一、项目框架

在这里插入图片描述

Common层:
1、封装requests请求方法
2、读取excel
3、封装日志
4、封装数据库
5、数据处理
6、读取配置文件
7、获取路径

conf层
1、将一些数据写入配置文件中
Output层
1、输出测试报告和日志
Test_case层
1、conftest.py文件
2、测试用例
Test_data层
1、测试数据
main
执行
pytest.ini
1、pytest.ini配置文件

二、请求方法封装

代码如下(示例):

def send_request(method,url,datas=None):
    if method == "post" or method == "POST":
        res=requests.post(url,params=data,headers=header)
    elif method == "get" or method == "GET":
        res=requests.get(url,params=data,headers=header)
    elif method == "put" or method == "PUT":
        res=requests.put(url,params=data,headers=header)
    elif method == "delete" or method == "DELETE":
        res=requests.delete(url,params=data)
    else:
        res=None
    return res

2.日志封装

代码如下(示例):

class Handel_logger(logging.Logger):

    def __init__(self, filename=None):
        '''
        先设置收集器,读取日志级别
        :param filename: 输出渠道--文件
        '''
        #设置收集器
        log_name=conf.get("log","log_name")
        # 设置日志级别
        log_level = conf.get("log", "log_level")
        super().__init__(log_name,log_level)

        #设置输出格式:
        fmt=' %(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d: %(message)s'
        formatter=logging.Formatter(fmt)
        # 设置输出渠道---控制台
        console = logging.StreamHandler()
        #将日志格式绑定到输出渠道中
        console.setFormatter(formatter)
        #将输出渠道添加到日志收集器中
        self.addHandler(console)
        #判断是否要将日志输出到日志文件
        if filename:
            # 设置输出渠道---控制台
            output_file = logging.FileHandler(filename,encoding="utf-8")
            output_file.setFormatter(formatter)
            self.addHandler(output_file)

3.配置文件

[log]
log_name = loggers.log
log_level = INFO
log_file = xxx

[case_data]
url = http://xxx/
mobile = xxx
password = xxx

[mysql]
host = xxx
port = xxx
user = xxx
password = xxx
database = xxx
charset = utf8

4.数据库的封装

class Handle_db:

    def __init__(self):
        '''
        初始化:连接数据库
        步骤:1、连接数据库
             2、创建游标
             3、获取数据库数据
             4、关闭数据库
        host:
        port:
        user:
        password:
        databases:
        charset:
        cursorclass:
        '''
        self.conn=pymysql.connect(
            host=conf.get("xxx","xxx"),
            port=conf.get("xxx","xxx"),
            user=conf.get("xxx","xxx"),
            password=conf.get("xxx","xxx"),
            database=conf.get("xxx","xxx"),
            charset=conf.get("xxx","xxx"),
            cursorclass=pymysql.cursors.DictCursor

        )

        #创建数据库游标
        self.cur=self.conn.cursor()
    #获取结果次数
    def get_count(self,sql):
        self.conn.commit()
        count=self.cur.execute(sql)
        return count
    #获取一条结果
    def get_onedata(self,sql):
        self.conn.commit()
        self.cur.execute(sql)
        return self.cur.fetchone()

    #获取所有结果
    def get_alldata(self,sql):
        self.conn.commit()
        self.cur.execute(sql)
        return self.cur.fetchall()
    #更新数据库
    def updata(self,sql):
        try:
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            raise

    #关闭数据库
    def close_db(self):
        self.cur.close()
        self.conn.close()

5.编写测试用例脚本

@pytest.mark.usefixtures("init")
class Test_login:
    @pytest.mark.parametrize("case",cases)
    def test_login(self,case):
        res=send_request(case["method"],case["url"],case["request_data"])
        expect=json.loads(case["expect"])
        logger.info("响应结果为:{}".format(res.json()))
        logger.info("期望结果为:{}".format(expect))
        if case["expect"]:
            try:
                assert res.json()["code"]==expect["code"]
                assert res.json()["msg"] == expect["msg"]
            except Exception as e:
                logger.info("断言失败")
                raise
            return res

6.执行脚本

import pytest

pytest.main(["-s",
             "-v",
             "-m","sign",
             "--html=pyreports.html",
             "--alluredir=allure_dir",
             "--reruns","2","--reruns-delay","5"])

## 7.allure

在这里插入图片描述

总结

提示:其余内容涉及项目暂不展示

  • 2
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Python是一种广泛使用的编程语言,因其易学易用、灵活性和可扩展性而备受欢迎。requestsPython的一个库,它提供了一种简单且易于使用的方式来发送HTTP请求。pytestPython的另一个库,它提供了一种用于编写和运行测试的框架allure是一个测试报告生成工具,可以为测试结果提供美观和易读的报告。 在接口自动化测试中,可以使用Pythonrequests库来发送HTTP请求,并使用pytest框架来编写和运行测试。可以使用Excel来存储测试数据、预期结果和实际结果。使用allure工具可以生成美观的测试报告。 以下是使用Python requestspytestallure进行接口自动化测试的一般步骤: 1. 安装Pythonrequestspytestallure 2. 创建一个Excel文件,输入测试数据、预期结果和实际结果 3. 创建一个pytest测试文件,并使用requests库发送HTTP请求,比较预期结果和实际结果 4. 在pytest测试文件中添加allure装饰器,以便生成测试报告 5. 运行pytest测试文件并生成allure测试报告 例如,以下是一个使用Python requestspytestallure进行接口自动化测试的示例代码: ```python import requests import pytest import allure import openpyxl @allure.title("测试接口") @pytest.mark.parametrize("test_input, expected", [(1, "success"), (2, "fail")]) def test_api(test_input, expected): # 从Excel文件中获取测试数据和预期结果 wb = openpyxl.load_workbook("testdata.xlsx") sheet = wb.active test_data = sheet.cell(row=test_input, column=1).value expected_result = sheet.cell(row=test_input, column=2).value # 发送HTTP请求 response = requests.get("http://example.com/api", params=test_data) actual_result = response.text # 比较预期结果和实际结果 assert actual_result == expected_result, f"预期结果:{expected_result},实际结果:{actual_result}" # 添加allure描述 allure.attach("请求参数", str(test_data)) allure.attach("预期结果", str(expected_result)) allure.attach("实际结果", str(actual_result)) ``` 在上面的代码中,使用了pytest的parametrize装饰器来传递测试数据和预期结果。使用openpyxl库从Excel文件中获取测试数据和预期结果。使用requests库发送HTTP请求并比较预期结果和实际结果。使用allure的装饰器来添加测试描述。最后,运行pytest测试文件并生成allure测试报告。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姑娘别秃头

你的鼓励是为我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值