Back to Explore
GuideVibeFix editorialUpdated Nov 24, 2026

GitHub Actions in Practice: Run Your Tests Automatically on Every Push

AI writes code fast, but it also breaks quietly — and you find out from a user. GitHub Actions runs your checks on a clean machine at every push. This guide takes a 6-test Python project from red to green locally (one wrong expectation: 226.0 != 226.5, FAILED with 1 failure), then writes a 1-job, 5-step workflow with checkout@v7 and setup-python@v7 on Python 3.12, and replays the CI steps locally. Python 3.12.3, PyYAML 6.0.1.

Real photo: a developer writing code on a laptop with a dark code editor on screen

You have seen how fast AI writes code: one sentence in, a working module out. But you have also seen the other side: the code runs, yet the numbers it computes are wrong, and you only find out when a user comes to you. The problem is not that AI writes slowly, it is that you have no check that runs automatically on every push. GitHub Actions is that check: you push your code, GitHub runs your checks from scratch on a clean machine, a green check if they pass, a red cross if they fail. This guide works through a tiny project called pricecalc with only 6 tests, from two local runs — red, then green — to a workflow with 1 job and 5 steps, and finally a local replay of the CI steps in order. Every number comes from actually running the demo script demo246_zh.py. The English rerun script is rerun_en_demo246_g2.py and its numbers match. The local environment is Python 3.12.3, and the workflow uses actions/checkout@v7 and actions/setup-python@v7, verified as the current versions in the official repo README on 2026-11-24.

First, where CI sits: it is not deployment and it is not monitoring, it is "every time someone pushes code, run the checks you defined, automatically". Checks can be compiling, tests, or formatting; this guide does only the two most basic ones, a compile check and unit tests. Many beginners try to stuff linting, type checking, tests, building, and deployment into their first CI setup, get buried in errors on day one, and never touch CI again. The right order is the reverse: get the simplest check green first, then add items one at a time. Green gives you the confidence to add more; red tells you which item broke.

One uncomfortable truth up front: CI can only check the checks you wrote, not the ones you did not write. Branches your tests never cover, and code that is "correct" because the requirement was misunderstood, both pass — a green check does not mean the code is right, it only means the checks you wrote all passed. So the value of CI is not the green check itself, it is that CI forces you to write down "what counts as right" as tests that run automatically: every assertion you write is a promise that gets re-verified on every push afterwards. The more honest the tests, the more the CI means; if the tests are decoration, the CI is a decorative green check.

Write a test that runs first: 6 cases, zero third-party packages

The demo project has a single pricing module, price.py, with three functions: total with tax, yuan formatting, and discounts. The tests use Python's standard library unittest, 6 cases in total, no pytest and no third-party packages. Why not pytest? The site already has a pytest testing guide, and the point of this guide is CI itself, not the test framework; and unittest ships with the standard library, so it works on a different machine or a different CI environment without installing anything — for a first workflow, one fewer dependency is one fewer point of failure.

# price.py
def total_with_tax(price, qty, rate=0.13):
    """Total price including tax, rounded to cents."""
    return round(price * qty * (1 + rate), 2)

def format_yuan(amount):
    return f"¥{amount:.2f}"

def apply_discount(amount, discount):
    if not 0 <= discount <= 1:
        raise ValueError("discount must be between 0 and 1")
    return round(amount * (1 - discount), 2)

Each of the 6 test cases checks one thing: at the default 13% tax rate, 100 yuan times 2 items comes to 226.00; at a zero rate, 100 yuan times 2 items is 200.00; 59.9 yuan times 3 items with tax is 203.06; 226 formats as ¥226.00; 200 yuan at a 10% discount is 180.00; and a discount of 1.5 must raise ValueError. The first five check "did it compute the right thing", the last one checks "did it refuse a bad input". Beginners writing tests most often test only the happy path, but the wrong path needs testing too, because real users will definitely walk it.

Break one number on purpose: see what red looks like first

