搭建Python自动化框架需先明确测试类型,选择核心工具。Web自动化推荐Selenium+Pytest,接口自动化选用Requests+Pytest+YAML。项目结构需模块化,划分config、tests、utils等目录,通过conftest.py共享浏览器实例或API请求头,提升复用性。使用Python搭建自动化框架可遵循以下步骤,结合核心工具与最佳实践实现高效测试:
一、Web自动化测试框架搭建
1. 环境准备
安装Python:从官网下载最新版本,确保兼容性。
安装依赖库:
bashpip install selenium pytest pytest-html pytest-xdist
selenium:Web自动化核心库,支持多浏览器操作。
pytest:测试框架,支持参数化、fixture和插件扩展。
pytest-html:生成HTML测试报告。
pytest-xdist:支持多线程并行测试。
2. 项目结构规划
web_auto_framework/├── config/ # 配置文件目录│ └── config.py # 存储基础URL、浏览器类型等├── tests/ # 测试用例目录│ ├── conftest.py # 共享fixture│ └── test_login.py # 示例测试用例├── utils/ # 工具类目录│ └── driver_utils.py # 浏览器驱动管理└── reports/ # 测试报告目录
3. 核心代码实现
配置文件(config.py):
pythonBASE_URL = "https://example.com"BROWSER = "chrome" # 支持chrome/firefox
浏览器驱动管理(driver_utils.py):
pythonfrom selenium import webdriverfrom config import BROWSERdef get_driver():if BROWSER == "chrome":return webdriver.Chrome()elif BROWSER == "firefox":return webdriver.Firefox()else:raise ValueError("Unsupported browser")
共享Fixture(conftest.py):
pythonimport pytestfrom utils.driver_utils import get_driver@pytest.fixture(scope="session")def browser():driver = get_driver()yield driverdriver.quit()
测试用例(test_login.py):
pythonimport pytestfrom selenium.webdriver.common.by import By@pytest.mark.usefixtures("browser")class TestLogin:def test_valid_login(self, browser):browser.get("https://example.com/login")browser.find_element(By.ID, "username").send_keys("testuser")browser.find_element(By.ID, "password").send_keys("test123")browser.find_element(By.ID, "login-btn").click()assert "Dashboard" in browser.title
4. 运行与报告
执行测试:
bashpytest tests/ --html=reports/report.html --self-contained-html
并行测试(加速执行):
bashpytest -n 4 # 使用4个线程并行执行
二、接口自动化测试框架搭建
1. 环境准备
安装依赖库:
bashpip install requests pytest pytest-html pyyaml
requests:发送HTTP请求的核心库。
pyyaml:解析YAML格式的测试数据。
2. 项目结构规划
api_auto_framework/├── config/ # 配置文件目录│ └── api_config.py # 存储接口基础URL、超时时间等├── testcases/ # 测试用例目录│ ├── __init__.py│ └── test_user_api.py # 示例测试用例├── data/ # 测试数据目录│ └── user_data.yaml # YAML格式的测试数据└── reports/ # 测试报告目录
3. 核心代码实现
配置文件(api_config.py):
pythonBASE_URL = "https://api.example.com"TIMEOUT = 10 # 请求超时时间(秒)
测试数据(user_data.yaml):
yaml- case_name: "用户登录成功"method: "POST"url: "/user/login"headers: {"Content-Type": "application/json"}json: {"username": "testuser", "password": "test123"}expected_status: 200expected_response: {"code": 0, "message": "success"}
测试用例(test_user_api.py):
pythonimport pytestimport requestsimport yamlfrom config.api_config import BASE_URL, TIMEOUTdef load_test_data(file_path):with open(file_path, "r", encoding="utf-8") as f:return yaml.safe_load(f)@pytest.mark.parametrize("case", load_test_data("data/user_data.yaml"))def test_user_api(case):url = BASE_URL + case["url"]response = requests.request(method=case["method"],url=url,headers=case.get("headers"),json=case.get("json"),timeout=TIMEOUT)assert response.status_code == case["expected_status"]assert response.json() == case["expected_response"]
4. 运行与报告
执行测试:
bashpytest testcases/ --html=reports/api_report.html
三、关键优化与扩展
数据驱动测试:
使用pytest.mark.parametrize实现多组数据测试,避免重复代码。
示例:在接口测试中,通过YAML文件管理多组请求参数和预期结果。
Page Object Model(POM):
将页面元素和操作封装为类,提高Web自动化测试的可维护性。
示例:创建LoginPage类封装登录页面的元素定位和操作方法。
日志与错误追踪:
使用Python的logging模块记录测试过程,便于定位问题。
示例:在关键步骤中添加日志输出。
CI/CD集成:
通过GitHub Actions或Jenkins实现自动化测试与代码提交绑定。
示例:在GitHub Actions中配置工作流,每次推送代码时自动运行测试并生成报告。
四、场景推荐工具优势
Web自动化Selenium + Pytest社区支持强,功能全面
接口自动化Requests + Pytest + YAML轻量级,数据与代码分离
报告生成Allure交互式报告,支持测试步骤可视化
并行测试pytest-xdist显著缩短测试执行时间
持续集成GitHub Actions / Jenkins自动化构建与测试,与开发流程无缝集成
python自动化框架搭建通过pytest-html或Allure生成可视化报告,快速定位失败用例;集成日志模块记录关键步骤,辅助调试。扩展功能可结合CI/CD,实现代码提交后自动触发测试,并支持多线程并行执行,显著缩短测试周期。最终框架应具备高可维护性、可扩展性及与开发流程的无缝集成能力。