AI Hints
Home›CI/CD with GitHub Actions Tutorial›Reviews, Flaky Tests, and Gates
CI/CD with GitHub Actions · Lesson 74 of 138

Flaky Tests

Pass, fail, pass.

⏱ 2 min read▶ Video at 1:24:42🎓 Free
Watch this lesson in the CI/CD with GitHub Actions courseWatch on YouTube ↗Full CI/CD with GitHub Actions course

A flaky test sometimes passes and sometimes fails, without any change to the code. Flaky tests are poison for CI. Once people learn that red might mean nothing, they start ignoring red, and real bugs slip through.

Flaky Tests
From the video: Flaky Tests
  • Passes, then fails
  • No code change
  • People stop trusting red

A hidden dependency

Here's a classic cause. Cat shows two tests sharing one list. The second test only passes if the first one ran before it. Together, they pass. Run the second test alone, or in a different order, and it fails. In CI, test order and parallel runs can change, so this becomes flaky.

Terminal
cat test_state.py
cart = []

def test_add():
    cart.append("apple")
    assert len(cart) == 1

def test_has_item():
    assert "apple" in cart
pytest -q test_state.py | tail -1
2 passed in 0.01s
pytest -q test_state.py::test_has_item | tail -1
1 failed in 0.01s

Common causes and fixes

Shared state between tests, like this one. Fix it by giving each test its own fresh data. Timing, like sleeping and hoping something is ready. Wait for a real signal instead. Real network calls, which can be slow or down. Use fakes in unit tests. And randomness, which you can fix with a seed.

keyvalue
Shared statefresh data per test
Timingwait for a signal
Networkuse fakes
Randomnessset a seed

Summary

Flaky tests destroy trust in CI. Find the cause, fix it, and quarantine the test until you do. Re running until green only hides the problem. Next, practice building a quality gate.

Key takeaways
  • Same code, different result
  • Shared state, timing, network
  • Fix, don't re-run
Next up: Practice: A Quality Gate — lint, format, test