自动化测试框架pytest+requests+allure

Pytest +requests+ Allure

这个框架基于python的的 Pytest 进行测试执行,并结合 Allure插件 生成测试报告的测试框架。采用 关键字驱动 方式,使测试用例更加清晰、模块化,同时支持 YAML 文件来管理测试用例,方便维护和扩展。

测试用例:YAML 文件

主要包含测试用例的步骤、调用的函数、函数所需的参数。


分层结构

  • config 层:全局配置(base_url、公共变量)。
  • steps 层:测试步骤(请求 -> 提取 -> 断言)。

模板引擎

  • 支持 {{}} 变量插值语法。
  • 支持环境变量注入(${ENV_VAR})。

示例:登录失败测试用例(用户名为空)

desc: 登录失败测试用例--用户名为空
steps:
  - 发送Post请求:
      关键字: request_post_form_data
      URL: "{{url}}"
      PARAMS:
        s: /api/user/login
        application: app
      DATA:
        accounts: ''
        pwd: 123456
        type: username
  - 通过JSONPATH提取数据-MSG:
      关键字: ex_jsonData
      EXVALUE: $..msg
      INDEX: 0
      VARNAME: msg_success
  - 断言-文本断言-等于:
      关键字: assert_text_comparators
      VALUE: "{{msg_success}}"
      EXPECTED: 登录账号不能为空
      OP_STR: ==

关键字驱动模式(封装 Keywords 函数)

Keywords 类封装了 YAML 文件中定义的请求关键字,并在执行步骤时,将有用的信息(如 tokenresponse)存入全局字典 gc,同时,每个方法都使用 @allure.step 装饰器,以生成测试报告的步骤。

关键字实现示例

class Keywords:
    @allure.step('发送POST请求')
    def request_post(self, **kwargs):
        response = requests.post(**kwargs)
        gc.set_dict('current_response', response)
        return response

    @allure.step('发送GET请求')
    def request_get(self, **kwargs):
        response = requests.get(**kwargs)
        gc.set_dict('current_response', response)
        return response

    @allure.step('发送PUT请求')
    def request_put(self, **kwargs):
        response = requests.put(**kwargs)
        gc.set_dict('current_response', response)
        return response

    @allure.step('发送POST请求--form_data表单的请求')
    def request_post_form_data(self, **kwargs):
        url = kwargs.get('URL', None)
        params = kwargs.get('PARAMS', None)
        data = kwargs.get('DATA', None)
        headers = kwargs.get('HEADERS', None)
        request_data = {'url': url, 'params': params, 'data': data, 'headers': headers}
        response = self.request_post(**request_data)
        return response

Pytest 框架入口

import os
import pytest

pytest_args = [
    '-v', '-s', '--capture=sys', '--clean-alluredir', '--alluredir=allure-results',
    '--type=yaml', '--cases=./data/yaml_testcase', './core/ApiTestRunner.py'
]
pytest.main(pytest_args)

使用 pytest.main 函数,同时指定运行参数,包括 Allure 测试报告数据目录和运行的 py 脚本。


用例运行脚本

class TestRunner:
    def test_case_execute(self, get_dict_token, caseinfo):
        try:
            allure.dynamic.title(caseinfo['_case_name'])  # 自定义用例标题
            local_context = caseinfo.get('context', {})
            kw = Keywords()
            
            # 解析测试用例步骤
            steps = caseinfo.get('steps', None)
            for step in steps:
                step_name = list(step.keys())[0]
                step_value = list(step.values())[0]
                
                context = copy.deepcopy(g_context().show_dic())
                context.update(local_context)
                step_value = eval(ReFresh(step_value, context))
                
                with allure.step(step_name):
                    key = step_value['关键字']
                    try:
                        key_func = kw.__getattribute__(key)
                    except Exception as e:
                        print(e)
                    key_func(**step_value)
        
        except Exception as e:
            assert False, f"核心执行器或是核心执行器调用的关键字有错误: {e}"
        
        finally:
            print('---执行用例完成---')

此运行脚本的功能:

  • 读取 YAML 测试用例 (caseinfo 变量)。
  • 逐步运行测试用例步骤 (steps)。
  • 使用 Keywords 类中的函数执行测试操作。
  • 通过 Python 反射机制动态获取 Keywords 类中的方法并执行。

测试用例执行全流程

  1. 测试用例按照 YAML 规范编写,指定每一步测试步骤。
  2. 运行脚本读取 YAML 文件。
  3. 逐步执行 YAML 中定义的步骤,并调用 Keywords 类中的方法。

技术要点

  1. YAML 文件管理测试用例
  2. 采用关键字驱动模式 设计测试用例执行框架,使用例执行更加清晰。
  3. 使用全局字典管理数据,处理测试用例之间的关联情况。
  4. 集成 Allure 生成测试报告,提供详细的测试结果。
### 使用 PytestAllure 实现自动化测试框架集成 为了构建一个高效的 Python 自动化测试框架,可以结合使用 `pytest` 测试库和 `allure-pytest` 插件来生成详细的测试报告。以下是具体方法: #### 安装依赖包 首先安装必要的工具,在命令行执行如下指令: ```bash pip install pytest allure-pytest requests ``` #### 编写测试脚本 创建一个新的 Python 文件作为测试文件,例如命名为 `test_sample.py`。 在此文件中编写简单的 API 请求测试案例,并加入装饰器用于标记不同类型的测试用例以及描述信息。 ```python import pytest import requests @pytest.mark.smoke def test_api_status(): response = requests.get('https://jsonplaceholder.typicode.com/posts/1') assert response.status_code == 200, "API should respond with status code 200" data = response.json() title = data['title'] body = data['body'] # 添加更多断言验证返回的数据结构是否符合预期 assert isinstance(title, str), f"title must be string but got {type(title)}" assert isinstance(body, str), f"body must be string but got {type(body)}" @pytest.mark.regression def test_api_data_validation(): response = requests.post( 'https://jsonplaceholder.typicode.com/posts', json={"title": "foo", "body": "bar", "userId": 1} ) result = response.json() expected_keys = ['id', 'title', 'body', 'userId'] actual_keys = list(result.keys()) missing_fields = set(expected_keys).difference(actual_keys) message = f"The following fields are missing from the JSON response: {missing_fields}" assert not missing_fields, message created_id = int(result["id"]) user_id = int(result["userId"]) assert created_id > 0, "ID of newly created post should be greater than zero." assert user_id == 1, "User ID does not match what was sent in request payload." if __name__ == "__main__": pytest.main(['-v']) ``` 上述代码展示了两个不同的 HTTP 方法 GET 和 POST 的基本测试例子[^3]。 #### 配置 Allure 报告 为了让 `pytest` 能够收集并导出数据给 Allure 工具处理,需修改运行参数以启用插件功能。可以在终端通过指定选项启动测试会话: ```bash pytest --alluredir=./results tests/ ``` 这将会把所有的测试结果保存到当前目录下的 results 文件夹内。 接着可以通过下面这条命令查看生成的结果: ```bash allure serve ./results ``` 该命令会在本地打开浏览器窗口展示交互式的 HTML 格式的测试报告页面[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值