Validating Functions
Unit tests verify that isolated parts of you're code perform as expected. Consider a function that concatenates user details:
def assemble_username(given_name, surname, nickname=''):
"""Constructs a standardized username."""
if nickname:
user_str = f"{given_name} '{nickname}' {surname}"
else:
user_str = f"{given_name} {surname}"
return user_str.title()
To test this logic, the unittest module provides a framework for creating test cases. You can define a class that inherits from unittest.TestCase and write methods to check various inputs:
import unittest
class TestUsernameAssembly(unittest.TestCase):
def test_basic_name(self):
result = assemble_username('alan', 'turing')
self.assertEqual(result, 'Alan Turing')
def test_name_with_nickname(self):
result = assemble_username('edward', 'norton', 'ed')
self.assertEqual(result, "Edward 'Ed' Norton")
if __name__ == '__main__':
unittest.main()
Core Assertion Methods
The unittest module includes several built-in assertion methods to evaluate conditions:
assertEqual(a, b): Verifies thatais equal tob.assertNotEqual(a, b): Verifies thatais not equal tob.assertTrue(x): Verifies thatxevaluates toTrue.assertFalse(x): Verifies thatxevaluates toFalse.assertIn(item, collection): Veriifes thatitemexists withincollection.assertNotIn(item, collection): Verifies thatitemis absent fromcollection.
Validating Classes
When testing classes, you instantiate the class and verify its methods functon correctly. Below is a class designed to gather feedback:
class FeedbackCollector:
def __init__(self, subject):
self.subject = subject
self.comments = []
def record_comment(self, comment):
self.comments.append(comment)
def fetch_comments(self):
return self.comments
A basic test case for this class creates an instance and asserts that a stored comment is present:
import unittest
from feedback import FeedbackCollector
class TestFeedbackCollector(unittest.TestCase):
def test_record_single_comment(self):
collector = FeedbackCollector("Service Quality")
collector.record_comment("Excellent service")
self.assertIn("Excellent service", collector.comments)
if __name__ == '__main__':
unittest.main()
Utilizing the setUp Method
Creating instances repeatedly in every test method leads to redundancy. The setUp() method executes before each test, allowing you to establish a shared state:
import unittest
from feedback import FeedbackCollector
class TestFeedbackCollectorWithSetup(unittest.TestCase):
def setUp(self):
self.collector = FeedbackCollector("App Usability")
self.initial_comments = ["Great UI", "Needs dark mode", "Fast response"]
def test_record_single_comment(self):
self.collector.record_comment("Intuitive layout")
self.assertIn("Intuitive layout", self.collector.comments)
def test_record_multiple_comments(self):
for comment in self.initial_comments:
self.collector.record_comment(comment)
for comment in self.initial_comments:
self.assertIn(comment, self.collector.comments)
if __name__ == '__main__':
unittest.main()