ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Selenium+Pytest+Allure自动化测试实战指南

Selenium+Pytest+Allure自动化测试实战指南

1. 项目概述:Selenium+Pytest+Allure测试组合的价值

在Web应用开发中,UI自动化测试是保证产品质量的重要环节。这套技术组合中,Selenium负责浏览器自动化操作,Pytest作为测试执行框架,Allure则提供可视化报告,三者协同工作形成完整的测试解决方案。

我曾在电商项目中用这套组合将回归测试时间从8小时压缩到25分钟,关键页面测试覆盖率提升至98%。这种组合特别适合需要频繁回归测试的敏捷开发团队,以及需要向非技术人员展示测试结果的场景。

2. 环境搭建与工具配置

2.1 基础环境安装

Python环境建议使用3.7+版本,避免兼容性问题。使用virtualenv创建隔离环境:

python -m venv test_env source test_env/bin/activate # Linux/Mac test_env\Scripts\activate # Windows

核心组件安装命令:

pip install selenium pytest allure-pytest

注意:Allure需要额外安装命令行工具,从GitHub Releases下载对应版本,解压后将bin目录加入PATH环境变量

2.2 浏览器驱动配置

以Chrome为例,需下载与浏览器版本匹配的chromedriver:

# 查看Chrome版本 google-chrome --version # 下载对应驱动 wget https://chromedriver.storage.googleapis.com/114.0.5735.90/chromedriver_linux64.zip unzip chromedriver_linux64.zip mv chromedriver /usr/local/bin/

常见问题处理:

  • 版本不匹配:通过Chrome菜单→帮助→关于Google Chrome查看精确版本号
  • 权限问题:执行chmod +x chromedriver
  • 路径问题:建议将驱动放在系统PATH包含的目录

3. 测试框架设计与实现

3.1 项目目录结构

推荐采用分层设计:

project/ ├── pages/ # 页面对象类 │ ├── login_page.py │ └── home_page.py ├── tests/ # 测试用例 │ ├── test_login.py │ └── test_search.py ├── conftest.py # pytest fixtures ├── pytest.ini # 配置文件 └── reports/ # 测试报告

3.2 页面对象模式实现

示例登录页面封装:

# pages/login_page.py from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class LoginPage: def __init__(self, driver): self.driver = driver self.username_locator = (By.ID, "username") self.password_locator = (By.ID, "password") self.submit_locator = (By.CSS_SELECTOR, "button[type='submit']") def enter_credentials(self, username, password): WebDriverWait(self.driver, 10).until( EC.presence_of_element_located(self.username_locator) ).send_keys(username) self.driver.find_element(*self.password_locator).send_keys(password) def submit(self): self.driver.find_element(*self.submit_locator).click()

3.3 测试用例编写

结合Pytest参数化实现数据驱动测试:

# tests/test_login.py import pytest from pages.login_page import LoginPage @pytest.mark.parametrize("username,password,expected", [ ("admin", "correct_pwd", True), ("guest", "wrong_pwd", False), ("", "", False) ]) def test_login(driver, username, password, expected): """测试不同账号密码组合的登录结果""" login_page = LoginPage(driver) login_page.enter_credentials(username, password) login_page.submit() if expected: assert "dashboard" in driver.current_url else: assert "error" in driver.page_source

4. Allure报告高级应用

4.1 测试步骤注解

使用装饰器增强报告可读性:

import allure @allure.feature("用户认证") @allure.story("登录功能") def test_login_with_allure(driver): with allure.step("打开登录页面"): driver.get("https://example.com/login") with allure.step("输入凭证"): LoginPage(driver).enter_credentials("admin", "admin123") with allure.step("提交表单"): LoginPage(driver).submit() allure.attach(driver.get_screenshot_as_png(), name="登录后页面", attachment_type=allure.attachment_type.PNG)

4.2 报告生成与查看

执行测试并生成报告:

pytest tests/ --alluredir=./results allure serve ./results # 本地查看 allure generate ./results -o ./report --clean # 生成静态报告

关键参数说明:

  • --alluredir:指定结果文件存储目录
  • --clean:清除历史结果
  • -o:指定报告输出目录

5. 常见问题解决方案

5.1 元素定位问题处理

典型定位失败场景处理方案:

问题现象解决方案代码示例
元素未加载完成使用显式等待WebDriverWait(driver,10).until(EC.presence_of_element_located(locator))
元素在iframe中切换iframe上下文driver.switch_to.frame("frame_name")
动态ID元素使用XPath或CSS选择器//div[contains(@class,'login-form')]

5.2 测试稳定性提升技巧

  1. 智能等待策略:
def wait_for_ajax(driver): WebDriverWait(driver, 10).until( lambda d: d.execute_script("return jQuery.active == 0") )
  1. 失败自动重试: 在pytest.ini中添加:
[pytest] reruns = 2 reruns_delay = 1
  1. 跨浏览器支持:
@pytest.fixture(params=["chrome", "firefox"]) def driver(request): if request.param == "chrome": options = webdriver.ChromeOptions() return webdriver.Chrome(options=options) else: return webdriver.Firefox()

6. 高级应用场景

6.1 持续集成集成

Jenkins Pipeline示例:

pipeline { agent any stages { stage('Test') { steps { sh 'pytest tests/ --alluredir=./results' } } stage('Report') { steps { allure includeProperties: false, jdk: '', results: [[path: 'results']] } } } }

6.2 移动端响应式测试

通过设置浏览器窗口尺寸测试响应式布局:

@allure.story("响应式布局测试") @pytest.mark.parametrize("width,height", [(320,568), (768,1024), (1920,1080)]) def test_responsive(driver, width, height): driver.set_window_size(width, height) # 执行布局测试逻辑 assert element.is_displayed()

这套技术组合经过多个百万级用户项目的验证,在保持测试代码可维护性的同时,能有效提升测试效率。关键在于合理设计页面对象模型,配合Allure的丰富报告功能,使自动化测试真正成为质量保障的利器。

返回列表