Run Playwright Python Tests in GitHub Actions (CI Workflow)

Tests that only run on a laptop protect nobody. In continuous integration (CI), every push and pull request runs the suite on a clean machine, and a red result blocks the change before it reaches users. GitHub Actions is free for public repositories and built into GitHub. In this lesson you will write a complete workflow for a Playwright Python project: install Python, dependencies and browsers, run pytest with failure artifacts, use secrets, cache downloads, run a browser matrix, publish a results table in the job summary, run nightly and on demand, and cancel outdated runs.

Advertisement

📖 What You’ll Learn: where workflows live and how they are triggered, a minimal Playwright Python workflow step by step, actions/checkout, setup-python with pip caching, playwright install –with-deps, running pytest with screenshots, traces and JUnit, uploading artifacts on failure, secrets and environment variables, a browser matrix with fail-fast off, caching browsers, a job summary from JUnit XML, schedule and workflow_dispatch triggers with inputs, concurrency, and running in the Playwright container.


🔁 How GitHub Actions Works

A workflow is a YAML file in .github/workflows/ in your repository. It says when to run (on: push, pull request, schedule …) and what to run (jobs:, each a list of steps: on a fresh virtual machine called a runner).

your-repo/
├── .github/workflows/playwright.yml    the workflow
├── requirements.txt
├── pytest.ini
└── tests/

When you push the file, GitHub runs it and shows the result next to each commit and pull request (Actions tab).


🧪 The Project

A tiny but realistic project: pinned requirements and a few tests against the SQA Shop.

📄 requirements.txt

playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
python-dotenv==1.2.4

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
markers =
    smoke: quick checks for every push

📄 tests/test_shop.py

import os

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.smoke
def test_home(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("product-card").first).to_be_visible()


@pytest.mark.smoke
def test_login(page: Page):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill(os.getenv("SHOP_USER", "testuser"))
    page.get_by_test_id("login-password").fill(os.getenv("SHOP_PASSWORD", "Test@123"))
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")


def test_coupon(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.goto(SHOP + "#/cart")
    page.get_by_test_id("coupon-input").fill("FLAT200")
    page.get_by_test_id("apply-coupon").click()
    expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹200")

📝 Step 1: A Minimal Workflow

📄 .github/workflows/playwright.yml

name: Playwright tests

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v7

      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip                     # caches pip downloads, keyed on requirements.txt

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Install Playwright browsers
        run: playwright install --with-deps chromium

      - name: Run tests
        env:
          SHOP_USER: ${{ secrets.SHOP_USER }}
          SHOP_PASSWORD: ${{ secrets.SHOP_PASSWORD }}
        run: >
          pytest
          --tracing retain-on-failure
          --screenshot only-on-failure
          --video retain-on-failure
          --junitxml=reports/junit.xml

      - name: Upload failure artifacts
        if: failure()
        uses: actions/upload-artifact@v7
        with:
          name: playwright-results
          path: test-results/
          retention-days: 7

Line by line:

Step Why
actions/checkout@v7 Copies your repository onto the runner
actions/setup-python@v7 with cache: pip Installs Python and reuses downloaded packages between runs
pip install -r requirements.txt Pinned versions: CI uses exactly what you tested locally
playwright install --with-deps chromium Downloads the browser and the Linux system libraries it needs
env: with secrets.* Credentials come from encrypted repository secrets, never from the code (Lesson 47)
--tracing/--screenshot/--video ... Failure evidence in test-results/ (Lessons 39, 62)
if: failure() + upload-artifact Keeps the evidence only when something failed; download it from the run page
timeout-minutes: 30 A hung run cannot block the queue for six hours (the default limit)

Add the secrets under Settings → Secrets and variables → Actions → New repository secret (SHOP_USER, SHOP_PASSWORD). Secrets are masked in logs and not available to pull requests from forks.

Check the workflow file before pushing

A YAML indentation mistake is the most common reason a workflow never starts. A two-line check catches it:

📄 check_workflow.py

import yaml

wf = yaml.safe_load(open(".github/workflows/playwright.yml", encoding="utf-8"))
steps = wf["jobs"]["test"]["steps"]
print("jobs:", list(wf["jobs"]), "| steps:", len(steps))
print([s.get("uses") or s.get("name") for s in steps])

⌨️ Terminal

python check_workflow.py

🖥️ Output

jobs: ['test'] | steps: 6
['actions/checkout@v7', 'actions/setup-python@v7', 'Install dependencies', 'Install Playwright browsers', 'Run tests', 'actions/upload-artifact@v7']

Run the same command locally

CI should run what you run. GitHub sets the environment variable CI=true; the test command is the same:

⌨️ Terminal

$env:CI = "true"; pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure --junitxml=reports/junit.xml

🖥️ Output

...                                                                      [100%]
3 passed in 9.00s

🎛️ Step 2: A Browser Matrix

A matrix runs the same job several times with different values, in parallel, on separate runners:

📄 .github/workflows/cross-browser.yml

name: Cross-browser

on:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    strategy:
      fail-fast: false                    # let every browser finish, even if one fails
      matrix:
        browser: [chromium, firefox, webkit]
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt
      - run: playwright install --with-deps ${{ matrix.browser }}
      - run: pytest --browser ${{ matrix.browser }} --junitxml=reports/junit-${{ matrix.browser }}.xml
      - uses: actions/upload-artifact@v7
        if: always()
        with:
          name: junit-${{ matrix.browser }}
          path: reports/
  • fail-fast: false matters: by default GitHub cancels the other browsers as soon as one fails, so you would not know whether the bug is browser-specific.
  • Each matrix job installs only its own browser, which keeps it fast.
  • Artifact names must be unique per job, hence junit-${{ matrix.browser }}.

Advertisement

⚡ Step 3: Cache the Browsers

playwright install downloads around 150 to 300 MB per browser. Cache the download folder, keyed on the Playwright version from requirements.txt:

      - name: Get Playwright version
        id: pw
        run: echo "version=$(pip show playwright | grep Version | cut -d' ' -f2)" >> "$GITHUB_OUTPUT"

      - name: Cache browsers
        id: browsers
        uses: actions/cache@v6
        with:
          path: ~/.cache/ms-playwright
          key: playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}

      - name: Install browsers
        if: steps.browsers.outputs.cache-hit != 'true'
        run: playwright install --with-deps chromium

      - name: Install system dependencies only
        if: steps.browsers.outputs.cache-hit == 'true'
        run: playwright install-deps chromium

