pytest结合pymysql实现数据库数据驱动

一、selenium读取mysql中数据

获得数据库连接
查询数据获得数据库连接
查询数据

二、创建数据库,表,向表中插入数据。

连接数据库
mysql -u root -p
查看现有的数据库
show databases; 
创建数据库
create database testing_db;
使用创建的数据库
use testing_db;
创建表
create table user_tbl(id int primary key auto_increment,username varchar(20),pwd varchar(20));
查看表结构
desc user_tb1;
向表中插入数据
insert into user_tbl(username,pwd)values('tom','123');
insert into user_tbl(username,pwd)values('rose','666');
insert into user_tbl(username,pwd)values('tina','888');
查询表中数据
select id,username,pwd from user_tbl;

三、pymysql执行sql数据,获取数据库表中数据,pytest参数化拿到数据,传递给用例执行

代码示例:

import pymysql

import pytest

"""
安装pymysql模块
获得数据库连接
查询数据

"""
conn = pymysql.connect(
    user='root',
    passwd='88888888',
    host='localhost',
    port=3306,
    db='testing_db'
)


def get_data():
    sql = "select id,username,
实现 **从 YAML 文件加载测试数据,使用 `pytest` 参数化执行,并与真实数据库查询结果进行动态对比**,我们可以结合以下技术: - 使用 `PyYAML` 读取测试数据; - 使用 `pymysql` 连接 MySQL 数据库; - 使用 `pytest fixtures` 管理数据库连接; - 使用 `allure-pytest` 添加报告支持; - 结合 `requests` 模拟 API 请求。 --- ## ✅ 示例目录结构 ``` project/ │ ├── test_api.py ├── test_data.yaml └── conftest.py ``` --- ## 📄 test_data.yaml 示例内容 ```yaml - user_id: 1 expected_name: "Leanne Graham" compare_with_db: false - user_id: 2 expected_name: null compare_with_db: true - user_id: 3 expected_name: null compare_with_db: true ``` --- ## 🧩 安装依赖(建议在虚拟环境中) ```bash pip install pytest pyyaml pymysql allure-pytest requests ``` > 如果你没有安装 `allure-commandline`,也可以通过 pipx 或直接下载二进制文件: > > ```bash > pip install allure-pytest > ``` --- ## 📁 conftest.py(全局 fixture 管理) ```python # conftest.py import pytest import pymysql @pytest.fixture(scope="module") def db_connection(): """ 全局数据库连接 fixture,用于模块级别共享 """ conn = pymysql.connect( host='localhost', user='your_user', password='your_password', database='your_database', port=3306, charset='utf8mb4' ) yield conn conn.close() def get_user_name_from_db(conn, user_id): """ 从数据库中查询用户名称 """ with conn.cursor() as cursor: sql = "SELECT name FROM users WHERE id = %s" cursor.execute(sql, (user_id,)) result = cursor.fetchone() return result[0] if result else None @pytest.fixture def get_db_user_name(db_connection): def _get(user_id): return get_user_name_from_db(db_connection, user_id) return _get ``` --- ## 📄 test_api.py 测试脚本 ```python # test_api.py import pytest import yaml import os import requests import allure BASE_URL = "https://jsonplaceholder.typicode.com/users/" def load_test_data(): current_dir = os.path.dirname(__file__) yaml_path = os.path.join(current_dir, 'test_data.yaml') with open(yaml_path, 'r', encoding='utf-8') as f: return yaml.safe_load(f) @allure.step("加载测试数据:{case}") def step_load_case(case): pass @allure.step("调用接口获取用户信息:{user_id}") def step_call_api(url): return requests.get(url) @allure.step("断言状态码和用户名") def step_assertions(data, expected_name, actual_name): assert data["name"] == expected_name, f"Expected '{expected_name}', got '{actual_name}'" @pytest.mark.parametrize("case", load_test_data()) def test_get_user_info(case, get_db_user_name): user_id = case["user_id"] expected_name = case["expected_name"] compare_with_db = case["compare_with_db"] # 显示当前用例的数据源 step_load_case(case) url = f"{BASE_URL}{user_id}" response = step_call_api(url) assert response.status_code in (200, 404), \ f"Unexpected status code {response.status_code}" if response.status_code == 200: data = response.json() if compare_with_db: expected_name = get_db_user_name(user_id) assert expected_name is not None, f"No data found in DB for user_id={user_id}" step_assertions(data, expected_name, data["name"]) else: assert response.text == "" ``` --- ## 📊 生成 Allure 报告 ### 执行测试并生成原始报告数据: ```bash pytest test_api.py --alluredir=./allure-results -v ``` ### 查看报告: ```bash allure serve ./allure-results ``` --- ## 🔍 Allure 报告展示内容说明 - 每个测试用例会显示其使用的 YAML 数据; - 展示调用的接口 URL; - 展示数据库比对逻辑是否启用; - 显示预期值和实际值; - 支持步骤分步查看,便于调试和分析失败原因。 --- ## ✅ 总结功能亮点 | 功能 | 描述 | |------|------| | 外部数据源 | YAML 文件定义测试数据 | | 数据驱动 | `pytest.parametrized` 实现多组测试 | | 数据库连接 | `pymysql` + `fixture` 统一管理连接 | | 动态比对 | 根据字段决定是否使用数据库最新数据 | | 报告支持 | `Allure` 提供可视化测试流程和数据详情 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值