Section 3 of the demo deliberately writes the first case's expectation wrong: the correct value is 226.00, it is written as 226.50, then python -m unittest -v runs. The output has 6 test result lines, 5 ok and 1 FAIL, ending with:

FAIL: test_total_default_rate (test_price.TestPrice.test_total_default_rate)
AssertionError: 226.0 != 226.5
FAILED (failures=1)

The exit code is 1. Read the three pieces together: FAIL says which case broke, AssertionError: 226.0 != 226.5 says what the computed value and the expected value each were, and exit code 1 tells the machine "this run failed". CI runs on exit codes: if any step exits with anything other than 0, the whole run goes red, without anyone having to read the log to know. The demo script's transcript deliberately drops the timing figure from the Ran 6 tests in 0.00Xs line, because those fractions of a second differ every run; only the 6 tests and the 1 failure are the same every time, and this article quotes only the numbers that do not change.

There is also a point of attitude here: everyone setting up CI for the first time should deliberately see red once. Red is not bad news — red means the check you spent half an hour building is actually working. Many people panic the first time they see red, thinking the CI is misconfigured, when in fact the CI is configured right and that is why it is red: it caught the 226.50 mistake before you pushed, instead of a user telling you about it. The earlier it goes red, the cheaper it is to fix.

Change one line to green: 226.50 becomes 226.00

Section 4 changes exactly one thing: the expectation goes from 226.50 back to 226.00, the other 5 cases untouched, and the tests run again. The output becomes 6 ok lines, ending with a lone OK and exit code 0. Only one number separates red from green, but the process itself is the whole working method of CI: change code, run checks, read red or green. From now on every code change should follow this loop — except the checks are no longer run by your hand, they are run for you by GitHub.

test_total_default_rate (test_price.TestPrice.test_total_default_rate) ... ok
test_total_zero_rate (test_price.TestPrice.test_total_zero_rate) ... ok
test_total_decimal (test_price.TestPrice.test_total_decimal) ... ok
test_format_yuan (test_price.TestPrice.test_format_yuan) ... ok
test_discount (test_price.TestPrice.test_discount) ... ok
test_discount_rejects (test_price.TestPrice.test_discount_rejects) ... ok

OK

A debugging order worth mentioning: when a test fails, suspect the test first, then the code. In the demo the wrong thing was the test's expectation — the code's 226.00 was right all along. Tests generated by AI are especially prone to this: the model writes an expectation from its own understanding, and the understanding is wrong. When you see red, do not rush to change the business code; read the failing assertion first and ask "is the expectation itself right" — it saves a lot of wasted time.

Write ci.yml: 1 job, 5 steps

With the tests green locally, it is time to write the workflow. The workflow file lives at .github/workflows/ci.yml in the repo, and section 5 of the demo validates it item by item with PyYAML 6.0.1: the workflow is named CI, the triggers are push and pull_request, there is 1 job named test, and 5 steps.

name: CI
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
permissions:
  contents: read
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - name: Show Python version
        run: python --version
      - name: Compile check
        run: python -m py_compile price.py
      - name: Run tests
        run: python -m unittest -v

The 5 steps, one by one. Step 1, actions/checkout@v7, fetches your code onto the CI machine — without it the machine is empty and nothing afterwards can run. Step 2, actions/setup-python@v7, installs Python 3.12: the official docs explicitly recommend always setting the Python version, because the machine's default version changes, and without a pinned version a check that runs today may run under a different Python tomorrow. Step 3 prints the Python version — a single line, but useful when debugging: when a test fails on CI, look at this line first to confirm the version is right, and you rule out a whole class of "works on my machine" problems. Step 4 is the compile check, which stops a syntax error here instead of waiting for the tests to fail. Step 5 runs the tests with the same command you run locally, python -m unittest -v — that is the key point: the command CI runs and the command you run locally should be the same one, so green locally usually means green on CI too.

