This document explains the purpose of assertions in testing, describes common PyUnit assertions, and discusses the role of happy and sad paths in test case design.
This document explores the purpose and use of assertions in Python testing, highlights common PyUnit assertions, and explains the importance of testing both happy and sad paths for robust code validation.
Assertions are statements in test cases that check if a condition is true or false. They are essential for determining whether code behaves as expected. If an assertion fails, the test fails, helping identify issues early.
Assertions can be made using Python’s built-in assert statement or with specialized assertion methods provided by test frameworks like PyUnit (unittest). These methods make tests more readable and expressive.
1assert sum(2, 3) == 5
1from unittest import TestCase
2class TestSum(TestCase):
3 def test_sum(self):
4 self.assertEqual(sum(2, 3), 5)
| Assertion Method | Purpose |
|---|---|
| assertEqual(a, b) | Check that a is equal to b |
| assertNotEqual(a, b) | Check that a is not equal to b |
| assertIn(a, b) | Check that a is in b |
| assertNotIn(a, b) | Check that a is not in b |
| assertTrue(x) | Check that x is True |
| assertFalse(x) | Check that x is False |
| assertIsInstance(a, T) | Check that a is an instance of type T |
| assertRaises(E, f, …) | Check that function f raises exception E |
| assertAlmostEqual(a, b) | Check that a and b are almost equal (floats) |
1from unittest import TestCase
2from triangle import area_of_a_triangle
3
4class TestAreaOfTriangle(TestCase):
5 def test_happy_paths(self):
6 self.assertAlmostEqual(area_of_a_triangle(3.4556, 8.3567), 14.43870626)
7 self.assertEqual(area_of_a_triangle(2, 5), 5.0)
8 self.assertEqual(area_of_a_triangle(0, 5), 0.0)
9
10 def test_sad_paths(self):
11 with self.assertRaises(ValueError):
12 area_of_a_triangle(-2, 5)
13 with self.assertRaises(ValueError):
14 area_of_a_triangle(2, -5)
15 with self.assertRaises(TypeError):
16 area_of_a_triangle(True, 5)
17 with self.assertRaises(TypeError):
18 area_of_a_triangle(2, "height")
Assertions are the foundation of effective test cases. Using a variety of assertion methods and testing both happy and sad paths ensures code is robust, reliable, and handles errors as expected.
(1) Happy paths confirm correct results for valid input, while sad paths ensure errors are handled properly.
| Assertion Method | Purpose |
|---|---|
| A. assertEqual | 1. Check that a is in b |
| B. assertIn | 2. Check that a is equal to b |
| C. assertRaises | 3. Check that a function raises exception |
| D. assertIsInstance | 4. Check that a is an instance of a type |
A-2, B-1, C-3, D-4.
assertTrue and assertFalse are used to check if a value is True or False in a test case.
True. These assertions verify boolean conditions in test cases.