Python ModulesPytest TutorialReal World examples of pytest

Real-Life Examples with pytest

pytest is a versatile testing framework that can be applied to various real-world scenarios. Let’s explore some practical examples to understand how pytest is used in everyday development workflows.


1. Testing a Python Function or Module

pytest is ideal for verifying the behavior of individual Python functions or modules.

Example: Testing a Calculator Function

# calculator.py
def add(a, b):
    return a + b
 
def subtract(a, b):
    return a - b
# test_calculator.py
from calculator import add, subtract
 
def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
 
def test_subtract():
    assert subtract(5, 3) == 2
    assert subtract(0, 5) == -5

Running the Tests

pytest test_calculator.py

2. Testing a Flask API

pytest can be used with Flask’s test client to verify API endpoints.

Example: Testing a Simple Flask Application

# app.py
from flask import Flask, jsonify
 
app = Flask(__name__)
 
@app.route("/hello")
def hello():
    return jsonify({"message": "Hello, World!"})
# test_app.py
import pytest
from app import app
 
@pytest.fixture
def client():
    app.testing = True
    return app.test_client()
 
def test_hello_endpoint(client):
    response = client.get("/hello")
    assert response.status_code == 200
    assert response.json == {"message": "Hello, World!"}

Running the Tests

pytest test_app.py

3. Integrating pytest into a CI/CD Pipeline

pytest can be integrated into Continuous Integration/Continuous Deployment (CI/CD) pipelines to ensure code quality and reliability.

Example: Using pytest with GitHub Actions

Step 1: Create a requirements.txt

pytest

Step 2: Create a GitHub Actions Workflow

# .github/workflows/python-tests.yml
name: Python Tests
 
on:
  push:
    branches:
      - main
  pull_request:
 
jobs:
  test:
    runs-on: ubuntu-latest
 
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
 
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.9"
 
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
 
      - name: Run pytest
        run: |
          pytest

Result

Each push or pull request triggers the workflow, running pytest to validate your code.


Summary

  • Testing Functions: Validate individual Python functions with pytest.
  • API Testing: Use pytest fixtures and Flask’s test client for API endpoints.
  • CI/CD Integration: Automate testing workflows using pytest in CI/CD pipelines.

These examples demonstrate how pytest fits seamlessly into various stages of the development lifecycle, ensuring your code is robust and reliable.