Two details that are easy to miss. The trigger's branches: [main] means the workflow runs only for pushes to main and PRs targeting main; pushing to your own branch for fun does not trigger it, saving time and CI minutes. The top-level permissions: contents: read follows the official README's recommendation for least privilege: this workflow only needs to read code, so it is only given permission to read code, nothing more. CI permissions are generous by default, so tightening them while writing the workflow is a good habit.

YAML validation and the trap where on becomes True

Besides counting the steps, section 5 does something beginners easily skip: it parses ci.yml with PyYAML to confirm it is genuinely valid YAML. YAML looks like anyone can write it, but one wrong indent or one missing space after a colon breaks the whole file, and GitHub's error often just says "workflow invalid" without telling you which line. Parsing it locally first stops that kind of problem before pushing. The validation result: the triggers are pull_request and push, there is 1 job, 5 steps, step 1 is actions/checkout@v7, step 2 is actions/setup-python@v7 with python-version 3.12, the last step is python -m unittest -v, and the permissions are contents: read — all exactly as written.

The validation also ran into a genuine trap worth its own paragraph: YAML 1.1 parses on as the boolean value True. The demo script first tried doc["on"] to read the triggers and got KeyError: 'on' straight away, because the parsed key is not the string on at all, it is True. GitHub's own parser knows what on means and does not fall into this trap, but if you read a workflow file with Python's PyYAML for validation, you have to write it as doc.get("on", doc.get(True)). Remember this one: the next time you read ci.yml in a script and on is nowhere to be found, first check whether it turned into True.

There is another quoting issue in the same file: do not drop the quotes in python-version: "3.12". In YAML, an unquoted 3.12 parses as the decimal 3.12, not the string "3.12"; setup-python will usually cope, but the official README's examples always quote it, as '3.13'. A version is a string, not a number — the quotes speak to the parser, and to the next person who reads the file. While on the subject of file rules: workflow files must live in the .github/workflows directory, with a .yml or .yaml extension — both work, the official docs say so; and one repo can hold several workflow files, say ci.yml for checks and deploy.yml for deployment, each with its own triggers, without interfering.

Flow diagram: one push triggers the CI pipeline, 1 job with 5 steps, red run 1 failure, green run all 6 passed

The diagram above shows the workflow running: a push or a PR triggers it, the code is checked out, Python 3.12 is installed, the compile check runs, then 6 tests run, and any step with a non-zero exit code turns the whole run red. The red run has exactly one failure point, the case with the wrong expectation, 226.0 != 226.5; the green run passes all 6. The numbers in the diagram match the demo transcript exactly.

Replay the CI commands locally first

Do not push the workflow the moment it is written; section 6 does a "local CI replay": run the commands the workflow will run, in the workflow's order, on your own machine first. The compile check exits 0, the tests exit 0, and the local CI replay passes completely. Why bother? Because finding out only after pushing means waiting for CI to queue, waiting for a machine to start, waiting for the logs — several minutes round trip; running it locally takes a fraction of a second. Green locally first, then push, and the push will probably be green too — that saves your own time.

But one honest caveat: green locally does not guarantee green on GitHub. The machines are different: yours has dependencies already installed, CI's is clean; yours runs macOS or Windows, CI runs ubuntu-latest; yours has environment variables, CI's has none. A local replay catches ninety percent of problems; the remaining ten percent only show up after pushing. The real verification is always the same: push, then open the Actions page and see whether that run is a green check or a red cross. A local replay saves time; it is not a substitute for verification.

What happens after you push

After the file is pushed, open the repo's Actions page and you will see a new run named after the workflow's name, CI. Open it, watch the 5 steps tick off one by one, and the whole job turns green, with a green check appearing next to your commit. From then on, every push and every PR runs this round automatically, without you clicking anything. The PR page shows the check results too: green means reviewers can merge with confidence; red shows up next to the merge button, reminding you to fix the tests before merging.

