QA and Test Automation · Lab 23 of 35

Run API and UI Test Suites in GitHub Actions: Hands-On Lab

Put ShopRung, the pytest API suite and the Playwright UI suite in one repository, then build a GitHub Actions workflow step by step: start the shop and wait for it, run both suites, a browser matrix, run summaries, artifacts, secrets, a practice-bug switch and required checks.

⏱ 90 minIntermediate💸 Free6 steps

GitHub ActionsactionlintShopRung (Node.js 22)pytest API suite (lab 11)Playwright suite (lab 13)

Overview video

1 / 6

0 of 6 steps done

What you will build

A GitHub repository whose tests run on every pull request, every push to main, every night and on demand:

  • .github/workflows/tests.yml: an api job that starts ShopRung inside the job, waits for its health check and runs the 23 pytest API tests; a ui job that runs only if the API passed, with a browser matrix (Chromium and Firefox) for the 7 Playwright tests.
  • A run summary table on every run, artifacts (JUnit results, ShopRung's log, the Playwright report and traces), a password from repository secrets, and a Run workflow button that can switch on a ShopRung practice bug.
  • Branch protection that blocks merging when a check is red.

Before you start

Setup

S1Collect the three projects in one folder

Make a folder shoprung-qa with three subfolders: shoprung (unzip ShopRung into it), api-tests (unzip the Python project from the pytest API lab) and e2e (unzip the Playwright project from lab 13). In e2e, run npm install once so a package-lock.json exists: CI needs it for npm ci and for caching.

Run
cd shoprung-qa
ls
cd e2e && npm install && cd ..
You should see
api-tests  e2e  shoprung

S2Install actionlint (optional, recommended)

actionlint checks workflow files for mistakes before you push, so you do not wait for GitHub to tell you about a typo.

Run
brew install actionlint
1

One repository on GitHub

The app, both suites and a .gitignore, pushed to a new repository.

Create .gitignore in shoprung-qa. It keeps dependencies, virtual environments, test output and ShopRung's local database out of Git: CI will produce those fresh on every run.

Then create an empty repository on GitHub called shoprung-qa (Public or Private both work; GitHub Actions minutes are free for public repositories and include a monthly allowance for private ones) and push your folder to it. Everything in this lab happens in that repository.

.gitignore
# dependencies and virtual environments
node_modules/
.venv/
__pycache__/
# test output: CI keeps it as artifacts instead
api-tests/results/
e2e/results/
e2e/test-results/
e2e/playwright-report/
e2e/playwright/.auth/
# ShopRung's local database and log
shoprung/data/
shoprung/shoprung.log
  1. The saved login state from lab 13: never commit session cookies.line 10
  2. ShopRung creates its database here; every CI run starts from fresh seed data instead.line 12
Run
git init -b main
git add .
git commit -m "ShopRung with API and UI suites"
git remote add origin https://github.com/<you>/shoprung-qa.git
git push -u origin main
You should seeyour text will differ: the model writes it
To https://github.com/<you>/shoprung-qa.git
 * [new branch]      main -> main
2

The first workflow: start the shop, run the API suite

A job that starts ShopRung inside GitHub's machine and runs 23 API tests against it.

Create .github/workflows/tests.yml. on lists the triggers: every pull request and every push to main. The api job runs on a fresh Ubuntu machine with a 15 minute timeout. Its steps check out the code, install Node 22, start ShopRung in the background with its output saved to a log, wait until it answers, install Python with a pip cache, and run pytest with a JUnit XML report.

Note http-get:// in the wait-on line. With a plain http:// URL, wait-on checks with a HEAD request, ShopRung answers HEAD with 405 Method Not Allowed, and the step times out after a minute although the shop is running. We hit exactly that while building this lab; http-get:// makes wait-on send a GET.

Check the file with actionlint, then commit and push. Open the Actions tab of your repository and click the run.

.github/workflows/tests.yml
name: tests

on:
  pull_request:
  push:
    branches: [main]

jobs:
  api:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Start ShopRung
        working-directory: shoprung
        run: |
          npm start > shoprung.log 2>&1 &
          npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip

      - name: API tests
        working-directory: api-tests
        run: |
          pip install -r requirements.txt
          pytest --junitxml=results/api.xml
  1. A hung test can never burn hours of CI time.line 11
  2. & runs ShopRung in the background, so the next line runs while it starts.line 22
  3. Poll the health check with GET until it answers, up to 60 seconds. Never sleep 10.line 23
  4. Keeps downloaded packages between runs: faster pull requests.line 28
  5. A failing test makes pytest exit with an error, so the step, the job and the check go red.line 34
Run
actionlint
git add .github && git commit -m "CI: API suite" && git push
You should seeyour text will differ: the model writes it
Actions tab → tests → api ✓
  Start ShopRung ✓
  API tests ✓   ... 23 passed in 2.19s
Stuck on this step?
"Error: Timed out waiting for: http://localhost:8080/api/health"
Use http-get://localhost:8080/api/health. ShopRung does not support HEAD, which is what wait-on sends for http://.
npm start fails with "Missing script: start".
The step runs in working-directory: shoprung. Check the folder name and that shoprung/package.json is committed.
3

Evidence: a run summary and artifacts

A results table on the run page, and files you can download, even when tests fail.

Create .github/summary.py. It reads a JUnit XML file and prints a small Markdown table plus one line per failed test. Anything a step appends to the file named in $GITHUB_STEP_SUMMARY appears on the run's summary page.

Add two steps to the api job. Both have if: always(): a failed test step would otherwise skip everything after it, which is exactly when you need the evidence. upload-artifact stores the JUnit file and ShopRung's own log with the run.

.github/workflows/tests.yml 10 new or changed lines
name: tests

on:
  pull_request:
  push:
    branches: [main]

jobs:
  api:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Start ShopRung
        working-directory: shoprung
        run: |
          npm start > shoprung.log 2>&1 &
          npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip

      - name: API tests
        working-directory: api-tests
        run: |
          pip install -r requirements.txt
          pytest --junitxml=results/api.xml

      - name: Summary
        if: always()
        run: python3 .github/summary.py api-tests/results/api.xml >> "$GITHUB_STEP_SUMMARY"

      - name: Keep results and the shop's log
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: api-results
          path: |
            api-tests/results/
            shoprung/shoprung.log
  1. Markdown appended here shows on the run page.line 38
  2. Downloadable from the run page for 90 days by default.line 42
  3. The server's side of every failure: often faster to read than the test output.line 47
.github/summary.py
"""Turn a JUnit XML file into a short Markdown table for the GitHub Actions run summary."""
import sys
import xml.etree.ElementTree as ET

path = sys.argv[1]
try:
    root = ET.parse(path).getroot()
except (OSError, ET.ParseError):
    print(f"No test results at `{path}`: the tests did not run.")
    sys.exit(0)

suites = [root] if root.tag == "testsuite" else list(root.iter("testsuite"))
total = sum(int(s.get("tests", 0)) for s in suites)
failed = sum(int(s.get("failures", 0)) + int(s.get("errors", 0)) for s in suites)
skipped = sum(int(s.get("skipped", 0)) for s in suites)

print(f"### {path}\n")
print("| Tests | Passed | Failed | Skipped |\n| --- | --- | --- | --- |")
print(f"| {total} | {total - failed - skipped} | {failed} | {skipped} |\n")
for case in root.iter("testcase"):
    problem = case.find("failure")
    if problem is None:
        problem = case.find("error")
    if problem is not None:
        message = (problem.get("message") or "").splitlines()[0][:150] if problem.get("message") else ""
        print(f"- ❌ `{case.get('classname')}.{case.get('name')}`: {message}")
  1. If the tests never ran, say so instead of crashing the summary step.line 8
  2. One line per failed test, with the first line of its message.line 26
Run
actionlint
git add .github && git commit -m "CI: summary and artifacts" && git push
You should seeyour text will differ: the model writes it
api-tests/results/api.xml
| Tests | Passed | Failed | Skipped |
| --- | --- | --- | --- |
| 23 | 23 | 0 | 0 |

Artifacts: api-results
4

The UI job: a browser matrix

Playwright in Chromium and Firefox, only after the API suite passed.

First two small changes in e2e. In playwright.config.ts, add a firefox project (with the same login setup as a dependency) and a junit reporter for the summary. In tests/auth.setup.ts, read the password from ALICE_PASSWORD when it is set, so CI can pass it as a secret (next step).

Then add the ui job. needs: api makes it wait for the API job and skip when that failed, which saves the slow browser minutes when the basics are broken. The matrix runs the job once per browser in parallel; fail-fast: false lets Firefox finish even when Chromium fails. Each copy installs only its browser, runs only that project, and uploads the HTML report and traces only on failure.

.github/workflows/tests.yml 25 new or changed lines
name: tests

on:
  pull_request:
  push:
    branches: [main]

jobs:
  api:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Start ShopRung
        working-directory: shoprung
        run: |
          npm start > shoprung.log 2>&1 &
          npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip

      - name: API tests
        working-directory: api-tests
        run: |
          pip install -r requirements.txt
          pytest --junitxml=results/api.xml

      - name: Summary
        if: always()
        run: python3 .github/summary.py api-tests/results/api.xml >> "$GITHUB_STEP_SUMMARY"

      - name: Keep results and the shop's log
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: api-results
          path: |
            api-tests/results/
            shoprung/shoprung.log

  ui:
    needs: api
    runs-on: ubuntu-latest
    timeout-minutes: 20
    strategy:
      fail-fast: false
      matrix:
        browser: [chromium, firefox]
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
          cache-dependency-path: e2e/package-lock.json

      - name: Start ShopRung
        working-directory: shoprung
        run: |
          npm start > shoprung.log 2>&1 &
          npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000

      - name: Install Playwright and the browser
        working-directory: e2e
        run: |
          npm ci
          npx playwright install --with-deps ${{ matrix.browser }}

      - name: UI tests
        working-directory: e2e
        run: npx playwright test --project=${{ matrix.browser }}
        env:
          ALICE_PASSWORD: ${{ secrets.ALICE_PASSWORD }}

      - name: Summary
        if: always()
        run: python3 .github/summary.py e2e/results/ui.xml >> "$GITHUB_STEP_SUMMARY"

      - name: Keep the report and traces
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-report-${{ matrix.browser }}
          path: |
            e2e/playwright-report/
            e2e/test-results/
            shoprung/shoprung.log
          retention-days: 14
  1. Order the jobs: cheap API checks first, browsers only when they pass.line 50
  2. Two jobs from one definition, named "ui (chromium)" and "ui (firefox)".line 56
  3. Cache npm downloads, keyed on the lock file you created in setup.line 64
  4. The browser plus the Linux libraries it needs.line 76
  5. Traces are large: keep them only when something failed, for 14 days.line 89
e2e/playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  fullyParallel: false, // the tests share one ShopRung and reset it, so run one at a time
  workers: 1,
  retries: process.env.CI ? 2 : 0,
  reporter: [['list'], ['html', { open: 'never' }], ['junit', { outputFile: 'results/ui.xml' }]],
  use: {
    baseURL: process.env.BASE_URL ?? 'http://localhost:8080',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/alice.json' },
      dependencies: ['setup'],
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'], storageState: 'playwright/.auth/alice.json' },
      dependencies: ['setup'],
    },
  ],
});
  1. The same summary script reads this file.line 8
  2. Same tests, same login state, another engine.line 22
  3. From lab 13: GitHub sets CI=true, so failures are retried twice and the first retry keeps a trace.line 7
