Python Testing: unittest & pytest ๐งช๐

Testing is crucial for writing reliable and maintainable Python code. Python provides two popular testing frameworks:
๐น unittest โ Built-in, inspired by Java's JUnit.
๐น pytest โ More user-friendly, supports fixtures & plugins.
1๏ธโฃ unittest โ Built-in Testing Framework ๐๏ธ
๐น Comes pre-installed with Python.
๐น Uses classes and methods for structuring tests.
๐น Requires assert methods like assertEqual(), assertTrue(), etc.
Basic Example
import unittest
# Function to test
def add(x, y):
return x + y
# Create a Test Case
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
# Run the tests
if __name__ == "__main__":
unittest.main()
โ
Run the test
python test_file.py
Key unittest Methods
Method Description
assertEqual(a, b) Check if a == b
assertNotEqual(a, b) Check if a != b
assertTrue(x) Check if x is True
assertFalse(x) Check if x is False
assertRaises(Exception, func, args) Check if function raises an exception
2๏ธโฃ pytest โ Simpler & More Powerful ๐
๐น More concise โ No need to define classes, just write test functions.
๐น Better error reporting โ Shows detailed output.
๐น Supports fixtures โ Useful for setting up test data.
Installing pytest
pip install pytest
Basic pytest Example
# Function to test
def multiply(x, y):
return x * y
# Test function (No need for classes!)
def test_multiply():
assert multiply(2, 3) == 6
assert multiply(-1, 5) == -5
โ
Run the test
pytest test_file.py
Advanced pytest with Fixtures
Fixtures help set up test environments (like database connections).
import pytest
@pytest.fixture
def sample_data():
return {"name": "Alice", "age": 30}
def test_user(sample_data):
assert sample_data["name"] == "Alice"
assert sample_data["age"] == 30
3๏ธโฃ unittest vs pytest โ Which to Use?
Feature unittest pytest
Installation Built-in Requires pip install pytest
Syntax Uses classes & methods Simple functions
Fixtures Manual setup/teardown Built-in fixture support
Output Basic error messages Detailed output
Date: 2025-03-24 00:00:00.000000