You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright测试套件并行转串行执行配置问题咨询

解决方案

要实现分阶段并行/串行执行的需求,核心是给不同阶段的测试单独配置项目,指定各自的worker数,并控制执行顺序。以下是具体实现步骤:

1. 拆分测试项目配置

在playwright.config.ts中,把测试拆成3个独立项目,分别对应你的三个执行阶段:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    // 阶段1:并行执行section 01
    {
      name: 'section01',
      testMatch: 'tests/section01/**/*.spec.ts', // 匹配section01所有用例
      workers: 4, // 指定4个worker并行执行
    },
    // 阶段2:并行执行section02中可并行的用例
    {
      name: 'section02-parallel',
      testMatch: 'tests/section02/**/*.spec.ts',
      grepInvert: /@serial/, // 排除标记了@serial的不可并行用例
      workers: 4,
      dependencies: ['section01'], // 依赖section01,确保先完成环境配置再执行
    },
    // 阶段3:串行执行section02中不可并行的用例
    {
      name: 'section02-serial',
      testMatch: 'tests/section02/**/*.spec.ts',
      grep: /@serial/, // 只执行标记了@serial的用例
      workers: 1, // 强制1个worker串行执行
      dependencies: ['section02-parallel'], // 依赖并行阶段,确保先完成并行测试再执行串行
    },
  ],
});

2. 标记不可并行的测试用例

给section02中涉及日期修改、数据清理的用例加上@serial标签,让配置文件能精准筛选:

// tests/section02/date-handle.spec.ts
test('修改系统日期', { tag: '@serial' }, async ({ page }) => {
  // 你的测试逻辑
});

test('清理测试数据', { tag: '@serial' }, async ({ page }) => {
  // 你的测试逻辑
});

如果这些串行用例之间存在依赖(比如必须先修改日期再清理数据),可以用test.describe.serial确保它们内部的执行顺序:

test.describe.serial('日期修改与数据清理组', () => {
  test('修改系统日期', { tag: '@serial' }, async ({ page }) => { /* ... */ });
  test('验证日期关联功能', { tag: '@serial' }, async ({ page }) => { /* ... */ });
  test('恢复日期并清理数据', { tag: '@serial' }, async ({ page }) => { /* ... */ });
});

3. 执行测试

直接执行所有项目,Playwright会按照dependencies定义的顺序自动执行:

npx playwright test

执行流程为:

  • 先跑section01(4个worker并行)
  • 完成后跑section02-parallel(4个worker并行,排除@serial用例)
  • 最后跑section02-serial(1个worker串行执行所有@serial用例)

问题原因说明

你之前的配置未达预期,大概率是没有给串行阶段的项目单独设置workers: 1。Playwright中项目级的workers配置会覆盖全局配置,只要给section02-serial单独指定workers:1,就能确保该阶段只用1个worker执行。

如果不想用项目依赖,也可以用命令行分阶段执行,每个阶段指定worker数:

# 执行section01,4个worker
npx playwright test section01 --workers=4
# 执行section02并行用例,4个worker
npx playwright test section02 --grep-invert="@serial" --workers=4
# 执行section02串行用例,1个worker
npx playwright test section02 --grep="@serial" --workers=1

这种方式更灵活,但项目配置的方式更易于长期维护。

内容的提问来源于stack exchange,提问作者User101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:47:24