如何为 RTL 布局写镜像测试?

解读

在国内前端/客户端团队里,RTL(Right-to-Left,阿拉伯语、希伯来语等从右到左书写方向)适配早已不是“国际化加分项”,而是合规硬需求:华为、阿里、字节、腾讯的海外产品上线前必须通过阿拉伯语镜像验收。
Pytest 侧的核心诉求是:

  1. 用纯 Python 代码描述“镜像”规则,不依赖人工截图比对;
  2. 能跑在 CI(GitLab-CI、阿里云效、GitHub-CN 镜像源)里,失败时给出可读的 diff;
  3. 支持参数化,一次性覆盖 LTR→RTL 正反场景;
  4. 与现有前端构建流水线解耦,最好让后端/测试同学也能本地调试。

因此题目考察的是:

  • 如何抽象“镜像”为可断言的数据结构;
  • 如何用 Pytest 的 fixture + 参数化 + 插件体系把镜像规则沉淀为自动化用例;
  • 如何在中国网络环境下解决 WebDriver 镜像拉取、字体渲染差异等稳定性痛点。

知识点

  1. RTL 镜像的数学本质:水平轴对称变换,x' = 2·参考点 − x。
  2. CSS 方向模型:
    • direction: rtl;
    • 物理属性 vs 逻辑属性(margin-inline-start 代替 margin-left)。
  3. Pytest 参数化:ids 用中文可读命名,方便国内测试经理评审。
  4. 视觉回归方案选型:
    • 轻量:pyppeteer + Pillow 逐像素 diff;
    • 企业级:pytest-playwright 自带 to_have_screenshot(),可关抗锯齿;
    • 阿里内部常用:pytest-eyes-applitools,但需走阿里云代理访问。
  5. 稳定性加固:
    • 禁用动画、字体回退到 Noto Sans Arabic;
    • 使用 Git-LFS 存参考图,避免 GitHub 慢;
    • 在 conftest.py 里加 retry 装饰器,对抗国内 CDN 抖动。
  6. 断言策略:
    • 几何断言:元素左上角 x 坐标满足镜像公式,误差 ≤1px;
    • 文本断言:获取 window.getComputedStyle(el).direction === 'rtl';
    • 截图断言:SSIM ≥ 0.98 且像素差异率 ≤ 0.1%。
  7. 合规:阿拉伯语地区隐私法要求不能上传真实用户截图,需用 mock 数据。

答案

项目结构
rtl_tests/
├─ conftest.py
├─ test_mirror.py
├─ snapshots/
│ ├─ ltr/
│ └─ rtl/
└─ pages/
└─ demo.py

conftest.py

import pytest
from pathlib import Path
from playwright.sync_api import sync_playwright

@pytest.fixture(scope="session")
def browser():
    with sync_playwright() as p:
        # 国内镜像源安装浏览器
        browser = p.chromium.launch(
            args=["--disable-web-security", "--font-render-hinting=none"]
        )
        yield browser
        browser.close()

@pytest.fixture
def page(browser):
    ctx = browser.new_context(locale="ar-SA", direction="rtl")
    page = ctx.new_page()
    # 禁用动画
    page.add_style_tag(content="*,*::before,*::after{transition:none!important;animation:none!important}")
    yield page
    ctx.close()

@pytest.fixture(params=["ltr", "rtl"], ids=["从左到右", "从右到左"])
def direction(request):
    return request.param

test_mirror.py

import pytest
from pathlib import Path
from PIL import Image
import numpy as np

SSIM_THRESHOLD = 0.98

def ssim(a: np.ndarray, b: np.ndarray) -> float:
    # 简化版 SSIM,面试现场手写核心公式即可
    ...

def test_navbar_mirror(page, direction, pytestconfig):
    # 1. 访问本地 dev server(国内用 127.0.0.1 避免 https 证书问题)
    page.goto("http://127.0.0.1:3000")
    page.evaluate(f"document.documentElement.setAttribute('dir', '{direction}')")
    page.wait_for_load_state("networkidle")

    # 2. 几何断言:导航栏第一个菜单项
    first_item = page.locator("nav ul li").first
    box = first_item.bounding_box()
    win_width = page.evaluate("window.innerWidth")
    if direction == "rtl":
        # 镜像后右边距应等于 LTR 的左边距
        expect_right = 20
        assert abs(win_width - box["x"] - box["width"] - expect_right) <= 1
    else:
        expect_left = 20
        assert abs(box["x"] - expect_left) <= 1

    # 3. 截图断言
    snapshot_dir = Path(__file__).parent / "snapshots" / direction
    snapshot_dir.mkdir(exist_ok=True)
    golden = snapshot_dir / "navbar.png"
    temp = snapshot_dir / "temp.png"
    page.locator("nav").screenshot(path=temp)

    if not golden.exists():
        temp.rename(golden)
        pytest.skip("首次运行,已保存基线")

    score = ssim(np.array(Image.open(golden)), np.array(Image.open(temp)))
    assert score >= SSIM_THRESHOLD, f"SSIM {score:.3f} < {SSIM_THRESHOLD}, 镜像可能退化"

运行

# 国内清华源安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pytest-playwright pillow
pytest -s --template-dir=rtl_tests/snapshots --baseline=ltr

失败示例

>       assert score >= SSIM_THRESHOLD
E       AssertionError: SSIM 0.972 < 0.98, 镜像可能退化
E       建议: 检查是否遗漏 transform: scaleX(-1) 或逻辑属性

拓展思考

  1. 多语言参数化:把“ar-SA, he-IL, fa-IR”做成第二个参数轴,与方向轴做笛卡尔积,一次运行 6 种组合。
  2. 逻辑属性 Lint:在 CI 里先跑 stylelint 插件 postcss-logical,只要出现 left/right 物理属性就失败,提前拦截。
  3. 性能基线:用 pytest-benchmark 统计 RTL 切换后首次渲染帧率,防止阿拉伯语字体过大导致掉帧。
  4. 暗黑模式交叉:RTL + Dark 双变量,用 pytest-dependency 保证先过 LTR Light,再测 RTL Dark,减少无效组合。
  5. 合规脱敏:若用 Applitools,需把 API 流量走企业阿里云 VPC 出口,避免用户截图出境;同时开启 redaction 字段,把价格、头像自动打码。