📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)
📝 职场经验干货:
目标
✅ 封装通用的接口响应断言逻辑
✅ 封装通用的数据库查询与断言逻辑
✅ 支持链式调用、日志记录、异常处理等高级特性
✅ 可集成到 pytest / unittest 等测试框架中使用
所需依赖(pip install)
pip install httpx pymysql SQLAlchemy pytest
目录结构建议
test_framework/
│
├── utils/
│ ├── assert_utils.py # 断言工具类(接口 + 数据库)
│ └── db_utils.py # 数据库连接工具
│
├── testcases/
│ └── test_api_with_assert.py
│
└── config/
└── db_config.py # 数据库配置
核心代码实现
1️⃣ 数据库配置:config/db_config.py
# config/db_config.py
DB_CONFIG = {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "your_password",
"database": "test_db",
"charset": "utf8mb4"
}
2️⃣ 数据库工具类:utils/db_utils.py
# utils/db_utils.py
import pymysql
from config.db_config import DB_CONFIG
class DBUtils:
def __init__(self, db_config=None):
self.db_config = db_config or DB_CONFIG
self.connection = None
def connect(self):
self.connection = pymysql.connect(**self.db_config)
return self.connection.cursor()
def query(self, sql: str):
cursor = self.connect()
try:
cursor.execute(sql)
result = cursor.fetchone() if "SELECT" in sql.upper() else None
self.connection.commit()
return result
finally:
cursor.close()
self.connection.close()
def execute(self, sql: str):
cursor = self.connect()
try:
cursor.execute(sql)
self.connection.commit()
finally:
cursor.close()
self.connection.close()
3️⃣ 高级断言工具类:utils/assert_utils.py
# utils/assert_utils.py
import logging
import json
from typing import Any, Union
logger = logging.getLogger(__name__)
class AssertUtils:
def __init__(self):
self._failures = []
def assert_equal(self, actual: Any, expected: Any, msg: str = "") -> None:
try:
assert actual == expected, f"{msg} | Expected: {expected}, Actual: {actual}"
except AssertionError as e:
self._failures.append(str(e))
logger.error(f"断言失败: {e}")
def assert_in(self, actual: str, expected: str, msg: str = "") -> None:
try:
assert expected in actual, f"{msg} | Expected substring '{expected}' not in '{actual}'"
except AssertionError as e:
self._failures.append(str(e))
logger.error(f"断言失败: {e}")
def assert_status_code(self, response, expected_code: int) -> None:
self.assert_equal(response.status_code, expected_code, "HTTP 状态码不匹配")
def assert_json_key(self, response, key: str) -> None:
try:
json_data = response.json()
assert key in json_data, f"JSON 响应缺少字段: {key}"
except Exception as e:
self._failures.append(str(e))
logger.error(f"断言失败: {e}")
def assert_json_value(self, response, key: str, expected_value: Any) -> None:
try:
json_data = response.json()
actual_value = json_data.get(key)
assert actual_value == expected_value, f"JSON 字段值不匹配: {key} | Expected: {expected_value}, Actual: {actual_value}"
except Exception as e:
self._failures.append(str(e))
logger.error(f"断言失败: {e}")
def assert_db_value(self, db_utils, sql: str, expected_value: Any) -> None:
try:
result = db_utils.query(sql)
actual_value = result[0] if result else None
assert actual_value == expected_value, f"数据库值不匹配 | SQL: {sql} | Expected: {expected_value}, Actual: {actual_value}"
except Exception as e:
self._failures.append(str(e))
logger.error(f"断言失败: {e}")
def assert_all(self):
if self._failures:
error_msg = "\n".join(self._failures)
raise AssertionError(f"以下断言失败:\n{error_msg}")
else:
logger.info("所有断言通过")
4️⃣ 示例测试用例:testcases/test_api_with_assert.py
# testcases/test_api_with_assert.py
import httpx
from utils.assert_utils import AssertUtils
from utils.db_utils import DBUtils
import pytest
@pytest.fixture
def client():
return httpx.Client(base_url="https://jsonplaceholder.typicode.com")
@pytest.fixture
def assert_utils():
return AssertUtils()
@pytest.fixture
def db_utils():
return DBUtils()
def test_get_user_and_assert(client, assert_utils, db_utils):
response = client.get("/users/1")
# 接口断言
assert_utils.assert_status_code(response, 200)
assert_utils.assert_json_key(response, "name")
assert_utils.assert_json_value(response, "id", 1)
# 数据库断言(假设我们有对应的用户表)
user_id = 1
sql = f"SELECT name FROM users WHERE id = {user_id}"
assert_utils.assert_db_value(db_utils, sql, "Leanne Graham")
# 最终验证所有断言是否成功
assert_utils.assert_all()
运行测试 & 查看结果
pytest testcases/test_api_with_assert.py -v
输出示例:
========= test session starts ==========
collected 1 item
test_api_with_assert.py::test_get_user_and_assert PASSED [100%]
========= 1 passed in 0.5s ===========
优势总结
可选增强功能(进阶)
打包发布建议
你可以将这些工具类打包为 Python 包,供多个项目复用:
pip install setuptools wheel
python setup.py sdist bdist_wheel
最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】