cache-navegadores-playwright-ci

Armazena em cache os binários dos navegadores Playwright em pipelines CI/CD (GitHub Actions, Azure DevOps) para evitar a sobrecarga de download de 1-2 minutos a cada compilação.

O que é cache-navegadores-playwright-ci?

Esta skill otimiza pipelines CI/CD para projetos que utilizam Playwright para testes E2E, evitando que os binários dos navegadores (~400 MB) sejam baixados a cada execução, o que normalmente adiciona de 1 a 2 minutos ao tempo de build. Ela é suportada no GitHub Actions e Azure DevOps e funciona extraindo a versão do Playwright do arquivo `Directory.Packages.props` (gerenciamento central de pacotes), utilizando-a como chave de cache. Quando a versão do Playwright muda, o cache é automaticamente invalidado, garantindo que apenas binários compatíveis com a SDK sejam usados. A skill também fornece um script auxiliar (`build/playwright.ps1`) que descobre e executa a CLI do Playwright, abstraindo variações de estrutura de projeto e sistema operacional. Ao aplicar essa técnica, o feedback loop dos PRs é acelerado, o uso de largura de banda é reduzido e falhas intermitentes de rede são minimizadas.

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

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Cache de Navegadores Playwright em CI/CD

Quando Usar Esta Skill

Use esta skill quando:

  • Estiver configurando CI/CD para um projeto com testes E2E Playwright
  • Os tempos de build estiverem lentos devido ao download dos navegadores (~400MB, 1-2 minutos)
  • Desejar invalidação automática de cache quando a versão do Playwright mudar
  • Estiver usando GitHub Actions ou Azure DevOps pipelines

O Problema

Por padrão, os navegadores Playwright (~400MB) são baixados a cada execução de CI. Isso:

  • Adiciona 1-2 minutos a cada build
  • Desperdiça largura de banda
  • Pode falhar devido a problemas de rede transitórios
  • Retarda o ciclo de feedback dos PRs

Padrão Principal

  1. Extrair a versão do Playwright de Directory.Packages.props (CPM) para usar como chave de cache
  2. Armazenar os binários do navegador em cache usando caminhos apropriados para cada plataforma
  3. Instalação condicional - baixar somente quando houver falta no cache
  4. Quebra automática de cache - a chave inclui a versão, então as atualizações de pacote invalidam o cache

Caminhos de Cache por SO

SOCaminho
Linux~/.cache/ms-playwright
macOS~/Library/Caches/ms-playwright
Windows%USERPROFILE%\AppData\Local\ms-playwright

GitHub Actions

- name: Obter Versão do 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: Cache dos Navegadores Playwright
  id: playwright-cache
  uses: actions/cache@v4
  with:
    path: ~/.cache/ms-playwright
    key: ${{ runner.os }}-playwright-${{ env.PlaywrightVersion }}

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

GitHub Actions Multi-SO

Para workflows que rodam em múltiplos sistemas operacionais:

- name: Cache dos Navegadores 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: 'Obter Versão do 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: 'Cache dos Navegadores Playwright'
  inputs:
    key: 'playwright | "$(Agent.OS)" | $(PlaywrightVersion)'
    path: '$(HOME)/.cache/ms-playwright'
    cacheHitVar: 'PlaywrightCacheHit'

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

Script Auxiliar: playwright.ps1

Crie um script build/playwright.ps1 que descobre e executa a CLI do Playwright. Isso abstrai a localização da CLI do Playwright, que varia conforme a estrutura do projeto.

# build/playwright.ps1
# Descobre Microsoft.Playwright.dll e executa a CLI Playwright empacotada

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

# Encontra a DLL do Playwright (após 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 não encontrada. Execute 'dotnet build' primeiro."
    exit 1
}

$playwrightDir = $playwrightDll.DirectoryName

# Encontra a CLI do Playwright (caminho varia por SO e versão do node)
$playwrightCmd = Get-ChildItem -Path "$playwrightDir/.playwright/node" -Recurse -Filter "playwright.cmd" -ErrorAction SilentlyContinue |
    Select-Object -First 1

if (-not $playwrightCmd) {
    # Tenta executável 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 "CLI do Playwright não encontrada em $playwrightDir/.playwright/node"
    exit 1
}

Write-Host "Usando CLI do Playwright: $($playwrightCmd.FullName)"
& $playwrightCmd.FullName @Arguments

Uso:

# Instalar navegadores
./build/playwright.ps1 install --with-deps

# Instalar navegador específico
./build/playwright.ps1 install chromium

# Mostrar navegadores instalados
./build/playwright.ps1 install --dry-run

Pré-requisitos

Este padrão assume:

  1. Gerenciamento Central de Pacotes (CPM) com Directory.Packages.props:

    <Project>
      <ItemGroup>
        <PackageVersion Include="Microsoft.Playwright" Version="1.40.0" />
      </ItemGroup>
    </Project>
    
  2. Projeto foi compilado antes de executar playwright.ps1 (para que as DLLs existam)

  3. PowerShell disponível nos agentes de CI (pré-instalado no GitHub Actions e Azure DevOps)

Por Que Chaves de Cache Baseadas na Versão São Importantes

Usar a versão do Playwright na chave de cache garante:

  • Invalidação automática quando você atualiza o Playwright
  • Sem binários de navegador desatualizados que não correspondem à versão do SDK
  • Sem necessidade de limpeza manual de cache após mudanças de versão

Se você codificar a chave de cache (ex.: playwright-browsers-v1), precisará incrementá-la manualmente a cada atualização do Playwright, ou receberá erros crípticos de incompatibilidade de versão.

Solução de Problemas

Cache não sendo usado

  1. Verifique se a etapa de extração da versão gera a versão correta
  2. Confirme que o caminho do cache corresponde ao seu SO
  3. Garanta que Directory.Packages.props existe e contém o pacote Playwright

"Navegador não encontrado" após acerto no cache

Os navegadores em cache não correspondem à versão do SDK Playwright. Isso acontece quando:

  • A chave de cache não inclui a versão
  • A extração da versão falhou silenciosamente

Correção: Garanta que a versão do Playwright esteja na chave de cache.

playwright.ps1 não consegue encontrar a DLL

Execute dotnet build ou dotnet restore antes de executar o script. A DLL do Playwright só existe após a restauração do NuGet.

Referências

Este padrão é testado em projetos de produção:

Skills Relacionadas

  • dotnet-skills:playwright-blazor - Escrevendo testes Playwright para aplicações Blazor
  • dotnet-skills:project-structure - Configuração de Gerenciamento Central de Pacotes

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.

Habilidades Relacionadas