柳嘉希

硕士研究生毕业生

软件工程师 | 可扩展的API · 网络爬虫 · 数据集成 · Vibe代码清理专家

pytest、Robot Framework 与 Playwright:fixture、关键字驱动和端到端测试

这几类测试工具解决的问题不同。pytest 更偏 Python 测试框架,Robot Framework 更偏关键字驱动的验收测试,Playwright 更偏现代 Web 端到端测试。

pytest 自动发现

pytest 会自动发现:

  • test_*.py
  • *_test.py
  • test_ 开头的函数
def test_add():
    assert 1 + 2 == 3

fixture

fixture 用来准备测试前置条件,也可以做测试后的清理。

import pytest
 
@pytest.fixture
def setup_env():
    print("prepare")
    yield
    print("cleanup")

测试函数只要把 fixture 名字写进参数,pytest 就会自动注入。

def test_example(setup_env):
    assert True

fixture scope

scope 决定 fixture 生命周期:

  • function:每个测试函数一次
  • class:每个测试类一次
  • module:每个文件一次
  • session:整个测试会话一次

真实项目里,公共 fixture 通常放在 conftest.py

Robot Framework

Robot Framework 的特点是关键字驱动,测试更接近业务语言。

*** Test Cases ***
Login With Valid User
    Open Browser To Login Page
    Login With Valid Credentials    ${USERNAME}    ${PASSWORD}
    Page Should Contain Element    id=dashboard

它适合验收测试、流程测试和让非开发人员也能读懂的自动化脚本。

Playwright

Playwright 更适合现代 Web E2E。

test("user can login", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Username").fill("jesse");
  await page.getByLabel("Password").fill("password");
  await page.getByRole("button", { name: "Login" }).click();
  await expect(page.getByTestId("dashboard")).toBeVisible();
});

减少 flaky 测试

不要用固定 sleep 当万能方案。

更好的方式:

  • 等元素可见
  • 等按钮可点击
  • 等请求完成
  • 等 URL 变化
  • 通过 API/DB 准备测试数据
  • UI 测试只覆盖核心路径

稳定测试的本质是等待“明确条件”,不是等待“固定时间”。