Playwright 并行测试:配置与优化技巧

49 阅读4分钟

当你需要运行大量测试用例时,串行执行会消耗大量时间。想象一下,500个测试用例每个耗时1分钟,串行执行需要8个多小时——这在实际开发中是不可接受的。Playwright的并行测试能力可以将这个时间缩短到几分钟,大幅提升开发和交付效率。

基础并行配置

1. 配置workers数量

在Playwright配置文件中,最直接的并行设置是通过workers参数:

// playwright.config.jsmodule.exports = {// 使用系统CPU核心数的50%作为默认workersworkers: process.env.CI ? 4 : '50%',// 或者固定worker数量// workers: 4,// 完全并行模式(不推荐用于所有场景)// fullyParallel: true,use: {    baseURL: 'https://your-app.com',    headless: true,  }};

实践经验:在CI/CD环境中,通常设置为固定值(如4),因为CI环境的核心数是确定的。本地开发可以使用百分比,自动适应不同开发者的机器配置。

2. 测试文件级别的并行

默认情况下,Playwright会在不同的worker中并行运行测试文件。但要确保测试之间没有依赖关系:

// 错误的示例 - 测试之间存在依赖test.describe('用户流程', () => {  test('注册用户', async ({ page }) => {    // 注册操作  });  test('登录用户', async ({ page }) => {    // 这里假设上一步已注册用户 - 这会导致并行执行时失败  });});// 正确的做法 - 每个测试独立test.describe('认证模块', () => {  test('用户注册流程', async ({ page }) => {    // 完整的注册测试  });  test('用户登录流程', async ({ page }) => {    // 使用预置的测试账号,不依赖其他测试  });});

高级并行策略

3. 使用Sharding实现跨机器并行

当测试套件非常庞大时,单机并行可能仍不够快。这时可以使用分片(Sharding):

# 将测试分成4个分片,在4台机器上运行npx playwright test --shard=1/4npx playwright test --shard=2/4npx playwright test --shard=3/4npx playwright test --shard=4/4

在CI/CD中,可以这样配置:

# GitHub Actions 示例jobs:test-shard:    strategy:      matrix:        shard-index:[1,2,3,4]        shard-total:[4]    runs-on:ubuntu-latest    steps:      -run:npxplaywrighttest--shard=${{matrix.shard-index}}/${{matrix.shard-total}}

4. 基于标签的并行执行

通过给测试打标签,可以实现更精细的并行控制:

// 给测试添加标签test('关键路径测试 @critical', async ({ page }) => {// 关键业务逻辑测试});test('性能测试 @slow', async ({ page }) => {// 耗时较长的性能测试});// 只运行关键测试npx playwright test --grep "@critical"// 排除慢测试npx playwright test --grep-invert "@slow"

优化技巧

5. 测试隔离与状态管理

并行测试最大的挑战是测试隔离。以下是几种解决方案:

方案A:使用独立测试数据

test('用户操作测试', async ({ page }) => {  // 为每个测试生成唯一用户  const uniqueUser = `testuser_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;    await page.fill('#username', uniqueUser);  await page.fill('#password', 'TestPass123!');  // ... 其他操作});

方案B:利用Playwright的测试隔离

// 每个测试获得完全独立的contexttest.describe('购物车测试', () => {  // 每个测试都会获得全新的浏览器上下文  test('添加商品到购物车', async ({ page, context }) => {    // 这里的context是全新的  });    test('清空购物车', async ({ page }) => {    // 这个测试不会受到上一个测试的影响  });});

6. 资源竞争处理

数据库竞争问题

// 创建测试专用的数据库工具class TestDatabase {constructor() {    this.connectionPool = [];  }async getUniqueConnection(testId) {    // 为每个测试worker提供独立的数据库连接    const connection = awaitthis.createConnection();    await connection.query(`USE test_${testId}`);    return connection;  }}// 在测试中应用test.beforeEach(async ({}, testInfo) => {const db = await testDatabase.getUniqueConnection(testInfo.workerIndex);// 使用独立的数据库schema});

7. 配置文件优化

// 优化的playwright.config.jsmodule.exports = {// 根据测试类型动态调整workersworkers: process.env.TEST_TYPE === 'e2e' ? 2 :            process.env.TEST_TYPE === 'component' ? 4 :            '50%',// 重试策略 - 对于并行测试很重要retries: process.env.CI ? 2 : 1,// 超时设置timeout: 30000,// 报告配置reporter: [    ['html', { outputFolder: 'playwright-report', open: 'never' }],    ['junit', { outputFile: 'results.xml' }],    ['list']  ],// 项目配置 - 针对不同类型的测试使用不同配置projects: [    {      name: 'chromium',      use: { browserName: 'chromium' },    },    {      name: 'firefox',      use: { browserName: 'firefox' },      // 为Firefox使用更少的workers      workers: 2,    },  ],};

8. 避免常见陷阱

陷阱1:全局状态污染

// 错误做法let sharedData = {}; // 全局变量在并行测试中会被污染// 正确做法test.beforeEach(async ({}) => {  const localData = {}; // 每个测试有自己的数据});

陷阱2:文件系统竞争

// 错误做法const fs = require('fs');test('生成报告', async () => {  fs.writeFileSync('report.json', data); // 多个worker会竞争同一个文件});// 正确做法test('生成报告', async ({}, testInfo) => {  const reportFile = `reports/report_${testInfo.workerIndex}.json`;  fs.writeFileSync(reportFile, data);});

9. 监控与调试

创建并行测试监控工具:

// parallel-monitor.jsconst { chromium } = require('playwright');asyncfunction monitorParallelExecution() {console.log(`开始时间: ${new Date().toISOString()}`);console.log(`CPU核心数: ${require('os').cpus().length}`);console.log(`Worker数量: ${process.env.PLAYWRIGHT_WORKERS || '默认'}`);// 监控资源使用  setInterval(() => {    const used = process.memoryUsage();    console.log(`内存使用: ${Math.round(used.heapUsed / 1024 / 1024)}MB`);  }, 5000);}module.exports = monitorParallelExecution;

性能调优建议

  1. 逐步增加workers:从较少的workers开始,逐步增加,观察系统负载和测试稳定性。

  2. 内存管理:每个Playwright worker大约消耗100-300MB内存。确保系统有足够内存:所需内存 ≈ workers数量 × 250MB

  3. 测试分组策略

    // 按测试时长分组,实现负载均衡const testGroups = {  fast: ['登录测试', '导航测试'],  medium: ['购物流程', '搜索测试'],  slow: ['文件上传', '报表生成']};
    
  4. 使用缓存加速

    # 在CI中缓存Playwright浏览器- name: Cache Playwright browsers  uses: actions/cache@v3  with:    path: ~/.cache/ms-playwright    key: playwright-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
    

结语

并行测试配置不是一次性的工作,而是一个持续优化的过程。开始时可以先实现基础并行,随着测试套件的增长和团队经验的积累,逐步引入更高级的策略。

记住,并非所有测试都适合并行。有些测试需要共享特定环境或状态,这些测试应该单独运行或放在同一个worker中。关键是找到适合你项目的最佳平衡点。

最后,定期审查测试执行时间,移除或优化耗时过长的测试,保持测试套件的健康状态。一个良好的并行测试配置,配合精心设计的测试用例,将为你节省大量时间,加速开发流程。