liveBook · Manning

TestCase

As explained in Python How-To

TestCase is the unittest base class that provides structure and assertion methods for individual test cases.

TestCase is the unittest base class for organizing individual tests. Create a subclass, name it with a Test prefix, and add test_ methods whose assertions compare actual results with expected results. section 13.3.2 section 13.5

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 focused example subclasses TestCase, calls create_task, compares object state with assertEqual, and runs the suite through unittest.main(). section 13.3.2

Use TestCase subclasses to:

Running a two-test suite

Executing the test file produces two dots followed by “Ran 2 tests in 0.000s” and “OK”, indicating that both tests passed. section 13.4.1

How Python How-To covers it

How deep it goes
Explains subclassing, naming, assertions, setUp, and execution, without detailing the full assertion-method API.
Examples
Demonstrates testing task-creation functions and class methods with object dictionaries, assertEqual, setUp, and passing command-line output.
What it assumes
Assumes basic functions, classes, methods, and expected outputs while teaching automatic test structure from the unittest module.
What you can do after
Build it from scratch by subclassing TestCase, writing test_ methods, asserting results, and running unittest.main().
How it connects
Connects unittest with unit testing, test discovery, assertions, setUp, functions, and class methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.