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

如何基于多服务器多凭据并行运行Playwright测试?

多服务器多凭据并行运行Playwright测试入门指南

1. 先整理测试配置数据

把需要测试的服务器地址、对应凭据整理成结构化数据,直接写在测试文件里或者单独存为JSON文件,方便维护:

// 测试配置数组,每个元素对应一个服务器+凭据组合
const testTargets = [
  { server: 'https://server-01.example.com', user: 'admin01', pwd: 'testpass01' },
  { server: 'https://server-02.example.com', user: 'admin02', pwd: 'testpass02' },
  { server: 'https://server-03.example.com', user: 'admin03', pwd: 'testpass03' }
];

2. 用Playwright Test的test.each()实现参数化

Playwright Test内置的test.each()可以直接遍历你的配置数组,为每个组合生成独立的测试用例,自动实现并行的基础:

const { test, expect } = require('@playwright/test');

const testTargets = [
  { server: 'https://server-01.example.com', user: 'admin01', pwd: 'testpass01' },
  { server: 'https://server-02.example.com', user: 'admin02', pwd: 'testpass02' }
];

// 遍历配置,每个组合生成一个测试实例
test.each(testTargets)('登录验证 - 服务器: %s', async ({ page, server, user, pwd }) => {
  // 跳转到目标服务器
  await page.goto(server);
  // 执行登录操作
  await page.locator('#username').fill(user);
  await page.locator('#password').fill(pwd);
  await page.locator('button[type="submit"]').click();
  // 验证登录成功
  await expect(page.locator('.user-profile')).toHaveText(`当前用户: ${user}`);
});

test.each()会自动给每个测试用例命名(比如登录验证 - 服务器: https://server-01.example.com),方便后续排查问题。

3. 配置并行运行规则

在playwright.config.js里开启全并行,并根据机器性能调整worker数量,确保测试能高效并行:

module.exports = {
  testDir: './tests',
  fullyParallel: true, // 开启所有测试用例并行
  workers: process.env.CI ? 4 : undefined, // CI环境固定4个worker,本地自动适配CPU核心数
  use: {
    headless: true, // 无头模式运行,节省资源
    viewport: { width: 1280, height: 720 }
  }
};

Playwright默认会为每个参数化测试用例分配独立的worker,互不干扰,不需要额外做隔离处理。

4. 敏感凭据的安全处理(可选)

不要把明文凭据写在代码里,用环境变量或者加密配置文件:

  • 用环境变量的话,修改配置数组:
const testTargets = [
  { server: process.env.SRV1_URL, user: process.env.SRV1_USER, pwd: process.env.SRV1_PWD },
  { server: process.env.SRV2_URL, user: process.env.SRV2_USER, pwd: process.env.SRV2_PWD }
];

运行前在终端设置环境变量,或者用dotenv包加载.env文件。

5. 运行测试并查看结果

直接执行命令启动测试:

npx playwright test

测试完成后,生成可视化报告方便排查:

npx playwright show-report

报告里会清晰展示每个服务器测试的运行状态、耗时和失败原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:05:11