如何参数化测试30种主题并生成Allure报告?

解读

  1. 场景定位:国内数据科学团队普遍使用 Dash 做多主题仪表盘,上线前需验证所有主题在 PC、移动端、深色/浅色模式下的视觉一致性。
  2. 参数化含义:30 种主题 = 30 组输入参数(主题名、主色、辅色、字体、背景、边框、组件皮肤等),需一次性注入测试用例,而非写 30 个文件。
  3. Allure 适配:国内主流 CI(GitLab-CI、Jenkins、阿里云效)已内置 Allure 插件,面试官想看你是否能把 Python 测试结果自动转换成 HR 与产品都能看懂的图形化报告,并集成到 Merge Request 门禁。
  4. 面试评分维度:
    • 参数化设计(pytest.mark.parametrize 与自定义 fixture 结合)
    • 主题注入方式(Dash 的 external_stylesheets 与 theme 对象动态替换)
    • 断言策略(视觉回归、CSS 计算值、组件属性三重校验)
    • Allure 标签规范(epic、feature、story、severity、step、attach)
    • 并发与稳定性(30 个浏览器实例资源控制、失败重试、截图缓存)
    • 工程化落地(PageObject、配置中心、CI 模板、Docker 化)

知识点

  • pytest 参数化机制:ids 命名、indirect 参数、笛卡尔积与筛选
  • Dash 主题体系:dbc.themes、plotly.io.templates、自定义 CSS 变量
  • Selenium/Appium 远程 WebDriver:Chrome DevTools Protocol 取 CSS 计算值
  • Allure-pytest 钩子:allure.dynamic 模块运行时改写标签
  • 视觉回归:Pillow 直方图对比 + SSIM,阈值可配置
  • 并发执行:pytest-xdist 的 loadscope 模式,保证同一主题下用例在同一进程
  • 失败截图与日志:pytest-runfailures + allure.attach.file
  • 国内镜像:清华 PyPI、阿里云 npm、ChromeDriver 镜像加速
  • 合规:截图不含用户隐私,敏感数据脱敏接口由 mock 服务器返回

答案

工程结构
tests/
├─conftest.py # 全局 fixture、WebDriver 初始化、失败截图钩子
├─data/theme.yaml # 30 组主题配置,国内色值采用 Ant Design 规范
├─pages/dashboard_page.py # PageObject,封装 Dash 应用常用操作
├─test_theme.py # 参数化用例文件
└─requirements-test.txt

  1. 主题配置(节选)
    themes:
  • name: 薄荷绿
    primary: "#13C2C2"
    background: "#f0fffe"
    font: "PingFang SC"

…共 30 组

  1. conftest.py 关键代码
import pytest, yaml, allure, os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

@pytest.fixture(scope="session")
def chrome():
    opt = Options()
    opt.add_argument("--headless=new")
    opt.add_argument("--force-device-scale-factor=1")
    driver = webdriver.Chrome(options=opt)
    yield driver
    driver.quit()

def pytest_generate_tests(metafunc):
    if "theme" in metafunc.fixturenames:
        with open("tests/data/theme.yaml") as f:
            raw = yaml.safe_load(f)["themes"]
        metafunc.parametrize("theme", raw, ids=[t["name"] for t in raw])

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        driver = item.funcargs.get("chrome")
        if driver:
            png = driver.get_screenshot_as_png()
            allure.attach(png, name="失败截图", attachment_type=allure.attachment_type.PNG)
  1. PageObject:dashboard_page.py
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
import allure

class DashboardPage:
    URL = "http://localhost:8050"
    def __init__(self, driver: WebDriver):
        self.d = driver
    @allure.step("加载主题:{theme_name}")
    def load(self, theme_name):
        self.d.get(f"{self.URL}?theme={theme_name}")
    @allure.step("获取主按钮背景色")
    def primary_button_bg(self):
        return self.d.execute_script(
            "return window.getComputedStyle(document.querySelector('.btn-primary')).backgroundColor"
        )
    @allure.step("整页截图")
    def screenshot(self):
        return self.d.get_screenshot_as_png()
  1. 参数化用例:test_theme.py
import allure, pytest
from pages.dashboard_page import DashboardPage
from PIL import Image
import io, numpy as np
from skimage.metrics import structural_similarity as ssim

@allure.epic("Dash 主题自动化")
@allure.feature("视觉一致性")
class TestTheme:
    @allure.story("主题配色")
    @allure.severity(allure.severity_level.CRITICAL)
    def test_primary_color(self, chrome, theme):
        page = DashboardPage(chrome)
        page.load(theme["name"])
        actual = page.primary_button_bg()
        # rgba 转 hex 省略,断言
        assert actual == theme["primary"], f"主色不匹配,实际{actual}"

    @allure.story("视觉回归")
    @allure.severity(allure.severity_level.NORMAL)
    def test_visual_regression(self, chrome, theme):
        page = DashboardPage(chrome)
        page.load(theme["name"])
        png = page.screenshot()
        # 与基线对比
        baseline = Image.open(f"tests/baseline/{theme['name']}.png")
        current = Image.open(io.BytesIO(png))
        score, _ = ssim(np.array(baseline), np.array(current), channel_axis=2, full=True)
        assert score >= 0.98, f"SSIM 过低:{score}"
  1. 运行与报告
# 安装依赖
pip install -r requirements-test.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# 启动 Dash 应用(开发端口 8050)
gunicorn app:server -b 0.0.0.0:8050 &
# 并发执行
pytest -n 6 --alluredir=report
# 生成 Allure HTML
allure generate report -o allure-html --clean
# 在 GitLab-CI 中只需把 allure-html 作为制品上传,MR 页面即可看到趋势图
  1. 门禁配置(GitLab-CI 片段)
test:
  stage: test
  image: python:3.11-slim
  services:
    - selenium/standalone-chrome:latest
  script:
    - pip install -r tests/requirements-test.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
    - pytest -n 6 --alluredir=report
  artifacts:
    when: always
    paths:
      - allure-html
    reports:
      allure:
        path: report
  only:
    - merge_requests

拓展思考

  1. 动态主题注入:如果 Dash 应用使用 CSS 变量而非 external_stylesheets,可通过 Dash 的 clientside_callback 把主题写入 :root,测试脚本只需执行 JS 替换变量即可,无需重启服务,节省 30% 时间。
  2. 视觉基线自动更新:在 CI 里增加 pytest --update-baseline 开关,跑通后自动把新截图推送到「基线」分支,产品验收后合并,解决设计师频繁调色的痛点。
  3. 多分辨率覆盖:国内用户 40% 使用 125% 系统缩放,可在 conftest.py 里加 @pytest.fixture(params=[1, 1.25, 1.5]) 参数化 DPR,结合 Chrome DevTools Protocol 的 Emulation.setDeviceMetricsOverride,一条用例覆盖三种像素比。
  4. 合规脱敏:若仪表盘含有真实订单金额,使用 pytest-mock 拦截 /api/data 路由,返回 mock 数据,并在 Allure 报告里打上 sensitive=false 标签,满足国内金融客户的安全审计要求。
  5. 性能基线:Allure 支持把 allure.attach 写入 window.performance.timing 的 JSON,面试时可提出「主题切换耗时」作为新增验收指标,展示你对前端性能的关注,进一步拉高技术深度。