1、接口项目(flask 后端)
研一时,课题组有一个横向课题,是基于AI的童话绘本生成,当时我负责后端代码的实现。也是在那个时候接触到了Flask框架。
Flask框架是一个轻量化的python后端框架,支持用户的高度diy,出于对新技术的好奇,想要了解一下python自动化接口测试的知识,因此自己搭建了一套基于pytest的自动化接口测试框架。针对该测试框架实现了用于测试的后端接口项目,项目地址如下:
XuWink/autopytestapi: 基于Flask+MySQL的后端接口项目
框架权限可以参考该文章:Flask用户登录及权限管理 | 禧语许
D:.
├─app
│ ├─api
│ │ └─__pycache__
│ ├─auth
│ ├─event
│ │ └─__pycache__
│ ├─static
│ └─__pycache__
├─common
│ └─__pycache__
├─config
│ └─__pycache__
├─data
├─logs
└─utils
项目比较简单,实现了用户的注册,登录,增删改查等功能。
其中,app模块使用python的蓝本实现了多模块开发,实现了不同模块的api;event模块是业务层,这里没有实现DAO层,简单的将业务层与DAO层写在了一起;common定义了MySQL、redis、logger等的manager类,实现解耦合;config模块是项目的配置文件;utils模块是工具包。
2、自动化测试平台
项目地址:https://github.com/XuWink/autopytest.git
2.1 pytest
pytest是python的自动化测试框架,用于编写和运行单元测试、集成测试以及其他类型的测试,使用pytest需要安装:
pip3 -m pip install pytest
简单易用:采用简洁的语法,无需继承特定的测试类,普通函数即可作为测试用例。例如,编写一个简单的测试用例只需定义一个以
test_
开头的函数,并在其中使用assert
语句进行断言。自动测试发现:能够自动查找和运行符合命名规则的测试文件和函数,测试文件通常以
test_
开头或以_test
结尾,测试函数以test_
开头。强大的断言:使用Python的
assert
语句,无需特殊断言方法,且在失败时能提供详细的错误信息。
import pytest
from my_module import add, divide
# 测试加法函数
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
# 测试除法函数(正常情况)
def test_divide():
assert divide(6, 3) == 2.0
# 测试除法函数(异常情况)
def test_divide_by_zero():
with pytest.raises(ValueError, match="Division by zero"):
divide(1, 0)
参数化测试:支持测试用例的参数化,通过
@pytest.mark.parametrize
装饰器为测试函数提供多组输入数据,减少重复代码。
import pytest
from my_module import add
# 参数化测试:提供多组输入和预期输出
@pytest.mark.parametrize(
"a, b, expected", # 参数名
[
(1, 2, 3), # 第一组数据
(-1, 1, 0), # 第二组数据
(0, 0, 0), # 第三组数据
]
)
def test_add_parametrized(a, b, expected):
assert add(a, b) == expected
丰富的插件生态:拥有大量的插件支持,如覆盖率分析、并行测试、生成美观的测试报告等,可通过插件扩展和定制测试过程。
灵活的夹具(Fixture):夹具是pytest的核心功能之一,用于提供测试所需的资源,通过
@pytest.fixture
装饰器定义,可控制夹具的生命周期,如函数级、模块级、会话级等。
import pytest
# 定义夹具(函数级夹具)
@pytest.fixture
def db_connection():
print("Connecting to database...") # 模拟连接
connection = "Mock DB Connection" # 返回模拟对象
yield connection # 测试代码执行到这里
print("Closing database connection...") # 测试后清理
# 使用夹具的测试
def test_query(db_connection):
assert isinstance(db_connection, str)
assert db_connection == "Mock DB Connection"
标记功能:使用
@pytest.mark
为测试添加标记,用于分类或选择性运行测试用例,还可通过pytest.ini
文件自定义标记。
import pytest
# 标记慢测试
@pytest.mark.slow
def test_long_running_operation():
import time
time.sleep(2) # 模拟耗时操作
assert True
# 标记需要特定环境的测试
@pytest.mark.skipif(not hasattr(pytest, "config"), reason="Requires pytest config")
def test_requires_config():
assert hasattr(pytest, "config")
###############################
pytest -m slow # 只运行标记为 slow 的测试
pytest -m "not slow" # 跳过标记为 slow 的测试
2.2 allure
https://github.com/allure-framework/allure2.git
Allure 是一个灵活、轻量级的测试报告工具,支持与 pytest 等测试框架集成,生成美观且详细的测试报告。以下是 Allure 的使用方法及示例:
2.2.1 安装
安装 Java 环境
Allure 依赖 Java 8+,需下载并安装 JDK,配置JAVA_HOME
环境变量。安装 Allure 命令行工具
从 GitHub Releases 下载 ZIP 包。
解压后,将
bin
目录添加到系统Path
环境变量中。验证安装:运行
allure --version
,显示版本号即成功。
安装 pytest 和 allure-pytest 插件
pip install pytest allure-pytest
2.2.2 使用示例
基础测试报告生成
import pytest
import allure
@allure.feature("用户管理模块")
class TestUserManagement:
@allure.story("用户登录")
@allure.title("验证用户使用正确密码登录成功")
def test_login_success(self):
with allure.step("打开登录页面"):
print("导航到登录页")
with allure.step("输入用户名和密码"):
print("输入用户名: admin, 密码: 123456")
with allure.step("点击登录按钮"):
print("点击登录")
assert True # 模拟断言
@allure.story("用户登录")
@allure.title("验证用户使用错误密码登录失败")
def test_login_failure(self):
with allure.step("输入错误密码"):
print("输入密码: wrong_password")
assert False, "登录失败,预期结果符合预期"
# 执行测试并生成 Allure 结果文件
pytest test_example.py --alluredir=./allure-results
# 生成 HTML 报告
allure generate ./allure-results -o ./allure-report --clean
# 打开报告(自动启动默认浏览器)
allure open ./allure-report
# 或者
allure serve ./allure-results
参数化测试与报告优化
使用 @pytest.mark.parametrize
和 allure.dynamic.title
优化报告标题
import allure
import pytest
datas = [
{"user": "king", "pwd": 123456},
{"user": "king1", "pwd": 1234567},
{"user": "hello", "pwd": 123456}
]
@pytest.mark.parametrize(
"data",
datas,
ids=[
"正确的用户名和密码",
"正确的用户名和错误的密码",
"不存在的用户名和密码"
]
)
def test_login(data):
with allure.step(f"尝试登录,用户名: {data['user']}, 密码: {data['pwd']}"):
assert data["user"].startswith("king") and data["pwd"] == 123456
添加附件与日志
在测试失败时自动截图并附加到报告:
import allure
import pytest
def test_with_attachment():
try:
assert 1 == 2 # 模拟失败
except AssertionError:
with open("error.log", "w") as f:
f.write("测试失败日志")
allure.attach.file("error.log", name="错误日志", attachment_type=allure.attachment_type.TEXT)
其他
使用命令行参数筛选特定标记的测试用例
pytest --alluredir=./allure-results --allure-severities=critical,blocker
与Jenkins集成:
在 Jenkins 中安装 Allure 插件。
配置构建后操作,选择 "Allure Report"。
构建项目后,可在 Jenkins 中查看 Allure 报告。
2.3 代码结构
D:.
├─api
├─common
├─config
├─core
├─data
├─operation
├─testcases
│ └─api_test
└─utils
3、与集成Jenkins
安装Jenkins可以参考本人博客:Ubuntu使用Docker配置Jenkins | 禧语许
todo