e2e/tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

// Logs Alice in once through the real login page and saves the browser state for every other test.
setup('log in as alice', async ({ page }) => {
  await page.goto('/#/login');
  await page.getByLabel('Email').fill('alice@shoprung.test');
  // in CI the password comes from a repository secret; locally the practice password is used
  await page.getByLabel('Password').fill(process.env.ALICE_PASSWORD || 'Alice123!');
  await page.getByRole('button', { name: 'Log in' }).click();
  await expect(page.getByTestId('user-name')).toHaveText('Hi, Alice Shah');
  await page.context().storageState({ path: 'playwright/.auth/alice.json' });
});
  1. ||, not ??: an unset GitHub secret arrives as an empty string.line 8
Run
actionlint
git add . && git commit -m "CI: UI matrix" && git push
You should seeyour text will differ: the model writes it
api ✓ → ui (chromium) ✓   ui (firefox) ✓

e2e/results/ui.xml
| Tests | Passed | Failed | Skipped |
| 7 | 7 | 0 | 0 |
5

Secrets, a nightly run and a Run workflow button

Credentials from settings, scheduled and manual runs, and safe permissions.

In GitHub, open Settings → Secrets and variables → Actions → New repository secret, name it ALICE_PASSWORD and enter Alice123!. The ui job already maps it into an environment variable; GitHub masks its value in logs. ShopRung's practice passwords are public, but this is how real credentials must always travel.

