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
- Find bugs early
- Prevent future bugs (regression)
- Improve code quality
- Make refactoring safe
- Required in real-world production systems
3. Unit Testing Workflow
- Write a function
- Write test cases for it
- Run tests
- Fix failures
- 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:
- Simpler syntax
- Better error messages
- Used in real companies
6. What is Debugging?
Debugging is the process of finding and fixing errors (bugs) in your code.
Bugs can be:
- Syntax errors
- Logical errors
- Runtime errors
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:
n→ next linec→ continueq→ quit
8. Debugging Using IDEs
- VS Code Debugger
- PyCharm Debugger
- Breakpoints
- Variable Watch
- Call Stack
9. Real-Life Use Cases
- Testing APIs
- Validating ML models
- Preventing bugs before deployment
- CI/CD pipelines
- Enterprise applications
10. Best Practices
- Write tests before production
- Test edge cases
- Keep tests independent
- Automate tests
- Debug logically, not randomly