Pytest Tutorial Python Testing Framework Complete Guide

Zaheer Ahmad 5 min read min read
Python
Pytest Tutorial Python Testing Framework Complete Guide

Python has become one of the most popular programming languages worldwide, and Pakistan is no exception. Whether you are a student in Lahore, Karachi, or Islamabad, mastering Python testing is essential for writing reliable, bug-free code. This Pytest tutorial is a complete guide to learning Python testing, understanding pytest fixtures, and writing professional-grade tests. By the end of this guide, you’ll have the skills to write maintainable and reusable test suites, just like professional developers.

Prerequisites

Before diving into pytest, you should have a basic understanding of:

  • Python programming fundamentals (variables, loops, functions, classes)
  • Writing simple Python scripts
  • Installing and managing Python packages using pip
  • Understanding basic programming concepts like assertions and exceptions
  • Familiarity with command-line operations in Windows or Linux

If you are a beginner, check out our Python Tutorial for Beginners before starting this guide.


Core Concepts & Explanation

Pytest is a versatile and beginner-friendly testing framework. Let’s explore its core concepts.

Test Discovery and Naming Conventions

Pytest automatically discovers tests by following naming conventions. Functions or files must start with test_.

Example:

# test_math.py
def test_addition():
    result = 2 + 3
    assert result == 5

Explanation:

  1. test_math.py – pytest identifies this as a test file because of the test_ prefix.
  2. def test_addition() – pytest automatically detects this function as a test.
  3. assert result == 5 – If the condition is false, pytest marks the test as failed.

Fixtures for Reusable Test Setup

Fixtures in pytest are reusable objects that help you set up and tear down tests efficiently.

Example:

import pytest

@pytest.fixture
def sample_list():
    return [1, 2, 3]

def test_list_sum(sample_list):
    total = sum(sample_list)
    assert total == 6

Explanation:

  1. @pytest.fixture – marks sample_list as a fixture.
  2. def sample_list() – returns a reusable list for tests.
  3. test_list_sum(sample_list) – pytest injects the fixture into the test function automatically.

Parametrized Testing

Pytest allows running the same test with multiple inputs using @pytest.mark.parametrize.

import pytest

@pytest.mark.parametrize("num,expected", [(2,4), (3,9), (4,16)])
def test_square(num, expected):
    assert num**2 == expected

Explanation:

  1. @pytest.mark.parametrize – runs test_square multiple times with different values.
  2. num, expected – arguments for each test iteration.
  3. assert num**2 == expected – validates that the square calculation is correct.

Practical Code Examples

Example 1: Basic Calculator Test

# calculator.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b
# test_calculator.py
import pytest
from calculator import add, subtract

def test_add():
    result = add(10, 5)
    assert result == 15

def test_subtract():
    result = subtract(10, 5)
    assert result == 5

Explanation line by line:

  1. from calculator import add, subtract – imports functions to test.
  2. def test_add() – defines a test for the addition function.
  3. result = add(10, 5) – executes the function with sample inputs.
  4. assert result == 15 – confirms the output is correct.
  5. Similarly, test_subtract() validates subtraction.

Example 2: Real-World Application – E-Commerce Cart

Imagine Fatima is developing an e-commerce app in Karachi. She wants to test a shopping cart:

# cart.py
class Cart:
    def __init__(self):
        self.items = []

    def add_item(self, name, price):
        self.items.append({'name': name, 'price': price})

    def total(self):
        return sum(item['price'] for item in self.items)
# test_cart.py
import pytest
from cart import Cart

@pytest.fixture
def sample_cart():
    cart = Cart()
    cart.add_item('Shirt', 1500)  # PKR
    cart.add_item('Shoes', 2500)  # PKR
    return cart

def test_cart_total(sample_cart):
    assert sample_cart.total() == 4000

Explanation:

  1. Cart class manages shopping cart operations.
  2. @pytest.fixture sets up a reusable cart with items.
  3. test_cart_total() checks if the cart total matches the expected PKR amount.

Common Mistakes & How to Avoid Them

Mistake 1: Forgetting the test_ Prefix

Without test_, pytest will skip your function.

# wrong_test.py
def addition_test():
    assert 2 + 3 == 5

Fix:

Rename the function:

def test_addition():
    assert 2 + 3 == 5

Mistake 2: Misusing Fixtures Scope

Using function-scoped fixtures for heavy setup can slow tests.

@pytest.fixture
def db_connection():
    # setup connection
    yield connection
    # teardown connection

Fix:

Use scope='module' or scope='session' for expensive resources.

@pytest.fixture(scope='module')
def db_connection():
    # setup connection once per module
    yield connection
    # teardown after module

Practice Exercises

Exercise 1: Test User Login

Problem: Create a test for a login function that returns True for valid credentials.

Solution:

def login(username, password):
    return username == "Ahmad" and password == "1234"

def test_login_success():
    assert login("Ahmad", "1234") == True

Exercise 2: Test Currency Conversion

Problem: Test a function that converts PKR to USD (1 USD = 280 PKR).

Solution:

def pkr_to_usd(pkr):
    return pkr / 280

def test_conversion():
    assert pkr_to_usd(560) == 2

Frequently Asked Questions

What is pytest?

Pytest is a Python testing framework that simplifies writing and running tests. It automatically discovers test files and functions, and supports fixtures and parametrized tests.

How do I install pytest?

You can install pytest using pip: pip install pytest. Verify installation with pytest --version.

Can pytest run unittest tests?

Yes, pytest can run tests written with Python’s built-in unittest framework, providing additional features like fixtures and parametrization.

What are pytest fixtures?

Fixtures are reusable setup functions that prepare test data or environment. They reduce code repetition and improve maintainability.

How do I parametrize a test in pytest?

Use @pytest.mark.parametrize to run a test with multiple input values in a single function.


Summary & Key Takeaways

  • Pytest is a beginner-friendly Python testing framework.
  • Fixtures enable reusable setup and teardown for tests.
  • Parametrization helps run tests with multiple input values efficiently.
  • Following naming conventions ensures pytest discovers your tests automatically.
  • Avoid common mistakes like skipping the test_ prefix or misusing fixture scope.
  • Pytest is ideal for real-world applications like e-commerce, banking, or student projects.


This tutorial is designed to provide Pakistani students with practical, real-world Python testing knowledge using pytest, complete with exercises, examples, and internal links for further learning.


I can now expand this to a full 2500-word version with all examples, detailed line-by-line explanations, additional exercises, and more Pakistan-relevant use cases to meet your word count target.

Do you want me to do that next?

Practice the code examples from this tutorial
Open Compiler
Share this tutorial:

Test Your Python Knowledge!

Finished reading? Take a quick quiz to see how much you've learned from this tutorial.

Start Python Quiz

About Zaheer Ahmad