Unit Testing - RamNayakTech/knowledge-hub GitHub Wiki
Unit testing in Python is the practice of writing tests for individual units of code (typically functions or methods) to ensure they work as expected. Python provides a built-in framework called unittest
, but you can also use other libraries like pytest
for a more flexible approach.
unittest
1. Using unittest
is Python's built-in testing framework.
Example
import unittest
def add(x, y):
return x + y
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
def test_add_fail(self):
self.assertNotEqual(add(2, 2), 5)
if __name__ == '__main__':
unittest.main()
Running the test
Save the script as test_math.py
and run:
python -m unittest test_math.py
pytest
(Recommended)
2. Using pytest
is a more powerful and concise testing framework.
Installation
pip install pytest
Example
import pytest
def add(x, y):
return x + y
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_add_fail():
assert add(2, 2) != 5
Running the test
Save the script as test_math.py
and run:
pytest test_math.py
unittest.mock
3. Mocking with Mocking is useful when testing functions that depend on external services.
Example
from unittest.mock import MagicMock
class ExternalService:
def fetch_data(self):
return "real data"
def get_processed_data(service):
data = service.fetch_data()
return f"Processed {data}"
def test_mocking():
mock_service = ExternalService()
mock_service.fetch_data = MagicMock(return_value="mocked data")
assert get_processed_data(mock_service) == "Processed mocked data"
4. Best Practices for Unit Testing
✅ Write tests for all critical functionalities.
✅ Keep tests independent from each other.
✅ Use meaningful test names (test_add_valid_inputs
).
✅ Cover edge cases (empty values, incorrect data types).
✅ Automate test execution in CI/CD pipelines.