第三方网站系统测试:【基于Pytest的自动化测试框架的测试】
Pytest作为Python社区主流的测试工具,提供了一个可扩展的生态,通过简洁的语法、强大的Fixture机制和丰富的插件体系,支持从简单的单元测试到复杂的功能集成与E2E(端到端)自动化测试。提升测试代码的可维护性、执行效率与集成能力。
测试框架架构
一个结构良好的测试框架包含以下:
1.测试用例层: 业务测试逻辑的载体,表现为以test_开头的函数或Test开头的类。此层应专注于“测试什么”,而非“如何准备或执行”。
2.页面对象层(适用于UI测试): 将Web页面或App屏封装为Python类。页面元素定位符和页面操作(如点击、输入)在此层定义,实现UI细节与测试逻辑的分离。
3.服务层(适用于API测试): 封装系统API接口,提供构造请求、发送请求、解析响应的通用方法,是API测试的基础构件。
4.数据管理层: 负责测试数据的生成、提供与清理。支持从外部文件(JSON, YAML, Excel)、数据库或通过脚本动态生成测试数据。
5.核心配置层: 通过配置文件(如conftest.py, pytest.ini, 环境配置文件)管理全局变量、Fixture、钩子函数(Hooks)和执行参数。
6.公共工具层: 提供日志记录、数据库连接、HTTP客户端、文件操作等复用工具。
7.报告与CI集成层: 集成Allure-Pytest、pytest-html等插件生成可视化报告,并通过pytest命令与Jenkins、GitLab CI等持续集成平台无缝对接。
技术实践
1. Fixture的精准应用Fixture是Pytest的灵魂,用于实现测试前置条件(Setup)和后置清理(Teardown)的复用。
# conftest.py
import pytest
from selenium import webdriver@pytest.fixture(scope="session")
def driver():# 会话级Fixture,所有测试只启动一次浏览器_driver = webdriver.Chrome()_driver.implicitly_wait(10)yield _driver # 将driver实例提供给测试用例_driver.quit() # 测试会话结束后退出浏览器@pytest.fixture
def login(driver):# 应用级Fixture,依赖driver,实现自动登录driver.get("https://zmtests.com/login")driver.find_element(By.ID, "username").send_keys("admin")driver.find_element(By.ID, "password").send_keys("secret")driver.find_element(By.TAG_NAME, "button").click()yield# 可选的后置清理,如退出登录
2. 参数化测试
使用@pytest.mark.parametrize轻松实现多组数据驱动测试,减少代码冗余。
import pytest@pytest.mark.parametrize("username, password, expected",[("admin", "secret", True),("user", "wrong_pass", False),("", "secret", False),]
)
def test_login(username, password, expected, login_page):# 使用参数化数据执行测试login_page.enter_credentials(username, password)login_page.click_login()assert login_page.is_login_successful() is expected
3. 动态配置标记
利用pytest.ini定义自定义标记,用于分类和选择性运行测试。
# pytest.ini
[pytest]
markers =smoke: marks tests as smoke suite (deselect with '-m "not smoke"')regression: marks tests as regression suiteslow: slow running tests
4. 插件生态
pytest-html: 生成简洁的HTML测试报告。
pytest-allure: 生成功能强大、交互式的Allure报告,支持附件、步骤描述和缺陷链接。
pytest-xdist: 实现测试用例的分布式执行,充分利用多核CPU,显著缩短测试总耗时。
pytest-rerunfailures: 为 flaky 测试(不稳定的测试)提供失败重试机制,增加稳定性。
pytest-dependency: 处理测试用例间的依赖关系。
5. 钩子函数的定制
通过重写conftest.py中的钩子函数,可以对Pytest的行为进行深度定制。
# conftest.py
def pytest_runtest_makereport(item, call):# 在测试执行生成报告时自动执行if call.when == "call" and call.excinfo is not None:# 如果测试调用失败,且当前有driver Fixture,则截图if "driver" in item.funcargs:driver = item.funcargs["driver"]screenshot_path = f"./screenshots/{item.name}.png"driver.save_screenshot(screenshot_path)# 可将截图附加到Allure报告中