使用 GAN 自动生成缺失像素并评估 PSNR。

解读

面试官把“GAN 补图 + PSNR 评估”抛给 Selenium 岗位,并不是要候选人去写模型代码,而是考察三层能力:

  1. 能否把非 UI 自动化问题快速拆解成“测试脚本可落地”的子任务;
  2. 是否理解WebDriver 的边界,知道哪些步骤必须跳出浏览器、交给 Python 脚本或 CI 流水线;
  3. 能否给出可量化的质量门禁(PSNR 阈值、回归基线、报告格式),并与现有 Selenium+Pytest+Allure 体系打通。
    在国内大厂实际项目中,GAN 补图通常由算法组提供 HTTP 接口或 Docker 服务,Selenium 自动化要做的只是“调接口→下载结果→算指标→断言报告”。因此答案必须体现“测试 orchestration”思维,而非深度学习细节。

知识点

  1. WebDriver 与浏览器沙箱限制:前端页面无法直接调用本地 GPU 模型,需通过脚本端桥接。
  2. 缺失像素模拟:用 Canvas API 或 CSS mask 在页面上造出随机遮挡,保证测试可重复。
  3. GAN 服务化:算法组一般暴露 /inpaint 接口,输入 base64 图片,返回补全后 PNG;需抓包或读 Swagger 文档。
  4. PSNR 计算:OpenCV cv2.PSNR 或 Skimage peak_signal_noise_ratio,注意 RGB 浮点归一化范围。
  5. Selenium 文件下载:设置 ChromePrefs 的 download.default_directory 与 safebrowsing.enabled=false,避免弹窗。
  6. Pytest 参数化:用 @pytest.mark.parametrize("mask_type", ["center", "random", "text"]) 实现多场景回归。
  7. Allure 附件:allure.attach.file("diff.png", name="GAN-Diff", attachment_type=AttachmentType.PNG) 可视化差异。
  8. 质量门禁:PSNR ≥ 32 dB 且 SSIM ≥ 0.92 才能通过 CI,否则标记为 BLOCK,合并请求自动打回。
  9. 并发性能:若算法服务单卡推理 300 ms,需用 pytest-xdist -n 4 并行,避免 WebDriver 等待累积。
  10. 合规与版权:国内金融、医疗项目需脱敏,GAN 补图不能还原出敏感信息,需额外引入人脸/文字擦除检测。

答案

下面给出一条可在 Jenkins 上直接跑的最小可运行流水线脚本(Python 3.9,Selenium 4.15,Pytest 7.4),体现“端到端测试 orchestration”思路,关键步骤已加粗:

# conftest.py
import pytest, os, base64, cv2, numpy as np, requests
from selenium import webdriver
from pathlib import Path

@pytest.fixture(scope="session")
def driver():
    opt = webdriver.ChromeOptions()
    opt.add_argument("--headless=new")
    **p = Path("tmp_download").absolute(); p.mkdir(exist_ok=True)**
    opt.add_experimental_option("prefs", {
        "download.default_directory": str(p),
        "safebrowsing.enabled": False
    })
    d = webdriver.Chrome(options=opt)
    yield d
    d.quit()

@pytest.fixture(scope="session")
def gan_url():
    **return os.getenv("GAN_SERVICE", "http://algo-team.inpaint:8501/inpaint")**
# test_inpaint.py
import allure, cv2, base64, io, requests
from PIL import Image
from skimage.metrics import peak_signal_noise_ratio as psnr

MASK_RATIO = 0.25
PSNR_THRESHOLD = 32.0

@allure.title("GAN 补全后 PSNR 达标")
def test_gan_inpaint_psnr(driver, gan_url):
    driver.get("https://test-app.company.com/gallery")
    **origin_img = driver.execute_script("""
        const c = document.createElement('canvas');
        const img = document.querySelector('#source');
        c.width=img.naturalWidth; c.height=img.naturalHeight;
        const ctx=c.getContext('2d'); ctx.drawImage(img,0,0);
        return c.toDataURL('image/png').split(',')[1];
    """)**

    # 构造缺失像素图
    np_img = cv2.imdecode(np.frombuffer(base64.b64decode(origin_img), np.uint8), 1)
    h, w = np_img.shape[:2]
    mask = np.zeros((h, w), dtype=np.uint8)
    **cv2.rectangle(mask, (w//4, h//4), (3*w//4, 3*h//4), 255, -1)**
    masked = np_img.copy()
    masked[mask==255] = 0
    _, buf = cv2.imencode('.png', masked)
    masked_b64 = base64.b64encode(buf).decode()

    # 调用 GAN 服务
    resp = requests.post(gan_url, json={"image": masked_b64, "mask": base64.b64encode(mask).decode()}, timeout=10)
    resp.raise_for_status()
    **inpaint_b64 = resp.json()["result"]**
    inpaint_np = cv2.imdecode(np.frombuffer(base64.b64decode(inpaint_b64), np.uint8), 1)

    # 计算 PSNR
    score = psnr(np_img, inpaint_np)
    allure.attach(f"{score:.2f} dB", name="PSNR", attachment_type=allure.attachment_type.TEXT)
    **assert score >= PSNR_THRESHOLD, f"PSNR {score:.2f} < 阈值 {PSNR_THRESHOLD}"**

本地运行:
pytest -n 4 --alluredir=report && allure serve report

Jenkinsfile(国内镜像加速):

pipeline {
  agent { label "selenium-py39" }
  environment { GAN_SERVICE = credentials('gan-service-url') }
  stages {
    stage('测试') {
      steps {
        sh 'pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple'
        sh 'pytest -n 4 --alluredir=report'
      }
    }
    stage('质量门禁') {
      steps {
        **allure thresholds: [[thresholdName: 'psnr', unstableThreshold: '32']]**
      }
    }
  }
}

拓展思考

  1. 跨浏览器一致性:GAN 服务返回图片体积较大(1-2 MB),Chrome 与 Firefox 在 canvas.toDataURL() 的默认压缩率不同,需在脚本里统一 quality=1.0,否则 PSNR 会出现 0.3 dB 级抖动。
  2. 模型版本回归:算法组每两周发版,可在 Allure 趋势图里把 PSNR 当 KPI 曲线;若连续两次迭代下降 >0.5 dB,自动 @算法负责人。
  3. 鲁棒性测试:用 Selenium BiDi API 在网速 50 kbps、丢包 5% 的 Chrome DevTools 预设下跑同一条用例,验证 GAN 服务超时重试逻辑,避免前端一直转圈。
  4. 安全合规:国内《个人信息保护法》要求对含人脸的测试图进行“可逆匿名化”,可在上传前用同一 GAN 接口先做人脸抹除,再进入缺失像素补全流程,实现“双保险”。
  5. 无参考指标:若 ground-truth 缺失,可改用 NIQE/BRISQUE 无参考评分,通过 Selenium 脚本把结果回写 TestRail,实现“0 人工”的算法效果回归。