Unit Testing & Debugging in Python

Write Reliable, Bug-Free, Production-Ready Code

1. What is Unit Testing?

Unit Testing means testing individual units (functions or methods) of your code to ensure they work correctly.

A unit is the smallest testable part of an application.

2. Why Unit Testing is Important

3. Unit Testing Workflow

  1. Write a function
  2. Write test cases for it
  3. Run tests
  4. Fix failures
  5. Repeat

4. Unit Testing with unittest (Built-in)

Example Function

def add(a, b):
    return a + b
      

Test File

import unittest
from math_utils import add

class TestMath(unittest.TestCase):

    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

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

✔ Each assert checks expected vs actual output.

5. Testing with PyTest (Industry Standard)

Install

pip install pytest
      

Example Test

def multiply(a, b):
    return a * b

def test_multiply():
    assert multiply(3, 4) == 12
      

PyTest is preferred because it is:

6. What is Debugging?

Debugging is the process of finding and fixing errors (bugs) in your code.

Bugs can be:

7. Debugging Tools in Python

print() Debugging

print("Value of x:", x)
      

pdb (Python Debugger)

import pdb

def divide(a, b):
    pdb.set_trace()
    return a / b

divide(10, 2)
      

Commands:

8. Debugging Using IDEs

9. Real-Life Use Cases

10. Best Practices

11. External Learning Resources