Spex3
    

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