Skip to main content
Lavanya-Talele
EditReport

Unit Tests in Python

Hey there! In this guide, we'll explore Unit Tests in Python. Unit testing is a software testing technique where individual parts (units) of a program are tested independently to ensure they work correctly. Let's dive in!


Unit Tests

Unit Testing is a software testing method in which individual units or components of a software application (such as functions, methods, or classes) are tested in isolation to verify that they work correctly as expected.


1. Why use Unit Tests?

  • Verify that functions return expected results
  • Catch errors automatically
  • Simplify debugging
  • Make code easier to maintain
  • Ensure new changes do not break existing functionality

2. PyTest

We can write unit tests using the pytest framework.

Installing Pytest:

pip install pytest

Example:

Python file:

# calculator.py

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

Test file:

# test_calculator.py

from calculator import add

def test_add():
assert add(2, 3) == 5

Running the test:

Run all tests:

pytest

Run a specific file:

pytest test_calculator.py

Example output:

================ test session starts ================
collected 1 item

test_calculator.py . [100%]

================= 1 passed =================

3. Pytest Naming Rules

Pytest automatically detects:

  • Files starting with test_
  • Functions starting with test_

Example:

def test_example():
pass

3.1 Using Assertions

Pytest uses normal Python assert statements.

Example:

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

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

3.2 Multiple Test Cases

A single test file can have multiple tests.

Example:

# math_operations.py

def subtract(a, b):
return a - b
# test_math_operations.py

from math_operations import subtract

def test_positive_numbers():
assert subtract(10, 5) == 5

def test_negative_result():
assert subtract(5, 10) == -5

def test_zero():
assert subtract(7, 7) == 0

3.3 Testing Exceptions

To test exceptions, the with keyword is used.

Example:

# calculator.py

def divide(a, b):
return a / b
# test_calculator.py

import pytest
from calculator import divide

def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(10, 0)

3.4 Parameterized Tests

In the same test, multiple inputs can be tested.

Example:

import pytest

def square(n):
return n * n

@pytest.mark.parametrize("num, result", [
(2, 4),
(3, 9),
(5, 25)
])
def test_square(num, result):
assert square(num) == result

4. Advantages of Pytest

  • Minimal boilerplate
  • Easy syntax
  • Better error messages
  • Powerful fixtures
  • Supports plugins
  • Scales well for large projects
Finished reading? Mark this topic as complete.