使用Selenium+Pytest实现Admin登录并截图对比

解读

在国内 Django 后端岗位面试中,这道题常被用来同时考察三项能力:

  1. 对 Django 自带 Admin 的熟悉程度(路由、CSRF、中间件、静态文件)
  2. 用 Selenium 编写可维护 UI 自动化用例的规范(POM、显式等待、失败重试、截图比对)
  3. 用 Pytest 组织测试、固件、参数化、断言以及生成 Allure 报告的能力

面试官通常会在 30 分钟内要求你:

  • 本地拉起一个全新 Django 项目
  • 创建超级用户
  • 用 Selenium 完成登录流程
  • 对登录成功页做整屏截图
  • 与“基准图”进行像素级比对,允许 1% 以内的差异(字体渲染、滚动条)
  • 用一条命令跑完整套用例并生成 HTML 报告

评分维度:代码结构、等待策略、异常处理、截图比对算法、运行稳定性、可移植性(Linux + 无头 Chrome)。

知识点

  1. Django Admin 登录流程
    • 路由 /admin/ → AdminSite.login
    • CSRF 令牌在 login.html 中的 csrfmiddlewaretoken 隐藏域
    • 登录失败会返回 200 并带 errornote 字段,不会 302
  2. Selenium 最佳实践
    • 显式等待 WebDriverWait + expected_conditions
    • pytest.fixture(scope="session") 复用浏览器,降低开销
    • Page Object 模式:LoginPage / AdminIndexPage
    • 无头模式与窗口大小固定(1366×768),避免元素错位
  3. 截图比对
    • 使用 Pillow.ImageChops.difference 计算像素差异
    • 允许动态区域遮罩(时间、用户名、版本号)
    • 差异率 = 不同像素数 / 总像素数,阈值 1%
  4. Pytest 技巧
    • pytest.mark.parametrize 覆盖“账号错误/密码错误/正常登录”
    • --html=report.html --self-contained-html 生成单文件报告
    • --base-url 自定义命令行参数,适配不同环境
  5. 持续集成
    • GitHub Actions / GitLab CI 中安装 chromium-driver 与 fonts-wqy-zenhei,解决中文渲染
    • 用 pytest-xvfb 在 Linux 无头环境运行

答案

项目结构 django_admin_login/ ├── manage.py ├── mysite/ ├── tests/ │ ├── conftest.py │ ├── pages/ │ │ ├── init.py │ │ ├── login_page.py │ │ └── admin_index_page.py │ ├── screenshots/ │ │ └── baseline.png │ ├── test_admin_login.py │ └── utils.py ├── requirements.txt └── pytest.ini

requirements.txt Django>=4.2,<5.0 selenium==4.15.0 pytest==7.4.3 pytest-html==4.1.1 Pillow==10.1.0

conftest.py import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options

@pytest.fixture(scope="session") def driver(): chrome_opts = Options() chrome_opts.add_argument("--headless=new") chrome_opts.add_argument("--no-sandbox") chrome_opts.add_argument("--disable-dev-shm-usage") chrome_opts.add_argument("--window-size=1366,768") # 解决中文渲染 chrome_opts.add_argument("--lang=zh-CN") chrome_opts.add_argument("--font-render-hinting=medium") _driver = webdriver.Chrome(options=chrome_opts) yield _driver _driver.quit()

@pytest.fixture(scope="session") def base_url(live_server): # live_server 由 pytest-django 提供 return live_server.url

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.url = "/admin/" self.username = (By.ID, "id_username") self.password = (By.ID, "id_password") self.login_btn = (By.CSS_SELECTOR, "input[type='submit']") self.errornote = (By.CLASS_NAME, "errornote")

def open(self, base_url):
    self.driver.get(base_url + self.url)

def login(self, username, password):
    WebDriverWait(self.driver, 10).until(
        EC.presence_of_element_located(self.username)
    ).send_keys(username)
    self.driver.find_element(*self.password).send_keys(password)
    self.driver.find_element(*self.login_btn).click()