Finish the workflow. schedule adds a nightly run (cron in UTC). workflow_dispatch adds a Run workflow button with an input, bugs, that switches on ShopRung practice bugs before the tests. The input reaches the script through an env variable and jq, never pasted straight into the command: text people type into a workflow must not become shell code. permissions gives the workflow read-only access, and concurrency cancels an older run of the same branch when you push again.

.github/workflows/tests.yml 23 new or changed lines
name: tests

on:
  pull_request:
  push:
    branches: [main]
  schedule:
    - cron: "17 2 * * *"   # nightly, 02:17 UTC
  workflow_dispatch:        # a "Run workflow" button in the Actions tab
    inputs:
      bugs:
        description: "Practice only: ShopRung bugs to switch on, comma separated"
        required: false
        default: ""

permissions:
  contents: read

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

jobs:
  api:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Start ShopRung
        working-directory: shoprung
        run: |
          npm start > shoprung.log 2>&1 &
          npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000

      - name: Switch on practice bugs
        if: inputs.bugs != ''
        env:
          BUGS: ${{ inputs.bugs }}
        run: |
          jq -n --arg b "$BUGS" '{enabled: ($b | split(","))}' |
            curl -sf -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d @-

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip

      - name: API tests
        working-directory: api-tests
        run: |
          pip install -r requirements.txt
          pytest --junitxml=results/api.xml

      - name: Summary
        if: always()
        run: python3 .github/summary.py api-tests/results/api.xml >> "$GITHUB_STEP_SUMMARY"

      - name: Keep results and the shop's log
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: api-results
          path: |
            api-tests/results/
            shoprung/shoprung.log

  ui:
    needs: api
    runs-on: ubuntu-latest
    timeout-minutes: 20
    strategy:
      fail-fast: false
      matrix:
        browser: [chromium, firefox]
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
          cache-dependency-path: e2e/package-lock.json

      - name: Start ShopRung
        working-directory: shoprung
        run: |
          npm start > shoprung.log 2>&1 &
          npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000

      - name: Switch on practice bugs
        if: inputs.bugs != ''
        env:
          BUGS: ${{ inputs.bugs }}
        run: |
          jq -n --arg b "$BUGS" '{enabled: ($b | split(","))}' |
            curl -sf -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d @-

      - name: Install Playwright and the browser
        working-directory: e2e
        run: |
          npm ci
          npx playwright install --with-deps ${{ matrix.browser }}

      - name: UI tests
        working-directory: e2e
        run: npx playwright test --project=${{ matrix.browser }}
        env:
          ALICE_PASSWORD: ${{ secrets.ALICE_PASSWORD }}

      - name: Summary
        if: always()
        run: python3 .github/summary.py e2e/results/ui.xml >> "$GITHUB_STEP_SUMMARY"

      - name: Keep the report and traces
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-report-${{ matrix.browser }}
          path: |
            e2e/playwright-report/
            e2e/test-results/
            shoprung/shoprung.log
          retention-days: 14
  1. 02:17 UTC every day. Avoid minute 0, when GitHub is busiest.line 8
  2. Adds the Run workflow button, with the input below.line 9
  3. The tests only read the code; least privilege for the token.line 17
  4. Push twice to a pull request and only the newest run continues.line 21
  5. Through an environment variable, so the input is data, not part of the script.line 43
  6. Builds {"enabled":["coupon-boundary"]} safely from "coupon-boundary".line 45
