unittest is Python’s built-in testing framework. It organizes tests, provides readable assertion methods, and runs tests repeatedly as code changes, helping confirm that new features work without breaking existing behavior. section 5.0 section 5.4
A unittest test suite follows a small set of conventions:
- Group related tests in classes that inherit from unittest.TestCase, using cohesion, namespacing, and separation of concerns to keep suites manageable. section 5.4.1
- Name test modules test_* or *_test, TestCase subclasses appropriately, and test methods with a test_ prefix so the runner can discover them. section 5.4.2
- Run discovered tests with python -m unittest; place tests beside the code or in a project-level tests/ directory. section 5.4.2
- Use assertions such as assertEqual and assertDictEqual for failure output that communicates what differed. section 5.4.1 section 5.4.6
Testing a product SKU
Create a Product with name 'shoes', size 'S', and color 'black'. The test sets the expected value to 'SHOES', calls transform_name_for_sku(), and compares both values with self.assertEqual. The same pattern extends to color transformation, complete SKU generation, and shopping-cart behavior. section 5.4.3 section 5.4.6
Listing 5.1. A product class for an e-commerce system
class Product:
def __init__(self, name, size, color): #1
self.name = name
self.size = size
self.color = color
def transform_name_for_sku(self):
return self.name.upper()
def transform_color_for_sku(self):
return self.color.upper()
def generate_sku(self): #2
"""
Generates a SKU for this product.
Example:
>>> small_black_shoes = Product('shoes', 'S', 'black')
>>> small_black_shoes.generate_sku()
'SHOES-S-BLACK'
"""
name = self.transform_name_for_sku()
color = self.transform_color_for_sku()
return f'{name}-{self.size}-{color}'
Inspect the small Product class used to practice unittest assertions, including uppercase transformations and combined SKU generation. section 5.4.3