def has_error(self):
    return bool(WebDriverWait(self.driver, 5).until(
        EC.presence_of_element_located(self.errornote)
    ))

pages/admin_index_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 AdminIndexPage: def init(self, driver): self.driver = driver self.site_name = (By.CSS_SELECTOR, "#site-name")

def wait_load(self):
    WebDriverWait(self.driver, 10).until(
        EC.visibility_of_element_located(self.site_name)
    )

utils.py from pathlib import Path from PIL import Image, ImageChops

def compare_screenshots(actual_path, baseline_path, threshold=0.01): actual = Image.open(actual_path).convert("RGB") baseline = Image.open(baseline_path).convert("RGB") diff = ImageChops.difference(actual, baseline) # 转换为灰度并计算差异像素 diff_gray = diff.convert("L") diff_pixels = sum(1 for p in diff_gray.getdata() if p > 0) total_pixels = diff_gray.size[0] * diff_gray.size[1] ratio = diff_pixels / total_pixels return ratio <= threshold, ratio

test_admin_login.py import pytest from pathlib import Path from pages.login_page import LoginPage from pages.admin_index_page import AdminIndexPage from utils import compare_screenshots

BASELINE = Path(file).with_name("screenshots") / "baseline.png"

@pytest.mark.django_db(transaction=True) @pytest.mark.parametrize("user,pwd,expect_success", [ ("admin", "wrong", False), ("wrong", "123456", False), ("admin", "123456", True), ]) def test_admin_login(driver, base_url, live_server, django_user_model, user, pwd, expect_success): # 预置超级用户 if user == "admin" and expect_success: django_user_model.objects.create_superuser( username="admin", password="123456", email="admin@example.com" )

login_page = LoginPage(driver)
login_page.open(base_url)
login_page.login(user, pwd)

if expect_success:
    index_page = AdminIndexPage(driver)
    index_page.wait_load()
    # 截图
    actual_png = Path(__file__).with_name("screenshots") / "actual.png"
    driver.save_screenshot(str(actual_png))
    ok, ratio = compare_screenshots(actual_png, BASELINE)
    assert ok, f"截图差异率 {ratio:.2%} 超过阈值"
else:
    assert login_page.has_error()

运行步骤

  1. 创建 Django 项目并迁移 django-admin startproject mysite cd mysite python manage.py migrate python manage.py collectstatic --noinput

  2. 安装依赖 pip install -r requirements.txt

  3. 生成基准图(仅一次) pytest tests/test_admin_login.py::test_admin_login -k "admin and 123456" --html=dummy.html cp tests/screenshots/actual.png tests/screenshots/baseline.png

  4. 完整回归 pytest -v --html=report.html --self-contained-html

拓展思考

  1. 多语言 & 多时区 在 settings.py 打开 USE_TZ = True 与 USE_I18N = True,CI 中需固定 TZ=Asia/Shanghai,否则时间戳区域会导致截图差异率飙升。
  2. 动态元素遮罩 对右上角“最近操作”或“时间”标签,可在比对前用 Pillow 画黑色矩形遮罩,降低误报。
  3. 并发执行 使用 pytest-xdist 并行跑用例时,每个 worker 需独立端口 --liveserver=localhost:0,并在 conftest.py 里动态分配 Chrome 端口,避免 Cookie 互串。
  4. 视觉回归与 UI 迭代 基准图应纳入 LFS(Git Large File Storage),并在 MR 阶段自动提醒 UI Diff,防止样式回归。
  5. 安全加固 生产环境关闭 /admin/ 或绑定 VPN;自动化测试使用一次性 superuser 并随用随删,防止硬编码账号泄露。
  6. 替代方案 若仅做接口测试,可用 django.test.Client 直接 POST /admin/login/ 获取 sessionid,跳过 Selenium,速度提升 10 倍;但题目明确要求 UI 级截图,所以 Selenium 仍是必选。