在 Playwright HTML 报告中显示元数据:完整指南

来源:undefined 2025-01-20 02:37:46 1027

playwright 测试框架的 html 报告功能强大,但对于大型项目而言,其简洁性可能显得不足。 本文将深入探讨如何为 playwright html 报告添加元数据,例如提交信息、作者信息和 ci 构建链接,从而提升报告的可读性和信息量。

Playwright 元数据配置的真相

Playwright 文档中关于元数据的描述已过时。虽然文档提到可以使用 metadata 字段,但实际上只有特定的字段会被 HTML 报告识别。 经过源码分析,支持的元数据字段如下:

1

2

3

4

5

6

7

8

9

10

export type metainfo = {

revision.id?: string;

revision.author?: string;

revision.email?: string;

revision.subject?: string;

revision.timestamp?: number | Date;

revision.link?: string;

ci.link?: string;

timestamp?: number;

};

登录后复制

正确的配置方法如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import { defineConfig } from @playwright/test;

export default defineConfig({

reporter: html,

metadata: {

revision.id: adcb0c51debdbe96a6a836e2ead9d40a859f6438,

revision.author: John Smith,

revision.email: john.smith@gmail.com,

revision.subject: Acceptance Tests,

revision.timestamp: Date.now(),

revision.link: https://github.com/microsoft/playwright/pull/12734,

ci.link: https://github.com/microsoft/playwright/actions/workflows/tests_primary.yml,

timestamp: Date.now(),

},

});

登录后复制

运行测试后,这些元数据将显示在 HTML 报告的标题中。

立即学习前端免费学习笔记(深入)”;

自动化元数据填充

手动填写元数据并不实际。 以下介绍几种自动化方法:

第三方库: 可以使用诸如 git-rev-parse 等工具来提取 Git 提交信息。

Playwright 的隐藏插件系统: Playwright 拥有一个未公开的插件系统,允许通过 @playwright/test 配置项添加自定义插件。 例如,一个名为 gitcommitinfo 的插件可以自动填充 Git 提交信息。 使用示例如下:

1

2

3

4

5

6

7

8

9

10

import { defineConfig } from @playwright/test;

import { gitcommitinfo } from playwright/lib/plugins; // 假设此插件存在

export default defineConfig({

reporter: html,

// @ts-expect-error  (因为插件未公开)

@playwright/test: {

plugins: [gitcommitinfo()],

},

});

登录后复制

该插件会自动填充提交哈希、提交信息、作者信息和时间戳等元数据。

自定义函数: 可以编写自定义函数来提取 Git 信息或其他元数据。 为了避免在每个 worker 中重复执行,建议只在主 worker 中执行此函数:

1

2

3

4

5

6

7

8

9

import { defineConfig } from @playwright/test;

import { gitStatusFromCLI } from ./commitInfo; // 自定义函数

const isMainWorker = !process.env.TEST_WORKER_INDEX;

export default defineConfig({

reporter: html,

metadata: isMainWorker ? gitStatusFromCLI() : undefined,

});

登录后复制

gitStatusFromCLI 函数示例 (需要根据实际情况调整):

1

2

3

4

import { spawnSync } from node:child_process;

import { randomUUID } from node:crypto;

// ... (函数实现,类似原文) ...

登录后复制

虽然 Playwright 的文档未完整描述元数据功能,但通过了解实际支持的字段和运用自动化方法,我们可以显著增强 HTML 报告的实用性。 选择手动配置、使用隐藏插件或自定义函数取决于项目的具体需求和复杂性。 记住优化并行测试以避免性能瓶颈。

以上就是在 Playwright HTML 报告中显示元数据:完整指南的详细内容,更多请关注php中文网其它相关文章!

最新文章