Python unittest Basics
A test is a small check that runs code and compares the result. unittest is the built-in tool that runs tests.
A test class
A test class groups tests for one thing. Each test is a method whose name starts with test.
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)Check equality with assertEqual
This small harness uses a bare TestCase to try one assert.
import unittest
checker = unittest.TestCase()
checker.assertEqual(2 + 3, 5)
print("The values are equal")Check truth with assertTrue
assertFalse is the mirror check. It passes when the value is false.
import unittest
checker = unittest.TestCase()
checker.assertTrue("python".startswith("py"))
checker.assertFalse("python".endswith("zz"))
print("Both checks passed")Preview: check an error with assertRaises
The with block must raise the named error. If it does, the check passes.
import unittest
checker = unittest.TestCase()
with checker.assertRaises(ValueError):
int("abc")
print("ValueError was raised")A failing test
This test fails on purpose. The report shows the letter F and both values, the real 5 and the wrong 6.
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 6)Example
# File: textstats.py
def word_count(text):
return len(text.split())
def char_count(text):
return len(text)
def most_common_word(text):
words = text.lower().split()
best = ""
best_count = 0
for word in words:
count = words.count(word)
if count > best_count:
best = word
best_count = count
return best
# File: test_textstats.py
import unittest
from textstats import word_count, char_count, most_common_word
class TestTextStats(unittest.TestCase):
def test_word_count(self):
self.assertEqual(word_count("one two three"), 3)
def test_word_count_empty(self):
self.assertEqual(word_count(""), 0)
def test_char_count(self):
self.assertEqual(char_count("hello"), 5)
def test_most_common_word(self):
self.assertEqual(most_common_word("cat dog cat"), "cat")
if __name__ == "__main__":
unittest.main()Key points
- Test: a small check that runs code and compares the result.
- Use unittest.TestCase as the base class for a group of tests.
- Use assertEqual(a, b) to check that two values are equal.
- Use assertTrue(x) to check that a value is true.
- Use assertRaises to check that code raises an error.
- Run tests with python3 -m unittest in the folder with your files.
- A dot in the report means a test passed.
- The letter F means a test failed.
- A failing assert stops that one test.
- Python can run the same checks again and again.
In this example, the code under test lives in textstats.py. The tests live in test_textstats.py, in the same folder. Save the two parts into those two files. Then run python3 -m unittest from that folder. The four dots mean four tests passed. The Ran line also reports a time in seconds. That time is different on every run, so it is not shown here. The word OK at the end means every test passed.
Note
The other tests still run, so you see every problem at once.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does a dot mean in the unittest report?