如何为色盲模式写自动化测试?
解读
面试官真正想考察的是“把可访问性(Accessibility)需求转化为可执行、可回归的自动化测试用例”的能力。色盲模式属于视觉无障碍范畴,国内大厂(阿里、腾讯、字节等)在《信息技术 互联网内容无障碍通用技术要求》合规审计中都会重点检查。测试难点在于:
- 颜色差异无法靠肉眼持续回归;
- 需要覆盖多种色盲类型(红盲、绿盲、蓝盲、全色弱);
- 必须在 CI 流水线中稳定运行,不能依赖人工截图比对。
因此,候选人要给出一条“Python + Pytest + 开源工具链”的可落地技术路线,并体现参数化、断言、fixture、并行、报告可追溯等 Pytest 最佳实践。
知识点
- 可访问性标准:国内等保 2.0、GB/T 37668-2019、工信部 App 无障碍评测指南。
- 色盲模拟算法:Brettel 1997、Machado 2009,开源实现有 colorblindly、Daltonize、opencv-contrib 的 cvtColor。
- Pytest 参数化:@pytest.mark.parametrize 与 pytest_generate_tests 钩子,可一次性生成多类型色盲用例。
- 图像差分算法:SSIM、ΔE2000、直方图相交,断言失败时自动附加 diff 热图到 allure 报告。
- 无头浏览器:Playwright 或 Selenium 4 配合 headless=True,在 Docker 容器内运行,保证 CI 一致性。
- 黄金 Master 策略:第一次运行自动生成“色盲基准图”,后续比对;支持 pytest --regen 开关刷新基准。
- 性能加速:pytest-xdist 按 viewport 或颜色类型分片并行,10 张截图可在 30 s 内跑完。
- 失败溯源:allure-pytest 附件、pytest-html 截图、日志中打印 RGB 直方图向量,方便开发一键定位色差区域。
答案
下面给出一套可直接搬进国内 GitLab CI 的实战方案,代码全部单文件可运行,依赖公开源,无版权风险。
-
目录结构
project/
├─ tests/
│ ├─ conftest.py
│ ├─ test_colorblind.py
│ ├─ assets/ # 存放黄金基准图
├─ pytest.ini
├─ requirements.txt -
requirements.txt
pytest>=7.4
pytest-xdist>=3.3
allure-pytest>=2.13
playwright>=1.40
opencv-python>=4.8
scikit-image>=0.21
colorblindly>=0.2 -
conftest.py
import pytest
from pathlib import Path
import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
CB_TYPES = ["protanopia", "deuteranopia", "tritanopia", "achromatopsia"]
def pytest_addoption(parser):
parser.addoption("--regen", action="store_true", help="重新生成黄金基准图")
@pytest.fixture(scope="session")
def browser(playwright):
browser = playwright.chromium.launch(headless=True)
yield browser
browser.close()
@pytest.fixture(scope="session")
def regen(request):
return request.config.getoption("--regen")
@pytest.fixture(params=CB_TYPES, ids=CB_TYPES)
def cb_type(request):
return request.param
def image_similarity(img1: np.ndarray, img2: np.ndarray) -> float:
"""返回 SSIM 0~1,1 为完全一致"""
if img1.shape != img2.shape:
return 0.0
gray1, gray2 = map(lambda x: cv2.cvtColor(x, cv2.COLOR_BGR2GRAY), (img1, img2))
return ssim(gray1, gray2)
def attach_img_to_allure(img_path, name):
import allure
allure.attach.file(img_path, name=name, attachment_type=allure.attachment_type.PNG)
- test_colorblind.py
import pytest
from pathlib import Path
import cv2
from colorblindly import simulate
from conftest import image_similarity, attach_img_to_allure
URL = "https://www.example.com" # 被测系统
VIEWPORT = {"width": 1280, "height": 720}
THRESHOLD = 0.98 # 国内合规一般要求 ≥98% 相似度
@pytest.mark.parametrize("route", ["/", "/product", "/order"])
def test_colorblind_screenshot(route, browser, cb_type, regen, tmp_path, request):
page = browser.new_page(viewport=VIEWPORT)
page.goto(URL + route)
# 1. 截图:正常视觉
normal_png = tmp_path / "normal.png"
page.screenshot(path=normal_png, full_page=True)
# 2. 生成色盲模拟图
normal_img = cv2.imread(str(normal_png))
cb_img = simulate(normal_img, cb_type=cb_type)
cb_png = tmp_path / f"{cb_type}.png"
cv2.imwrite(str(cb_png), cb_img)
# 3. 黄金 Master 逻辑
golden_dir = Path(__file__).with_suffix("") / "assets" / route.strip("/") / cb_type
golden_dir.mkdir(parents=True, exist_ok=True)
golden_png = golden_dir / "golden.png"
if regen or not golden_png.exists():
golden_png.write_bytes(cb_png.read_bytes())
pytest.skip("基准图已生成,请 review 后重跑")
# 4. 断言
golden_img = cv2.imread(str(golden_png))
score = image_similarity(cb_img, golden_img)
if score < THRESHOLD:
attach_img_to_allure(cb_png, f"实际-{cb_type}")
attach_img_to_allure(golden_png, f"基准-{cb_type}")
pytest.fail(f"{route} 在 {cb_type} 模式下相似度 {score:.3f} 低于阈值 {THRESHOLD}")
- 运行与集成
本地回归:
pytest -n auto --alluredir=report
CI(.gitlab-ci.yml 片段):
test_colorblind:
stage: test
image: mcr.microsoft.com/playwright/python:v1.40.0-focal
script:
- pip install -r requirements.txt
- playwright install chromium
- pytest -n auto --alluredir=report
artifacts:
when: always
paths:
- report/
expire_in: 7 days
- 结果解读
若断言失败,allure 报告会同时出现“实际图”“基准图”,并给出 SSIM 分值;开发可点击 diff 区域,快速定位按钮、图表、错误提示等关键元素是否因色盲模式丢失信息。若产品迭代 UI 变动合法,测试工程师执行pytest --regen即可一键刷新基准,继续守护后续版本。
拓展思考
-
动态内容如何稳定回归?
可在截图前注入一段 JS,把轮播图、广告位替换为占位色块;或对比时只对“感兴趣区域”(ROI) 做 SSIM,排除动效干扰。 -
仅验证颜色是否足够?
国内合规还要检查“非颜色提示”,例如输入错误不仅标红,还要出现图标或文字。可再增加一条用例:关闭颜色模拟,仅通过灰度图 OCR 识别提示文本,确保色盲用户也能感知。 -
如何量化“可阅读性”而不仅是“相似”?
引入 WCAG 2.1 对比度公式,对按钮文字与背景区域采样 LAB 空间,断言对比度 ≥4.5:1;Pytest 参数化与 fixture 机制同样适用。 -
多端覆盖?
同一套代码把 browser 换成 playwright 的 iphone12 设备描述符,即可在 CI 中并行跑移动端色盲截图,实现“一份用例,多端守护”。 -
大团队协同?
把黄金基准图存到 LFS 或 OSS,pytest 运行前自动 pull;在 MR 阶段若 diff 超过阈值,机器人自动评论并 @设计师,形成“设计-测试-开发”闭环。