Run
actionlint
git add .github && git commit -m "CI: secrets, schedule, manual runs" && git push
You should seeyour text will differ: the model writes it
(no output from actionlint)
Actions tab → tests → "Run workflow" button appears on the right
6

Make the checks required

A red check blocks the merge button.

A workflow only reports. To stop broken changes, open Settings → Branches → Add branch ruleset (or a classic branch protection rule) for main: require a pull request before merging, and require status checks to pass with api, ui (chromium) and ui (firefox) selected. Checks appear in the list after they have run once.

Try it: create a branch, change api-tests/tests/test_cart.py so a test expects $49.98 instead of $49.99, push, and open a pull request. The api check goes red, the ui jobs are skipped, and the Merge button is blocked. Close the pull request without merging.

Run
git switch -c break-a-test
# edit the expected total in test_cart.py, then:
git commit -am "Expect the wrong total" && git push -u origin break-a-test
You should seeyour text will differ: the model writes it
Pull request checks:
  ✘ tests / api
  ⊘ tests / ui (chromium)  skipped
  ⊘ tests / ui (firefox)   skipped
Merging is blocked: required status checks have not succeeded

Check it works

Open Actions → tests → Run workflow, type coupon-boundary in the bugs field and run it. The api job fails with exactly one failed test, test_save10_applies_at_exactly_50_dollars, and the run summary names it with assert 400 == 200. Download api-results: shoprung.log shows the coupon request answered with 400.

The ui jobs are skipped, because needs: api stops them. That is the design working: no browser minutes spent on a build whose API is broken. Run the workflow again with the bugs field empty: everything is green.

Test
Actions → tests → Run workflow → bugs: coupon-boundary
You should see
api ✘   ui (chromium) skipped   ui (firefox) skipped

FAILED tests/test_cart.py::test_save10_applies_at_exactly_50_dollars - assert 400 == 200
1 failed, 22 passed

Summary:
| Tests | Passed | Failed | Skipped |
| 23 | 22 | 1 | 0 |
- ❌ `tests.test_cart.test_save10_applies_at_exactly_50_dollars`: assert 400 == 200

Troubleshooting

The Start ShopRung step times out although ShopRung started.

Use http-get:// in the wait-on URL; with http:// it sends HEAD, which ShopRung answers with 405.

npm ci fails: "The npm ci command can only install with an existing package-lock.json".

Run npm install in e2e locally and commit e2e/package-lock.json.

The workflow does not appear in the Actions tab.

The file must be in .github/workflows/ on the default branch, with a .yml or .yaml extension. Run actionlint for syntax errors.

The Run workflow button is missing.

workflow_dispatch must be in the workflow on the default branch (main), not only on a feature branch.

UI tests fail at login in CI only.

Check the ALICE_PASSWORD secret's name and value; with || in auth.setup.ts, a missing secret falls back to the practice password.

Required checks never appear in the ruleset list.

GitHub lists only checks that have run on the repository recently. Run the workflow once, then add them.

What changes in production

  • Teams keep fast API and contract jobs on every pull request and move slow browser matrices or full regression to needs-ordered jobs or nightly schedules.
  • Workflows start the app inside the job or a service container for isolation, and wait on a health check, never a fixed sleep.
  • Artifacts and run summaries are how people read failures; many teams also publish an HTML or Allure report per branch.
  • Secrets live in repository or environment settings, workflow tokens get least privilege, and user input never goes straight into shell commands.
  • Branch protection or rulesets make the checks required; flaky tests are quarantined so required checks stay trusted.

Interview angle

“How would you run your test suites in GitHub Actions?”

One workflow triggered on pull requests, pushes to main, a nightly schedule and manual dispatch. The API job checks out the code, sets up Node and Python with caching, starts the application in the background and waits on its health endpoint with a GET, then runs pytest with a JUnit report. A UI job needs the API job and runs a browser matrix with fail-fast off. Every job writes a run summary and uploads results and the app log with if: always(), traces on failure. Credentials come from secrets, permissions are read-only, inputs reach scripts through environment variables, and branch rules make the checks required.

Clean up

Practice

These run in your browser and check your answer.

Expand a matrix

GitHub runs one job per combination of matrix values. Write expand(matrix) that takes a dict like {"browser": ["chromium", "firefox"], "os": ["ubuntu", "windows"]} and returns a list of dicts, one per combination, in order.

Exercise
def expand(matrix):
    key = list(matrix)[0]
    return [{key: value} for value in matrix[key]]
Hint

`itertools.product(*matrix.values())` gives every combination; zip each one with the keys.

The full project

Every file from this lab, as it is after the last step.

Download GitHub Actions project (.zip)