第 4 章 Day 3:工程化,做成能交付的项目
第 4 章 Day 3:工程化,做成能交付的项目
目标:把昨天散落的脚本,变成一个“新人 10 分钟能跑起来”的项目。重点不是写更多用例,而是结构、复用、可观测性。约 5 小时。
4.1 pytest 必备知识
import pytest
@pytest.fixture
def user():
"""准备数据,用完自动清理。"""
return {"name": "admin"}
@pytest.mark.smoke
def test_login(user):
assert user["name"] == "admin"
@pytest.mark.parametrize("keyword", ["测试", "自动化", "订单"])
def test_search(keyword):
assert keyword
| 概念 | 说明 |
|---|---|
| 用例发现 | 文件 test_.py,函数 test_,类 Test* |
| fixture | 测试前置/后置,按参数名注入;作用域 function/class/module/session |
| conftest.py | 同目录及子目录共享的 fixture 与钩子 |
| 参数化 | @pytest.mark.parametrize,一条用例跑多组数据 |
| marker | @pytest.mark.smoke,配合 -m smoke 筛选 |
| 断言 | 直接 assert;异常用 pytest.raises |
| 跳过 | @pytest.mark.skipif(条件, reason=...) |
pytest -v # 详细输出
pytest -k login # 按名称筛选
pytest -m smoke # 按 marker 筛选
pytest --fixtures # 查看可用 fixture
4.2 pytest-playwright 内置能力
| fixture | 说明 |
|---|---|
| page | 每个用例一个新的 Page(新 context) |
| context | BrowserContext,可配 storage_state / viewport |
| browser | 整个 session 复用的 Browser |
| browser_name | chromium / firefox / webkit |
| base_url | 配合 page.goto("/login") 使用 |
| 命令行参数 | 作用 |
|---|---|
| --headed | 有头模式,调试必用 |
| --browser=firefox | 切换内核 |
| --device="iPhone 13" | 设备模拟 |
| --slowmo=500 | 每步放慢,肉眼看流程 |
| --tracing=on | 记录 trace(retain-on-failure 更实用) |
| --screenshot=only-on-failure | 失败自动截图 |
| --video=on | 录屏(慢、文件大,按需开) |
| --base-url=... | 指定被测环境 |
| --storage-state=auth.json | 复用登录态 |
| --ignore-https-errors | 忽略证书错误 |
# pytest.ini
[pytest]
testpaths = tests
addopts = -v --tracing retain-on-failure --screenshot only-on-failure
markers =
smoke: 冒烟用例
regression: 回归用例
4.3 推荐项目结构
qa-e2e/
├─ conftest.py # 全局 fixture(浏览器参数、登录态)
├─ pytest.ini # 运行配置
├─ requirements.txt
├─ README.md
├─ pages/ # 页面对象
│ ├─ __init__.py
│ ├─ base_page.py
│ └─ login_page.py
├─ tests/ # 用例
│ ├─ conftest.py
│ ├─ test_login.py
│ └─ test_order.py
├─ data/ # 测试数据(json / yaml)
├─ utils/ # 工具:日志、配置、造数
├─ scripts/ # 一次性脚本(生成登录态等)
└─ test-results/ # 产物,加入 .gitignore
- conftest.py 只放全局的东西;页面相关的 fixture 放 tests/conftest.py,避免根目录越来越臃肿;
- pages/ 不依赖 tests/,方向永远是“用例依赖页面对象”,不能反过来。
4.4 Page Object 完整示例
# pages/base_page.py
class BasePage:
def __init__(self, page, base_url: str = ""):
self.page = page
self.base_url = base_url
def open(self, path: str):
self.page.goto(f"{self.base_url}{path}")
# pages/login_page.py
from playwright.sync_api import Page, expect
class LoginPage:
PATH = "/login"
def __init__(self, page: Page):
self.page = page
self.username = page.get_by_label("用户名")
self.password = page.get_by_label("密码")
self.submit = page.get_by_role("button", name="登录")
def open(self):
self.page.goto(self.PATH)
def login(self, username: str, password: str) -> "LoginPage":
self.open()
self.username.fill(username)
self.password.fill(password)
self.submit.click()
return self
def expect_error(self, message: str):
expect(self.page.get_by_role("alert")).to_contain_text(message)
# tests/test_login.py
from playwright.sync_api import Page, expect
from pages.login_page import LoginPage
def test_login_success(page: Page):
LoginPage(page).login("admin", "123456")
expect(page.get_by_text("欢迎,admin")).to_be_visible()
def test_login_wrong_password(page: Page):
LoginPage(page).login("admin", "wrong")
expect(page.get_by_text("用户名或密码错误")).to_be_visible()
提示:页面对象只负责“动作 + 组件级断言”;业务级断言(下单成功、金额正确)留在用例里。否则同一个断言散落在多处,改需求时要改十个文件。
4.5 登录态复用:storage_state
UI 登录慢且不稳定。做法是登录一次,把 cookie/localStorage 存成 auth.json,后续用例直接带上。
# scripts/gen_auth.py(只需跑一次,或 CI 里每次跑)
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com/login")
page.get_by_label("用户名").fill("admin")
page.get_by_label("密码").fill("123456")
page.get_by_role("button", name="登录").click()
page.wait_for_url("**/dashboard")
context.storage_state(path="auth.json")
browser.close()
# conftest.py:让所有用例默认带上登录态
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {**browser_context_args, "storage_state": "auth.json"}
- 也可以临时指定:pytest --storage-state=auth.json;
- auth.json 不要提交到 git,它等价于账号密码;
- token 会过期:CI 里建议用“登录一次生成”的 setup 步骤,或把账号放 secrets。
4.6 配置与环境
# .env
BASE_URL=https://test.example.com
TEST_USER=admin
TEST_PWD=123456
# conftest.py
import os
from dotenv import load_dotenv
load_dotenv()
@pytest.fixture(scope="session")
def base_url():
return os.getenv("BASE_URL", "https://test.example.com")
- 多环境:pytest --base-url=$env:TEST_URL(PowerShell);
- 密码一律走环境变量 / CI secrets,代码里不出现明文;
- 需要多套配置时,用 pytest -c pytest.staging.ini 或环境变量切换。
4.7 数据驱动
# data/cases.json
[
{"keyword": "测试", "expect_count": 3},
{"keyword": "自动化", "expect_count": 0}
]
import json
from pathlib import Path
import pytest
CASES = json.loads(Path("data/cases.json").read_text(encoding="utf-8"))
@pytest.mark.parametrize("case", CASES, ids=lambda c: c["keyword"])
def test_search(page, case):
page.get_by_placeholder("搜索").fill(case["keyword"])
page.get_by_placeholder("搜索").press("Enter")
expect(page.get_by_role("row")).to_have_count(case["expect_count"])
4.8 报告与产物
pip install pytest-html pytest-xdist pytest-rerunfailures
pytest --html=report.html --self-contained-html
pytest -n auto # 并行(每个 worker 独立浏览器)
pytest --reruns 2 --reruns-delay 1 # 失败重试,仅用于排除偶发
pytest --tracing on --video on # 全量产物(调试时用)
| 产物 | 是否进 CI artifact | 说明 |
|---|---|---|
| trace.zip | 建议(仅失败) | 排障主力,几 MB |
| report.html | 建议 | 给人看的汇总 |
| 截图 | 可选 | 失败时自动截 |
| 视频 | 不建议默认开 | 体积大、拖慢 30%+ |
4.9 稳定性治理
| 问题 | 策略 |
|---|---|
| 偶发超时 | 先看 trace;缩短链路(mock 不稳定接口),不要全局调大超时 |
| 等待 | 禁用 sleep;用 expect 或 expect_response |
| 数据竞争 | 并行时每个 worker 用独立账号/独立数据前缀 |
| 定位脆弱 | 语义定位 + 推动前端加 data-testid |
| 重试 | --reruns 2 只兜底,重试率高说明用例本身有问题 |
4.10 CI:GitHub Actions 示例
name: e2e
on:
push:
branches: [main]
schedule:
- cron: "0 1 * * *" # 每天 09:00(UTC+8)回归
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Cache browsers
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: pw-${{ hashFiles('requirements.txt') }}
- run: pip install -r requirements.txt
- run: python -m playwright install --with-deps chromium
- run: pytest -n auto --html=report.html --self-contained-html
- uses: actions/upload-artifact@v4
if: always()
with:
name: report
path: |
report.html
test-results/
- 容器里没有中文字体时,安装 fonts-noto-cjk,否则截图中文变方块;
- CI 用 --with-deps 一次性装齐系统依赖;
- 定时任务跑全量回归,push 只跑冒烟(-m smoke),节省时长。
4.11 Day 3 综合任务
用你自己的系统完成下面 4 步,做完第 3 天就结束了:
1. 写 3 条用例:登录成功、列表搜索、一个写操作(新增/修改/删除之一);
2. 抽 2 个 Page Object(登录页 + 业务页),用例里不出现任何选择器;
3. 开启 --tracing retain-on-failure 与失败截图,跑一遍并打开 trace;
4. 写一个 run.ps1(或 Makefile):装依赖、跑全量、生成报告,一条命令完成。
4.12 交付检查清单
| 检查项 | 标准 |
|---|---|
| README | 环境、命令、目录说明,新人照着能跑 |
| 依赖 | requirements.txt 固定版本,不依赖隐式全局包 |
| 配置 | 无硬编码账号/URL,全部走环境变量 |
| 用例 | 独立、可重复、无顺序依赖 |
| 排障 | 失败可定位:trace + 截图 + 清晰报错 |
| CI | 绿灯,且失败时会留产物 |
| 维护 | 改一个定位只改一处(POM) |