pytest+allure+yaml接口自动化框架搭建

整理下整个接口自动化框架的思路
主要用到的插件:pytest,allure-pytest,yaml

项目框架:

在这里插入图片描述
思维导图:
在这里插入图片描述
开始搭建框架

第一步: Conf 配置

创建config.ini文件:根据需要来去设计类别和类别下的元素
在这里插入图片描述

创建和编写config.py 文件:自定义一些get,set,add方法,用来读取,编辑,添加配置文件中的数据

import configparser
from Common import Log
import os

proDir = os.path.split(os.path.realpath(__file__))[0]
configPath = os.path.join(proDir, "config.ini")


class Read_config:

    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read(configPath)

    def get_global(self, param):
        value = self.config.get('global_paras', param)
        return value

    def get_mail(self, param):
        value = self.config.get('mail', param)
        return value

    def get_database(self, param):
        value = self.config.get('database', param)
        return value

    def get_conf(self, section, param):
        value = self.config.get(section, param)
        return value

    def set_conf(self, section, value, text):
        """
        配置文件修改
        :param section:
        :param value:
        :param text:
        :return:
        """
        self.config.set(section, value, text)
        with open(configPath, "w+") as f:
            return self.config.write(f)

    def add_conf(self, section_name):
        """
        添加类别到配置环境里
        :param section_name:
        :return:
        """
        self.config.add_section(section_name)
        with open(configPath, "w+") as f:
            return self.config.write(f)

第二步:编写测试用例

安装插件:

pip install PyYAML

在这里插入图片描述
说明:

  • 创建测试用例.yaml : 里面的结构可以自由设计,只需要了解以下yaml文件的基本语法就好了

编写读取yaml文件的方法:将方法写在通用类Utils里面

import yaml

  def read_data_from_file(file_name):
        """
        读取yaml文件的内容
        :param file_name
        """
        f = open(rootPath + '/data/' + file_name, encoding='utf-8')
        res_json = yaml.load(f, Loader=yaml.FullLoader)  # 添加loader参数是为了去掉load warning
        return res_json

第三步:封装request和assertion方法

安装request插件:

pip install request

创建Customize_request: 请求前的数据处理自行设计,请求后,获取返回的body,耗时,状态码,放入到字典中,该方法返回一个字典

"""
封装request

"""

import requests
from Common import Token
from Common.Utils import Utils
from Conf import Config
from Common import Log


class Request(Utils):

    def __init__(self, env):
        """
        :param env:
        """
        self.env = env
        self.config = Config.Read_config()
        self.log = Log.MyLog()
        self.t = Token.Token()

    def post_request(self, url, data):
        """
        Post请求
        :param url:
        :param data:
        :return:

        """

        # post 请求
        try:
            response = requests.post(url=request_url, params=data)

        except Exception as e:
            print('%s%s' % ('Exception url: ', request_url))
            print(e)
            return ()

        # time_consuming为响应时间,单位为毫秒
        time_consuming = response.elapsed.microseconds / 1000
        # time_total为响应时间,单位为秒
        time_total = response.elapsed.total_seconds()

        response_dicts = dict()
        response_dicts['code'] = response.status_code
        try:
            response_dicts['body'] = response.json()
        except Exception as e:
            print(e)
            response_dicts['body'] = ''

        response_dicts['text'] = response.text
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total

        return response_dicts


创建Cutomize_assertion方法:

"""
封装Assert方法

"""
from Common import Log
import json
import traceback
from Conf import Config


class Assertions:
    def __init__(self):
        self.log = Log.MyLog()

    @staticmethod
    def assert_status_code(status_code, expected_code):
        """
        验证response状态码
        :param status_code:
        :param expected_code:
        :return:
        """
        try:
            assert status_code == expected_code
            return True

        except Exception:
            log_error(traceback.format_exc(), status_code, expected_code)
            raise

    @staticmethod
    def assert_single_item(single_item, expected_results):
        """
        验证response body中任意属性的值
        :param single_item:
        :param expected_results:
        :return:
        """
        try:
            assert single_item == expected_results
            return True

        except Exception:
            log_error(traceback.format_exc(), single_item, expected_results)
            raise

    @staticmethod
    def assert_in_text(body, expected_results):
        """
        验证response body中是否包含预期字符串
        :param body:
        :param expected_results:
        :return:
        """
        text = json.dumps(body, ensure_ascii=False)
要在Python中使用requests、pytestallureyaml、DDT和logs构建接口自动化框架,并将环境配置成自己的,可以按照以下步骤进行: ### 1. 安装必要的库 首先,确保安装了必要的Python库。你可以使用pip来安装这些库: ```bash pip install requests pytest allure-pytest PyYAML ``` ### 2. 项目结构 创建一个项目目录,并按照以下结构组织文件: ``` project/ │ ├── tests/ │ ├── test_cases/ │ │ ├── test_example.py │ ├── conftest.py │ ├── data/ │ ├── test_data.yaml │ ├── utils/ │ ├── logger.py │ ├── request_utils.py │ ├── reports/ │ ├── config/ │ ├── config.yaml │ └── requirements.txt ``` ### 3. 配置环境 在`config/config.yaml`文件中配置环境变量: ```yaml base_url: "https://api.example.com" timeout: 10 ``` ### 4. 日志配置 在`utils/logger.py`中配置日志: ```python import logging import os def get_logger(): logger = logging.getLogger("api_logger") logger.setLevel(logging.DEBUG) if not logger.handlers: fh = logging.FileHandler("logs/api.log") fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) return logger ``` ### 5. 请求工具 在`utils/request_utils.py`中编写请求工具: ```python import requests from utils.logger import get_logger import yaml logger = get_logger() def send_request(method, url, **kwargs): response = requests.request(method, url, **kwargs) logger.info(f"Request: {method} {url} {kwargs}") logger.info(f"Response: {response.status_code} {response.text}") return response ``` ### 6. 测试用例 在`tests/test_cases/test_example.py`中编写测试用例: ```python import pytest import yaml from utils.request_utils import send_request @pytest.fixture(scope="module") def config(): with open("config/config.yaml", "r") as file: config = yaml.safe_load(file) return config def test_example(config): url = config["base_url"] + "/endpoint" response = send_request("GET", url) assert response.status_code == 200 ``` ### 7. 运行测试 使用pytest运行测试,并生成Allure报告: ```bash pytest --alluredir=reports allure serve reports ``` ### 8. 数据驱动 使用DDT进行数据驱动测试。在`tests/test_cases/test_ddt_example.py`中: ```python import pytest import yaml from utils.request_utils import send_request @pytest.fixture(scope="module") def config(): with open("config/config.yaml", "r") as file: config = yaml.safe_load(file) return config @pytest.mark.parametrize("data", yaml.safe_load(open("data/test_data.yaml", "r"))) def test_ddt_example(config, data): url = config["base_url"] + "/endpoint" response = send_request("POST", url, json=data) assert response.status_code == 200 ``` ### 9. 报告生成 Allure会生成详细的测试报告,可以通过浏览器查看。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值