Tests and continuous integration

Introduction

How does a maintainer know that your change works, and that it did not break something else? Nobody can read every line and run every case in their head. Tests answer the question: small programs that run the code and check the results. A project with good tests can accept changes from strangers, because the tests say at once whether the change is safe.

This lesson shows how tests look, how a service called continuous integration (CI) runs them on every pull request, and how to read a red check.

How it works

A test calls the code with a known input and compares the result with the expected one. In Python, assert does the comparison, and test runners such as pytest find every function named test_... and run it:

def test_empty_list():
    assert average([]) == 0

Good tests are small, test one thing each, have a name that says what they check, and need no luck: the same code gives the same result every time. When you fix a bug, you add a regression test for the case from the report, which fails before the fix and passes after it. When you add a feature, you add tests for it.

Continuous integration runs a pipeline for every push and pull request, on a clean machine. A typical pipeline has steps: install the project, run the linter, run the tests, and build it. The steps run in order, and the first one that fails stops the pipeline, because later steps would be meaningless. The result is a green check or a red cross on the pull request. The steps are written in a file in the repository (for GitHub, a file under .github/workflows), so the pipeline is code too, and you can change it by a pull request.

When a check is red, open its log. It shows each step, and the first error is almost always the cause. Run the same command on your own computer to reproduce it, fix it, and push again.

Sometimes a test passes on one run and fails on another with the same code. That is a flaky test, usually caused by timing, random numbers, the order of things or files left behind. Flaky tests are harmful because people learn to ignore red checks, so they should be fixed or removed, not rerun until they pass. Coverage reports how many lines the tests run; it shows what is not tested at all, though a high number alone does not prove that the tests are good.

Example

def lint():
    return True


def run_tests():
    results = {"test_add": True, "test_empty": False, "test_big": True}
    for name, ok in results.items():
        print(("PASS " if ok else "FAIL ") + name)
    return all(results.values())


def build():
    return True


pipeline = [("lint", lint), ("tests", run_tests), ("build", build)]
failed_step = None
for name, step in pipeline:
    if failed_step:
        print(f"{name}: skipped")
        continue
    print(f"--- {name}")
    if step():
        print(f"{name}: passed")
    else:
        print(f"{name}: FAILED")
        failed_step = name
print("result:", "red" if failed_step else "green")
Open in compiler

Line by line

  1. Three functions stand for the three steps. run_tests prints each result and returns True only if all passed.
  2. The loop runs the steps in order. After a failure, every later step is printed as skipped, as in a real CI log.
  3. The last line is the green or red result that appears on the pull request.

Expected result

--- lint
lint: passed
--- tests
PASS test_add
FAIL test_empty
PASS test_big
tests: FAILED
build: skipped
result: red

In the real world

Almost every serious project runs CI, and many will not merge a pull request with a red check. CI also tests the project on several versions of Python or several operating systems at once, which no single contributor could do by hand. Big projects keep a list of flaky tests and track how often each one fails, because they cost the whole team time.

Common mistakes

  • Sending a change without tests, or with tests that never fail.
  • Rerunning a red check until it turns green instead of finding out why it failed.
  • Tests that depend on each other or on the current time and random numbers.
  • Chasing 100 percent coverage with tests that check nothing.

Best practices

  • Write the test for a bug first, see it fail, then fix the bug and see it pass.
  • Keep tests small and fast, and give each a name that says what it checks.
  • Run the whole pipeline's commands on your computer before you push.
  • Read the first error in a log, not the last.

Summary

Tests are small programs that check code, and a regression test keeps a fixed bug from returning. Continuous integration runs a pipeline of lint, test and build steps on every pull request and stops at the first failure. Read the log of a red check, reproduce it locally, and treat flaky tests as bugs.

Quick check

1. What does a regression test protect against?
2. A pipeline has the steps lint, test and build, and the lint step fails. What happens to the others?
3. What is a flaky test?
4. Where do you look first when a check is red?

Key takeaways

  • A change without a test is a change nobody can check.
  • A pipeline runs the same steps on every pull request, and the first failing step stops it.
  • A failing check is information: read its log and fix the cause.
  • A flaky test is a bug in the test or in the code, not something to ignore.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.