The cache restores the browsers, but the system libraries are not part of it, so playwright install-deps still runs on a cache hit. When you bump Playwright, the key changes and new browsers are downloaded automatically.


📋 Step 4: Results in the Job Summary

GitHub shows Markdown written to the file named in $GITHUB_STEP_SUMMARY on the run’s summary page. A short script turns the JUnit XML into a table:

📄 ci/junit_summary.py

"""Write a Markdown summary of a JUnit XML file to $GITHUB_STEP_SUMMARY (or print it)."""
import os
import sys
import xml.etree.ElementTree as ET

path = sys.argv[1] if len(sys.argv) > 1 else "reports/junit.xml"
cases = list(ET.parse(path).getroot().iter("testcase"))


def outcome(case):
    if case.find("failure") is not None or case.find("error") is not None:
        return "❌ failed"
    if case.find("skipped") is not None:
        return "⏭️ skipped"
    return "✅ passed"


lines = ["## Playwright results", "", "| Test | Result | Time (s) |", "|---|---|---|"]
lines += [f"| {c.get('name')} | {outcome(c)} | {float(c.get('time', 0)):.1f} |" for c in cases]
passed = sum(outcome(c) == "✅ passed" for c in cases)
lines += ["", f"**{passed} of {len(cases)} passed**"]

summary = os.getenv("GITHUB_STEP_SUMMARY")
if summary:
    with open(summary, "a", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")
else:
    print("\n".join(lines))

⌨️ Terminal

python ci/junit_summary.py reports/junit.xml

🖥️ Output

## Playwright results

| Test | Result | Time (s) |
|---|---|---|
| test_home[chromium] | ✅ passed | 4.3 |
| test_login[chromium] | ✅ passed | 2.5 |
| test_coupon[chromium] | ✅ passed | 2.1 |

**3 of 3 passed**

In the workflow, run it even when tests fail:

      - name: Job summary
        if: always()
        run: python ci/junit_summary.py reports/junit.xml

⏰ Step 5: Nightly Runs and Manual Runs

Two more triggers cover most needs: a schedule for the full regression and workflow_dispatch for a “Run workflow” button with inputs:

📄 .github/workflows/nightly.yml

name: Nightly regression

on:
  schedule:
    - cron: "30 20 * * *"            # 20:30 UTC = 02:00 IST, every day
  workflow_dispatch:
    inputs:
      marker:
        description: "pytest -m expression"
        default: "not slow"
      browser:
        type: choice
        options: [chromium, firefox, webkit]
        default: chromium

concurrency:
  group: nightly-${{ github.ref }}
  cancel-in-progress: true

jobs:
  regression:
    runs-on: ubuntu-latest
    timeout-minutes: 60
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt pytest-xdist
      - run: playwright install --with-deps ${{ inputs.browser || 'chromium' }}
      - name: Run
        run: >
          pytest -n auto
          -m "${{ inputs.marker || 'not slow' }}"
          --browser ${{ inputs.browser || 'chromium' }}
          --tracing retain-on-failure --junitxml=reports/junit.xml
      - if: always()
        run: python ci/junit_summary.py reports/junit.xml
      - if: failure()
        uses: actions/upload-artifact@v7
        with:
          name: nightly-results
          path: test-results/
  • Cron times are in UTC. 30 20 * * * is 02:00 in India (UTC+5:30).
  • On scheduled runs the inputs are empty, so ${{ inputs.marker || 'not slow' }} falls back to a default.
  • concurrency with cancel-in-progress stops an older run when a newer one starts for the same branch, saving runner minutes.
  • pytest -n auto (Lesson 65) uses the runner’s CPU cores (GitHub’s standard Linux runners have 4).

📄 check_all.py

import pathlib

import yaml

for path in sorted(pathlib.Path(".github/workflows").glob("*.yml")):
    wf = yaml.safe_load(path.read_text(encoding="utf-8"))
    triggers = wf[True] if True in wf else wf["on"]      # YAML 1.1 reads the key `on` as boolean True
    print(f"{path.name:20} triggers={list(triggers)} jobs={list(wf['jobs'])}")

⌨️ Terminal

python check_all.py

🖥️ Output

cross-browser.yml    triggers=['pull_request'] jobs=['test']
nightly.yml          triggers=['schedule', 'workflow_dispatch'] jobs=['regression']
playwright.yml       triggers=['push', 'pull_request'] jobs=['test']

The wf[True] line is a classic YAML surprise: PyYAML follows YAML 1.1, where the bare word on means boolean true. GitHub reads it correctly; only your own scripts need to know.


🐳 Alternative: Run Inside the Playwright Container

Instead of installing browsers and system libraries, run the job inside Microsoft’s official image, which already contains them (Lesson 68):

jobs:
  test:
    runs-on: ubuntu-latest
    container:
      image: mcr.microsoft.com/playwright/python:v1.65.2-noble
      options: --user 1001
    steps:
      - uses: actions/checkout@v7
      - run: pip install -r requirements.txt
      - run: pytest

Keep the image tag equal to your playwright version in requirements.txt; a mismatch makes Playwright look for browsers that are not in the image.


Advertisement

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Change the minimal workflow so it runs only the smoke tests on pull requests but the full suite on pushes to main.

Show answer
      - name: Run tests
        run: |
          if [ "${{ github.event_name }}" = "pull_request" ]; then
            pytest -m smoke
          else
            pytest
          fi

Alternatively use two jobs with if: github.event_name == 'pull_request' and if: github.event_name == 'push'.

Exercise 2: Your matrix run fails only on WebKit, but you only see “cancelled” for Firefox. What setting is missing and what does it do?

Show answer

strategy.fail-fast: false. Without it, GitHub cancels the remaining matrix jobs as soon as one fails, so you cannot tell whether the failure is WebKit-specific.

Exercise 3: Write a step that uploads both reports/ and test-results/ as one artifact named results-<run number>, always, kept for 14 days.

Show answer
      - uses: actions/upload-artifact@v7
        if: always()
        with:
          name: results-${{ github.run_number }}
          path: |
            reports/
            test-results/
          retention-days: 14

Exercise 4: A teammate printed ${{ secrets.SHOP_PASSWORD }} in a step to debug and the log shows ***. Is the secret safe, and what should the team do?

Show answer

GitHub masks the exact secret value in logs, so it appears as ***, but masking is a safety net, not a guarantee (transformed values, such as base64 or partial strings, are not masked). Remove the debug print, never echo secrets, and rotate the password if there is any doubt that it leaked.


🧠 MCQ Quiz: Playwright Python in GitHub Actions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Where must GitHub Actions workflow files be stored?
  2. What does playwright install --with-deps chromium do on a Linux runner?
  3. How should CI tests receive passwords?
  4. What does if: failure() on the upload step do?
  5. Why set fail-fast: false in a browser matrix?
  6. When the browser cache hits, what must still run?
  7. In which time zone are GitHub Actions cron schedules?
  8. What does concurrency with cancel-in-progress: true do?
  9. What does $GITHUB_STEP_SUMMARY point to?
  10. Why must the Playwright container image tag match the playwright version in requirements.txt?

Want a longer, timed test? Take the Module 12 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 How much does GitHub Actions cost?

It is free for public repositories. Private repositories get a monthly quota of free minutes depending on the plan; Linux runners are the cheapest. Caching and concurrency keep usage down.

🤔 Can I run the tests on Windows or macOS runners?

Yes: runs-on: windows-latest or macos-latest. Use them when you need the real Edge (--browser-channel msedge) or Safari-specific checks; Linux is faster and cheaper for everything else.

🤔 How do I block merging when tests fail?

Make the workflow a required status check in the branch protection rules (Settings → Branches). Pull requests then cannot be merged until the check is green.

🤔 Where do I see screenshots and traces from a failed run?

On the workflow run page, under Artifacts. Download the zip, extract it and open the trace with playwright show-trace (Lesson 62).

🤔 Can I publish the Allure or pytest-html report?

Yes: upload it as an artifact, or deploy it to GitHub Pages with the official Pages actions. Lesson 64 shows how to generate the Allure report.


Advertisement

🏁 Summary

  • A workflow in .github/workflows/ checks out the code, sets up Python with pip caching, installs pinned dependencies and browsers (--with-deps), and runs pytest.
  • Pass credentials through repository secrets, keep failure artifacts with if: failure(), and add timeout-minutes.
  • Use a browser matrix with fail-fast: false, cache ~/.cache/ms-playwright keyed on the Playwright version, and still run install-deps.
  • Publish a results table to $GITHUB_STEP_SUMMARY, schedule nightly runs in UTC, add workflow_dispatch inputs and concurrency.
  • Or run inside mcr.microsoft.com/playwright/python with a tag that matches your Playwright version.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page