Community编程与开发github.com

Playwright CI 缓存

在 CI/CD 管道(GitHub Actions、Azure DevOps)中缓存 Playwright 浏览器二进制文件,避免每次构建时 1-2 分钟的下载开销。

Playwright CI 缓存 是什么?

该技能旨在解决 Playwright E2E 测试在 CI/CD 中的浏览器下载性能瓶颈。默认情况下,Playwright 浏览器(约 400MB)每次 CI 运行时都会重新下载,导致构建时间增加 1-2 分钟、带宽浪费以及网络不稳定时构建失败。它通过提取 Playwright 版本作为缓存键,缓存浏览器二进制文件,并在缓存未命中时仅执行条件安装,从而自动使缓存失效。该技能支持 GitHub Actions 和 Azure DevOps 管道,并提供了一个 `playwright.ps1` 辅助脚本,用于抽象 Playwright CLI 的路径。通过使用版本化缓存键,确保升级 Playwright 时自动使缓存失效,无需手动清理。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/playwright-ci-caching

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

在 CI/CD 中缓存 Playwright 浏览器

何时使用此技能

在以下情况下使用此技能:

  • 为包含 Playwright E2E 测试的项目设置 CI/CD
  • 由于浏览器下载(约 400MB,1-2 分钟)导致构建时间变慢
  • 希望在 Playwright 版本更改时自动使缓存失效
  • 使用 GitHub Actions 或 Azure DevOps 管道

问题

默认情况下,Playwright 浏览器(约 400MB)必须在每次 CI 运行时下载。这会导致:

  • 每次构建增加 1-2 分钟
  • 浪费带宽
  • 可能因临时网络问题而失败
  • 减慢 PR 反馈循环

核心模式

  1. 提取 Playwright 版本,从 Directory.Packages.props (CPM) 中读取,用作缓存键
  2. 缓存浏览器二进制文件,使用适合平台的路径
  3. 条件安装 - 仅在缓存未命中时下载
  4. 自动缓存失效 - 缓存键包含版本,因此包升级会使缓存失效

各操作系统的缓存路径

操作系统路径
Linux~/.cache/ms-playwright
macOS~/Library/Caches/ms-playwright
Windows%USERPROFILE%\AppData\Local\ms-playwright

GitHub Actions

- name: 获取 Playwright 版本
  shell: pwsh
  run: |
    $propsPath = "Directory.Packages.props"
    [xml]$props = Get-Content $propsPath
    $version = $props.Project.ItemGroup.PackageVersion |
      Where-Object { $_.Include -eq "Microsoft.Playwright" } |
      Select-Object -ExpandProperty Version
    echo "PlaywrightVersion=$version" >> $env:GITHUB_ENV

- name: 缓存 Playwright 浏览器
  id: playwright-cache
  uses: actions/cache@v4
  with:
    path: ~/.cache/ms-playwright
    key: ${{ runner.os }}-playwright-${{ env.PlaywrightVersion }}

- name: 安装 Playwright 浏览器
  if: steps.playwright-cache.outputs.cache-hit != 'true'
  shell: pwsh
  run: ./build/playwright.ps1 install --with-deps

多操作系统 GitHub Actions

适用于在多个操作系统上运行的工作流:

- name: 缓存 Playwright 浏览器
  id: playwright-cache
  uses: actions/cache@v4
  with:
    path: |
      ~/.cache/ms-playwright
      ~/Library/Caches/ms-playwright
      ~/AppData/Local/ms-playwright
    key: ${{ runner.os }}-playwright-${{ env.PlaywrightVersion }}

Azure DevOps

- task: PowerShell@2
  displayName: '获取 Playwright 版本'
  inputs:
    targetType: 'inline'
    script: |
      [xml]$props = Get-Content "Directory.Packages.props"
      $version = $props.Project.ItemGroup.PackageVersion |
        Where-Object { $_.Include -eq "Microsoft.Playwright" } |
        Select-Object -ExpandProperty Version
      Write-Host "##vso[task.setvariable variable=PlaywrightVersion]$version"

