This document introduces unit testing in Python, covering the process, naming conventions, test structure, and result interpretation. It explains how to build, execute, and review unit tests for reliable code quality.
This document explains the fundamentals of unit testing in Python, including the test process, naming conventions, test structure, and how to interpret results. Readers will learn to build, execute, and review unit tests for robust code quality.
Unit testing validates that individual units of code operate as intended. A unit is a small, testable part of an application, such as a function or method.
The unit test process involves two main phases:
unittest Python library to create unit tests.test to the module name (e.g., test_mymodule.py).from mymodule import square, doubler).Test and inherit from unittest.TestCase (e.g., class TestMyModule(unittest.TestCase):).test (e.g., def test_square(self):).assertEqual to compare actual and expected values.| Assertion Method | Purpose |
|---|---|
| assertEqual | Checks if two values are equal |
| assertTrue | Checks if a condition is true |
| assertFalse | Checks if a condition is false |
OK.| Step | Description |
|---|---|
| Local Testing | Test units on local system, fix issues, retest |
| Server Testing | Test units on CI/CD server, fix issues, retest |
| Integration | Merge passing units into final code base |
Unit testing ensures that code units function as designed, improving reliability and maintainability. Following proper naming conventions, structuring tests, and reviewing outputs are essential for effective testing and robust software development.
(1) Unit testing checks that each small, testable part of an application works as designed.
(2) If a unit test fails locally, the issue should be fixed and the test rerun before proceeding.
(3) Test files and classes should be clearly named to indicate their purpose and relation to the module.
(1) assertEqual compares the actual output of a function to the expected value.
| Step | Description |
|---|---|
| A. Local Testing | 1. Merge passing units into final code base |
| B. Server Testing | 2. Test units on local system, fix issues, retest |
| C. Integration | 3. Test units on CI/CD server, fix issues, retest |
A-2, B-3, C-1.
(2) Unit test output details which tests passed or failed, aiding in debugging.
Only functions that start with ’test’ in a unit test class are executed by the unittest framework.
True. The unittest framework runs only those functions whose names begin with ’test'.