Python Testing with unittest
In this page:
Introduction to Unit Testing
Unit testing means writing code that automatically verifies individual pieces of your application -- functions or classes -- behave correctly, rather than manually re-checking behavior by hand every time you make a change. unittest is Python's built-in testing framework, modeled after the xUnit family found in many other languages.
Example: Introduction to Unit Testing
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
unittest.main(argv=[""], exit=False)
Writing Assertions
Assertion methods like assertEqual(a, b) check that two values match and produce a clear, specific failure message naming both values if they don't -- more informative than a bare assert a == b, which only tells you the assertion failed without showing what the actual values were.
Example: Writing Assertions
import unittest
class TestMath(unittest.TestCase):
def test_equal(self):
self.assertEqual(2 + 2, 4)
unittest.main(argv=[""], exit=False)
Testing Exceptions
assertRaises() is used as a context manager to verify that a block of code raises a specific exception type when given invalid input, letting you test error-handling paths as rigorously as you test the normal success path.
Example: Testing Exceptions
import unittest
def divide(a, b):
return a / b
class TestDivide(unittest.TestCase):
def test_zero_division(self):
with self.assertRaises(ZeroDivisionError):
divide(1, 0)
unittest.main(argv=[""], exit=False)
Setup and Teardown Methods
setUp() runs automatically before every individual test method in a test class, and tearDown() runs automatically after each one -- the standard place to prepare shared fixtures (like mock files or database connections) and then clean them up, without repeating that setup code in every single test.
Example: Setup and Teardown Methods
import unittest
class TestExample(unittest.TestCase):
def setUp(self):
self.value = 10
def test_value(self):
self.assertEqual(self.value, 10)
unittest.main(argv=[""], exit=False)
Running unittest inside Script
Adding unittest.main() inside an if __name__ == __main__: guard lets you run all the tests in a file directly by executing that script, without needing to invoke a separate test-runner command -- convenient for quick, single-file test suites.
Example: Running unittest inside Script
import unittest
class TestBasic(unittest.TestCase):
def test_true(self):
self.assertTrue(1 == 1)
if __name__ == "__main__":
unittest.main(argv=[""], exit=False)
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects