How can you check that a code change has not broken a function? A test case supplies a particular input and checks for a particular expected result. Unlike a manual check, an automated test can be run again whenever the code changes. section 13.3.2 section 13.3
Check a task-creation function
Given "Laundry,3", create_task should return a Task with title "Laundry" and urgency 3. Call the function, then compare the result with the expected values using assertEqual. The example compares the objects’ __dict__ attributes because custom Task instances are not equal out of the box. section 13.3.1 section 13.3.2
Listing 13.5 Testing a function using TestCase (test_task_func.py)
from task_func import Task, create_task #1
import unittest #2
class TestTaskCreation(unittest.TestCase): #3
def test_create_task(self):
task_text = "Laundry,3"
created_task = create_task(task_text) #4
self.assertEqual(created_task.__dict__,
Task("Laundry", 3).__dict__)
if __name__ == "__main__":
unittest.main()
A complete test file shows a unittest.TestCase subclass, a test_-prefixed method, and the assertion for that input. section 13.3.2
To add another test case:
- Choose a specific input and decide what the result should be. section 13.3.1
- Add a test_-prefixed method to a unittest.TestCase subclass; call the code and assert the expected result. section 13.3.2
- Run the test file. Each dot represents a passing test; adding a second test method produces two dots. section 13.3.2
The same pattern works for class methods and instance methods. If several tests need the same expected task values, setUp can prepare them. When a test fails, inspect the reported actual and expected values before changing the application: the formatted-display example fails because its expected string omits a space that the method returns. section 13.4.1 section 13.4.2
Keep checking small features manually as you build them, then use automated cases to make repeated checks less costly. A failure may also come from an exception in the code under test, not just a mismatched assertion. section 13.4.3 section 13.4.4




















