When a run goes red, reading the log has a fixed routine: open the step that went red first, do not start from step one. CI logs are split by step, so read the red step and ignore the rest. Open the "Run tests" step and you will see output identical to the local one: 5 ok, 1 FAIL, and one line reading AssertionError: 226.0 != 226.5. The local and CI errors look the same because both sides ran the same command — that is no coincidence. Fix it the same way too: change the expectation, push, and watch another round. The rule for reading logs: look at the last few lines first, the conclusion lives there; the hundreds of lines before that are mostly install output, and you only scroll up when the last few lines do not make sense.

Once it is running, add things in this order. First, branch protection: in the repo settings, require CI to pass before a PR can merge, so red code cannot reach main and the main branch always runs. Second, run only when the code changed: add a paths filter to the triggers, so a docs-only change skips the tests and saves CI minutes. Third, cache dependencies: setup-python ships a cache: 'pip' option, and a project with a requirements.txt that turns it on skips re-downloading dependencies on every run and gets faster; this demo project has no third-party dependencies, so the option is off here — add it when you have dependencies. Fourth, a test matrix: list Python 3.12 and 3.13, and one push runs two rounds, proving the code runs on both versions. Add one item at a time, confirm it is still green, then add the next.

One more careful approach for a first workflow: do not push straight to main. Push to a trial branch first, watch one round finish red or green, and merge into main only once it is confirmed. Because the trigger says push to main, pushes to the trial branch will not trigger this workflow, so you can temporarily widen the branch condition, or add a workflow_dispatch trigger — that lets you run a round manually from the Actions page any time, without pushing code just to test the workflow. Once the workflow is stable, tighten the triggers back to pushes to main and PRs, and keep it clean.

Common traps: check these first when it goes red

First, the test file was never committed. Locally you run tests from files on your machine; the CI machine only has what you pushed, so if test_price.py never entered git, CI cannot find the tests at all and the error says the module is missing, not that a test failed. Before every push, ask yourself: did I commit the test file? Second, triggers only on main and PRs never get checked. The demo writes both push and pull_request triggers precisely so PRs get a round too; with only push, nothing checks a PR before it merges. Third, printing secrets into the log. Never print API keys or tokens in tests — CI logs are visible to anyone who can see them, and printing one once means publishing it once. Credential management is the subject of another guide; the one line here is: secrets go into Secrets only, never into code, and least of all into logs. Fourth, a stale cache: after turning on cache: 'pip', if the dependency file goes a long time without updating, the restored cache may not be used — the official docs say so explicitly, so when CI suddenly gets slower, check whether the cache missed. Fifth, tests that depend on things only your machine has: reading a file at an absolute path on your disk, connecting to a service that only runs locally, or assuming the network is reachable. The CI machine is clean and has none of those, so tests that are all green locally and all red on CI are almost always this cause. Write tests as if they must run on a fresh machine: relative paths, fake stand-ins for external services, and no network calls unless you truly need them.

Closing checklist and boundaries

Here it is as a checklist: write a test that runs locally before writing the workflow, never the reverse; start the workflow at its smallest, compile plus tests green, then build upward; run the same command locally and on CI; before pushing, replay the CI steps locally in order; after pushing, confirm the green check on the Actions page; give only the smallest permissions, and put secrets only in Secrets; when it goes red, read the failing assertion first, suspect the test before suspecting the code; write tests so they run on a clean machine, without depending on files and services that only exist locally; and changes to the workflow file itself follow the same process — validate locally first, then push and watch for the green check.

Finally, what this guide does not cover: it does not cover pytest — the site already has a pytest testing guide, and this one uses only the standard library unittest because the subject is CI itself; it does not cover Git workflows — branching strategy and commit conventions belong to another guide, while this one covers only the round of checks that runs automatically after you push; and it does not cover deployment — shipping code to a server is the next step, and it only makes sense once "every push gets checked for you" is in place. The point of CI in one sentence: let the machine check for you when you forget to check, and let mistakes be caught before they merge into the main branch instead of after a user finds them.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles