Writing Your First Tests
Writing a test is simpler than it sounds: call your code, and assert the result is what you expect. Here's how to do it with Python's built-in tools and a readable style.
Testing sounds advanced, but writing a test is genuinely simple: call your function with a known input, and assert the result equals what you expect. That's it. This session shows the practical mechanics - the assert pattern, Python's built-in unittest, and how to structure clear tests - so you can start testing your own code today.
The assert pattern
At heart, every test is an assertion: a statement that must be true. If it isn't, the test fails and tells you.
# arrange - set up inputs
items = [3, 1, 2]
# act - run the code under test
result = sorted(items)
# assert - check the result
assert result == [1, 2, 3]expect(result).to_equal(...).Using Python's unittest
For real projects, you group tests in Python's built-in unittest - no installation needed - so you can run them all with one command.
import unittest
from mymath import add
class TestAdd(unittest.TestCase):
def test_positives(self):
self.assertEqual(add(2, 3), 5)
def test_negatives(self):
self.assertEqual(add(-1, -1), -2)
if __name__ == "__main__":
unittest.main()| unittest method | Checks |
|---|---|
| assertEqual(a, b) | a == b |
| assertTrue(x) / assertFalse(x) | x is truthy / falsy |
| assertIn(item, container) | item is in container |
| assertRaises(Err, fn, ...) | fn raises Err |
Every Larz library uses unittest exactly like this - it's the standard, and it's built in. Name tests clearly (test_negatives), keep each focused, and run them with 'python -m unittest'. That one command re-checks your whole project in seconds.
Start testing today
- Every test is an assertion - a statement that must be true.
- Arrange, Act, Assert - set up, run the code, check the result.
- unittest is built into Python - group tests, run them all with one command.
- Keep each test focused and clearly named - one thing, obvious pass/fail.
๐งฉ Do it with LarzOS
Turn this lesson into action with the exact free tools and AI workflows for the job:
๐ฏ Key takeaways
- Writing a test is simple: call your code with a known input, and assert the result is what you expect.
- Structure tests as Arrange, Act, Assert - set up inputs, run the code, check the outcome.
- Python's built-in unittest groups tests so you run them all with one command (no installation).
- Keep each test focused on one thing and clearly named, with an obvious pass/fail.
Frequently asked
What's the difference between a plain assert and using unittest?
They're two levels of the same idea, and you'll use both. A plain assert statement is the raw mechanism: 'assert result == expected' simply checks that the condition is true and raises an AssertionError if not. It's perfect for a quick check, for tests inside a simple script, and for understanding what testing fundamentally is - a test is just an assertion that something is true. unittest (Python's built-in testing framework) is a structured way to organise many tests: you group related tests as methods in a class, it provides convenient assertion methods (assertEqual, assertTrue, assertRaises, and so on) that give clearer failure messages than a bare assert, and crucially it gives you a test runner - one command ('python -m unittest') that finds and runs all your tests, reports how many passed and failed, and shows details for failures. So plain asserts are the atoms, and unittest is the framework that organises those atoms into a suite you can run and manage at scale. For a tiny script, a few plain asserts might be all you need. For a real project with many tests, unittest's organisation and runner are very valuable - you want to run your whole test suite easily, see a clear pass/fail summary, and get good failure messages, which is exactly what a framework provides. The good news is unittest is built into Python, so there's nothing to install, and its assertion methods are basically nicer-reporting versions of the asserts you already understand (assertEqual(a, b) is essentially assert a == b but with a helpful message when it fails). There are also other testing frameworks (like pytest, which many people love for its simplicity, and readable ones like the Larz stack's larztest), but the concepts transfer: they all organise and run assertions. Start by understanding that a test is an assertion (plain assert), then use a framework like unittest to organise your tests into a runnable suite as your projects grow. Both are 'real' testing; the framework just adds structure, convenience, and a runner on top of the basic assert idea.
How do I know if my test is actually testing the right thing?
A good test checks a specific, meaningful expectation about your code's behaviour with a clear pass/fail, and you can sanity-check it a few ways. First, a genuinely useful test should be able to fail: if you deliberately break the code it's testing (say, change a plus to a minus), the test should go red. If it passes no matter what you do to the code, it isn't really testing that code - a surprisingly common mistake is writing a test that doesn't actually exercise the thing you think it does, or that asserts something trivially always true. Temporarily breaking your code to confirm the test catches it is a great habit for verifying your tests have teeth. Second, a good test checks behaviour, not implementation details - it should verify what the code should do (given this input, produce this output) rather than how it does it internally, so that you can refactor the internals without the test breaking as long as the behaviour is right. Third, follow the Arrange-Act-Assert shape and keep each test focused on one clear thing: if a test is checking many unrelated things, it's harder to tell what failed and why, so prefer several small focused tests over one sprawling one. Fourth, make sure you're testing the meaningful cases - the normal expected behaviour, the important edge cases (empty input, boundaries, invalid input), and the specific logic that matters - rather than trivial things that can't really go wrong (you don't need to test that Python's addition works). Naming helps too: if you can give the test a clear name describing what it checks (test_returns_zero_for_empty_list), you probably understand what it's testing; if the name is vague, the test might be too. Finally, when a test fails, the failure message should make it obvious what went wrong - which is why clear assertions (and tools like larzdiff for showing exactly what differed) matter. In short: a test is testing the right thing if it checks a specific meaningful behaviour, would fail if that behaviour broke, doesn't depend on internal implementation details, and is focused and clearly named. Building these instincts takes a little practice, but the 'break the code and confirm the test catches it' check is a reliable, concrete way to verify your tests are real from day one.
Related lessons
Why Test? Confidence to Change
Testing isn't about proving you're a good programmer โ it's about being able to change youโฆ
Testing & QualityWhat to Test (and What Not To)
You can't test everything, and you shouldn't try. Good testing is about covering what mattโฆ
Testing & QualityTest-Driven Development
What if you wrote the test *before* the code? It sounds backwards, but writing the test fiโฆ