- task: Cache@2
  displayName: '缓存 Playwright 浏览器'
  inputs:
    key: 'playwright | "$(Agent.OS)" | $(PlaywrightVersion)'
    path: '$(HOME)/.cache/ms-playwright'
    cacheHitVar: 'PlaywrightCacheHit'

- task: PowerShell@2
  displayName: '安装 Playwright 浏览器'
  condition: ne(variables['PlaywrightCacheHit'], 'true')
  inputs:
    filePath: 'build/playwright.ps1'
    arguments: 'install --with-deps'

辅助脚本:playwright.ps1

创建一个 build/playwright.ps1 脚本,用于发现并运行 Playwright CLI。这抽象了因项目结构而异的 Playwright CLI 位置。

# build/playwright.ps1
# 发现 Microsoft.Playwright.dll 并运行捆绑的 Playwright CLI

param(
    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$Arguments
)

# 查找 Playwright DLL(在 dotnet build/restore 之后)
$playwrightDll = Get-ChildItem -Path . -Recurse -Filter "Microsoft.Playwright.dll" -ErrorAction SilentlyContinue |
    Select-Object -First 1

if (-not $playwrightDll) {
    Write-Error "未找到 Microsoft.Playwright.dll。请先运行 'dotnet build'。"
    exit 1
}

$playwrightDir = $playwrightDll.DirectoryName

# 查找 playwright CLI(路径因操作系统和 node 版本而异)
$playwrightCmd = Get-ChildItem -Path "$playwrightDir/.playwright/node" -Recurse -Filter "playwright.cmd" -ErrorAction SilentlyContinue |
    Select-Object -First 1

if (-not $playwrightCmd) {
    # 尝试 Unix 可执行文件
    $playwrightCmd = Get-ChildItem -Path "$playwrightDir/.playwright/node" -Recurse -Filter "playwright" -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -eq "playwright" } |
        Select-Object -First 1
}

if (-not $playwrightCmd) {
    Write-Error "在 $playwrightDir/.playwright/node 中未找到 Playwright CLI"
    exit 1
}

Write-Host "正在使用 Playwright CLI: $($playwrightCmd.FullName)"
& $playwrightCmd.FullName @Arguments

用法:

# 安装浏览器
./build/playwright.ps1 install --with-deps

# 安装特定浏览器
./build/playwright.ps1 install chromium

# 显示已安装的浏览器
./build/playwright.ps1 install --dry-run

前提条件

此模式假设:

  1. 集中包管理 (CPM) 使用 Directory.Packages.props:

    <Project>
      <ItemGroup>
        <PackageVersion Include="Microsoft.Playwright" Version="1.40.0" />
      </ItemGroup>
    </Project>
    
  2. 项目已构建,然后再运行 playwright.ps1(以便 DLL 存在)

  3. PowerShell 在 CI 代理上可用(GitHub Actions 和 Azure DevOps 上预装)

为什么基于版本的缓存键很重要

在缓存键中使用 Playwright 版本可确保:

  • 升级 Playwright 时自动失效
  • 不存在与 SDK 版本不匹配的过时浏览器二进制文件
  • 版本升级后无需手动清除缓存

如果硬编码缓存键(例如,playwright-browsers-v1),则每次升级 Playwright 时都需要手动更新,否则会出现晦涩的版本不匹配错误。

故障排除

缓存未使用

  1. 验证版本提取步骤是否输出正确的版本
  2. 检查缓存路径是否与您的操作系统匹配
  3. 确保 Directory.Packages.props 存在并包含 Playwright 包

缓存命中后 "找不到浏览器"

缓存的浏览器与 Playwright SDK 版本不匹配。这发生在以下情况:

  • 缓存键不包含版本
  • 版本提取静默失败

解决方法:确保 Playwright 版本在缓存键中。

playwright.ps1 找不到 DLL

在运行脚本之前,先运行 dotnet build 或 dotnet restore。Playwright DLL 仅在 NuGet 恢复后才存在。

参考

此模式已在生产项目中经过实战测试:

相关技能

  • dotnet-skills:playwright-blazor - 为 Blazor 应用程序编写 Playwright 测试
  • dotnet-skills:project-structure - 集中包管理设置

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

相关技能