Unit Testing

Advanced PythonTestingFree Lesson

Advertisement

Introduction

Unit testing ensures code correctness through automated test cases.

Basic Test Case

import unittest

class TestMathOperations(unittest.TestCase):
    
    def test_addition(self):
        self.assertEqual(2 + 2, 4)
    
    def test_division(self):
        with self.assertRaises(ZeroDivisionError):
            1 / 0
    
    def test_list_operations(self):
        lst = [1, 2, 3]
        lst.append(4)
        self.assertEqual(lst, [1, 2, 3, 4])

if __name__ == "__main__":
    unittest.main()

Assertions

self.assertEqual(a, b)        # a == b
self.assertNotEqual(a, b)     # a != b
self.assertTrue(x)           # bool(x) is True
self.assertFalse(x)           # bool(x) is False
self.assertIsNone(x)          # x is None
self.assertIs(a, b)           # a is b (identity)
self.assertIn(x, coll)        # x in collection
self.assertAlmostEqual(a, b)   # a ≈ b (floating point)

Test Fixtures

class TestDatabase(unittest.TestCase):
    
    @classmethod
    def setUpClass(cls):
        cls.db = connect_database()
    
    def setUp(self):
        self.transaction = self.db.begin()
    
    def tearDown(self):
        self.transaction.rollback()
    
    @classmethod
    def tearDownClass(cls):
        cls.db.close()

Practice Problems

  1. Test basic calculator operations
  2. Test exception handling
  3. Use setUp and tearDown
  4. Test edge cases
  5. Mock external dependencies

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement