Friday, November 14, 2025

thumbnail

Automating Tests for Full Stack Python Projects

 1. Unit Testing (Backend)


Unit tests focus on testing individual functions or methods in isolation, ensuring that each component works as expected.


Tools for Backend Unit Testing:


pytest: A popular Python testing framework that is simple, scalable, and provides a lot of useful plugins.


unittest: A built-in Python module, often used for simple testing setups.


mock: To mock external dependencies or services.


Example:


For a simple function in your backend:


# Example backend function in Python

def add_numbers(a, b):

    return a + b



You can write a unit test using pytest:


# test_backend.py

import pytest

from backend_module import add_numbers


def test_add_numbers():

    assert add_numbers(2, 3) == 5

    assert add_numbers(-1, 1) == 0

    assert add_numbers(0, 0) == 0


Running Tests:


To run the tests, simply use the pytest command in the terminal:


$ pytest


2. Integration Testing (Backend)


Integration tests are used to ensure that multiple components of the system work together. For example, if you have a database or external APIs, integration tests verify that data flows correctly between these components.


Tools for Backend Integration Testing:


pytest: Can also be used for integration testing.


Factory Boy: Useful for creating test data.


pytest-django: If using Django, this plugin simplifies integration testing.


pytest-flask: If using Flask, this helps you simulate requests and responses.


Example (Database Integration Test):

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

import pytest


app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'

db = SQLAlchemy(app)


# Simple model

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(50))


@pytest.fixture

def client():

    db.create_all()

    yield app.test_client()

    db.drop_all()


def test_create_user(client):

    response = client.post('/create_user', json={'name': 'John'})

    assert response.status_code == 201

    user = User.query.filter_by(name='John').first()

    assert user is not None


3. End-to-End (E2E) Testing (Full Stack)


End-to-end tests simulate a user interacting with both the frontend and backend. This ensures that all parts of your application work together in a real-world scenario.


Tools for Full Stack E2E Testing:


Selenium: A browser automation tool for testing the UI in a real browser.


Cypress: An end-to-end testing tool for web applications, with a focus on fast, reliable testing.


Playwright: Another browser automation tool, similar to Selenium, but more modern and faster.


Example (Cypress Test):


Cypress is great for testing frontend interactions with the backend.


// Example of an E2E test with Cypress

describe('Full-stack app tests', () => {

  it('should create a user and display them on the list', () => {

    // Visit the app's home page

    cy.visit('http://localhost:3000');

    

    // Interact with the frontend

    cy.get('input[name="username"]').type('John');

    cy.get('button[type="submit"]').click();

    

    // Check if the user was created by verifying the list

    cy.contains('John').should('be.visible');

  });

});



You would typically run Cypress tests using:


$ npx cypress open


4. Mocking External Services (Backend)


Often, your backend will interact with external services, such as third-party APIs or external databases. For testing purposes, you may want to mock these services.


Tools for Mocking:


unittest.mock: A Python standard library for mocking objects.


requests-mock: Useful for mocking HTTP requests in Python tests.


pytest-mock: A pytest plugin for easier mocking with unittest.mock.


Example:


If your backend makes an HTTP request to a third-party API, you can mock this request in your tests:


import requests

from unittest import mock


def get_weather(city):

    response = requests.get(f'https://api.weather.com/{city}')

    return response.json()


# Test

def test_get_weather():

    with mock.patch('requests.get') as mock_get:

        mock_get.return_value.json.return_value = {'temp': 72}

        result = get_weather('New York')

        assert result['temp'] == 72


5. Frontend Unit Testing (If Using React/Vue/Angular)


If your project includes a frontend (e.g., React), you can write unit tests for the frontend as well.


Tools for Frontend Testing:


Jest: A popular testing framework for JavaScript (especially React).


React Testing Library: A library for testing React components.


Mocha/Chai: A testing framework for JavaScript.


Example (React Testing with Jest and React Testing Library):

import { render, screen, fireEvent } from '@testing-library/react';

import UserList from './UserList';


test('renders user list and adds user', () => {

  render(<UserList />);

  

  fireEvent.click(screen.getByText('Add User'));

  

  expect(screen.getByText('John')).toBeInTheDocument();

});



You can run React tests using Jest:


$ npm test


6. CI/CD Integration


Automating tests as part of your Continuous Integration/Continuous Deployment (CI/CD) pipeline is key to ensuring that your tests run on every commit and deployment.


Tools for CI/CD:


GitHub Actions: Automate tests on every push or pull request.


CircleCI: Another CI/CD tool that can automate your testing.


Travis CI: Another popular CI/CD tool that integrates with GitHub.


Example (GitHub Actions for Python and React):


Create a .github/workflows/test.yml file:


name: Run Tests


on: [push]


jobs:

  test:

    runs-on: ubuntu-latest

    

    steps:

    - name: Checkout repository

      uses: actions/checkout@v2


    - name: Set up Python

      uses: actions/setup-python@v2

      with:

        python-version: '3.9'


    - name: Install dependencies

      run: |

        pip install -r backend/requirements.txt

        cd frontend && npm install


    - name: Run backend tests

      run: |

        cd backend && pytest


    - name: Run frontend tests

      run: |

        cd frontend && npm test


7. Test Coverage


For both frontend and backend, you may want to track test coverage to ensure that you're testing a sufficient portion of your code.


Tools for Coverage:


coverage.py: A Python tool for measuring test coverage.


jest --coverage: For measuring test coverage in JavaScript/React tests.


Example (Python):

$ pytest --cov=backend tests/


Example (React):

$ npm test -- --coverage


Conclusion:


Automating tests in a full-stack Python project involves testing both the backend (using tools like pytest and unittest) and the frontend (using tools like Jest and Cypress). It’s important to use different types of tests—unit, integration, and end-to-end—to ensure that each part of your system works in isolation as well as together. By setting up a CI/CD pipeline, you can automate the process and ensure that your tests run on every code change.

Learn Fullstack Python Training in Hyderabad

Read More

How to Use PyTest for Full Stack Python Development

Writing Integration Tests for Python Web Applications

Debugging Your Full Stack Python Application with PDB

Test-Driven Development (TDD) with Python and Django

At Our Quality Thought Training Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive