Community程式設計與開發github.com

playwright-ci-caching

在 CI/CD 管線(GitHub Actions、Azure DevOps)中快取 Playwright 瀏覽器二進位檔,避免每次建置時多花 1-2 分鐘的下載時間。

playwright-ci-caching 是什麼?

此技能旨在解決 Playwright E2E 測試在 CI/CD 環境中因每次建置都需下載約 400MB 瀏覽器二進位檔(耗時 1-2 分鐘)而導致的效能瓶頸。它透過從 `Directory.Packages.props` 中提取 Playwright 版本作為快取金鑰,實現自動化快取無效化;當 Playwright 版本更新時,快取會自動失效,確保瀏覽器二進位檔與 SDK 版本一致。支援 GitHub Actions 與 Azure DevOps 兩種主流 CI/CD 平台,提供 YAML 範例與跨作業系統的快取路徑(Linux、macOS、Windows)。此外,技能包含一個 `build/playwright.ps1` 輔助腳本,可自動發現 Playwright CLI 位置,並提供 `install --with-deps` 等指令,僅在快取未命中時才執行下載,顯著縮短回饋循環。

相容平台~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. 從 Directory.Packages.props(CPM)提取 Playwright 版本作為快取金鑰
  2. 根據平台路徑快取瀏覽器二進位檔
  3. 條件式安裝-僅在快取未命中時下載
  4. 自動快取失效-金鑰包含版本,升級套件時自動失效

各作業系統的快取路徑

作業系統路徑
Linux~/.cache/ms-playwright
macOS~/Library/Caches/ms-playwright
Windows%USERPROFILE%\AppData\Local\ms-playwright

GitHub Actions

- name: Get Playwright Version
  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: Cache Playwright Browsers
  id: playwright-cache
  uses: actions/cache@v4
  with:
    path: ~/.cache/ms-playwright
    key: ${{ runner.os }}-playwright-${{ env.PlaywrightVersion }}

- name: Install Playwright Browsers
  if: steps.playwright-cache.outputs.cache-hit != 'true'
  shell: pwsh
  run: ./build/playwright.ps1 install --with-deps

多作業系統 GitHub Actions

針對在多個作業系統上執行的工作流程:

- name: Cache Playwright Browsers
  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: 'Get Playwright Version'
  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: 'Cache Playwright Browsers'
  inputs:
    key: 'playwright | "$(Agent.OS)" | $(PlaywrightVersion)'
    path: '$(HOME)/.cache/ms-playwright'
    cacheHitVar: 'PlaywrightCacheHit'

- task: PowerShell@2
  displayName: 'Install Playwright Browsers'
  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 not found. Run 'dotnet build' first."
    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 "Playwright CLI not found in $playwrightDir/.playwright/node"
    exit 1
}

Write-Host "Using 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. CI 代理程式上可使用 PowerShell(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.

相關技能