浅谈自己公司搭建的Python接口自动化框架

框架结构

allure-report(生成的allure测试报告的保存目录)
config(项目的一些基本配置)
data(保存数据驱动的用例文件)
log(日志)
testcase(测试用例逻辑)
tool(所需要的一些驱动工具脚本)
pytest.ini(pytest的初始化文件)
requirements.txt(依赖文件)

具体文件说明

allure-report

这个文件不用管,是allure测试报告自动生成的,文件名称可以在config中自定义

config

配置一些项目的域名基本配置和登录token的用户名密码

[config]
base_url:https://www.baidu.com
username:name
password:password

data

此处用的是excel文件存储测试用例数据的,例如:
Alt

log

存储日志文件

testcase

conftest.py 通用的token存储文件,所有接口需要使用token的要写在下方,此文件夹名称不能变,且只能放在与用例逻辑在同一个目录下。

import logging
import traceback
import pytest
import requests
from tool.read_ini import ReadConfig
base_url = ReadConfig().read_conf().get('config', 'base_url')
username = ReadConfig().read_conf().get('config', 'username')
password = ReadConfig().read_conf().get('config', 'password')


"""
如果用例执行前需要先登录获取token值,就要用到conftest.py文件了
作用:conftest.py 配置里可以实现数据共享,不需要import导入 conftest.py,pytest用例会自动查找
scope参数为session,那么所有的测试文件执行前执行一次
scope参数为module,那么每一个测试文件执行前都会执行一次conftest文件中的fixture
scope参数为class,那么每一个测试文件中的测试类执行前都会执行一次conftest文件中的fixture
scope参数为function,那么所有文件的测试用例执行前都会执行一次conftest文件中的fixture


"""


# 获取到登录请求返回的ticket值,@pytest.fixture装饰后,testcase文件中直接使用函数名"login_ticket"即可得到ticket值
@pytest.fixture(scope="session")
def login_token():
    params = {"username": username, "password": password, "grant_type": "password", "client_id": "wsngt-h5", "client_secret": "wsngt-h5"}
    url = base_url + 'oauth/token'
    logging.info('开始调用登录接口:{}'.format(url))
    requests.packages.urllib3.disable_warnings()
    res = requests.post(url, data=params, verify=False)  # verify:忽略https的认证
    try:
        token = res.json()['access_token']
    except Exception as ex:
        logging.error('登录失败!接口返回:{}'.format(res.text))
        traceback.print_tb(ex)
    logging.info('登录成功,ticket值为:{}'.format(token))
    return token

用例逻辑

import pytest
from tool.create_log import logger
from tool.read_excel import read_excel
import requests
import json
from tool.read_ini import ReadConfig
base_url = ReadConfig().read_conf().get('config', 'base_url')



class TestLogin:
    # 登录
    @pytest.mark.parametrize('data_id, url, method, params, code, msg',read_excel('oauth/token'))# 数据驱动
    def test_login(self, data_id, url, method, params, code, msg):
        url = base_url + url
        res = requests.get(url=url, params=json.loads(params)).text
        logger.debug(f'发送请求{res}')
        assert msg in res

tool

create_log.py 日志生成

import logging
import os

logger = logging.getLogger('test_log')
logger.setLevel(logging.DEBUG)

format = logging.Formatter('[%(asctime)s] [%(levelname)s] [%(funcName)s] %(message)s')
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) # 上级目录

f = logging.FileHandler(filename=f'{path}/log/zwdh.log',mode='a',encoding='utf8')
f.setFormatter(format)
s = logging.StreamHandler()
s.setFormatter(format)

logger.addHandler(f)
logger.addHandler(s)

read_excel.py 读取excel文件

import xlrd


def read_excel(url):
    excel = xlrd.open_workbook('./data/test_params.xlsx', 'r', encoding_override='utf-8')
    sheets = excel.sheet_names()
    test_data = []
    for s in sheets:
        sheet = excel.sheet_by_name(s)
        for i in range(sheet.nrows):
            if i == 0:
                continue
            else:
                cmd = sheet.row_values(i)
                if cmd[1] != url:
                    continue
                # data_id, url, method, params, code, msg = cmd[0], cmd[1], cmd[2], cmd[3], cmd[4], cmd[5]
                # print(data_id, url, method, params, code, msg)
            test_data.append(cmd)
    return test_data

read_ini.py 读取项目基本配置文件

import configparser
import os

class ReadConfig:
    def read_conf(self):
        conf = configparser.ConfigParser()
        path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))  # 上级目录
        conf.read(f'{path}/config/config.ini', encoding='utf8')
        return conf

pytest.ini

pytest框架自带的初始化配置文件

[pytest]
testpaths=./testcase #执行用例目录
addopts=-v -s --alluredir=./allure-report --clean-alluredir #-v打印信息 -s详细信息 --alluredir生成报告存放目录 --clean-alluredir每次生成前先删除之前的报告

requirements.txt

生成的依赖文件,具体如何生成在另一篇博客有提到
链接: https://blog.csdn.net/Tommy_two/article/details/129925326

总结

博主也是在接口自动化的入口摸爬滚打自己摸索,这是我结合所学的知识自己写的一套接口自动化的框架,当中肯定还会有很多不足,也欢迎各位大佬指正!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值