You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.9 KiB

Unit Testing Guide

This document provides a comprehensive guide for developers on how to use, write, and monitor unit tests in the be-ircfa project.

🚀 Getting Started

Prerequisites

Before running tests, ensure you have the virtual environment activated and the required dependencies installed.

# 1. Activate the venv
source venv/bin/activate

# 2. Install test dependencies (if not already installed)
pip install pytest pytest-sugar pytest-cov pytest-html

🛠 Running Tests

We have simplified the testing process using a Makefile and pytest.

1. Simple Execution (With Progress Bar)

To run all tests with a premium progress bar and colorful monitoring:

make test

2. Manual Execution

If you prefer running pytest directly:

export PYTHONPATH=$PYTHONPATH:$(pwd)
pytest tests/unit-test/ --color=yes

3. Generating HTML Reports

To generate a detailed HTML report for post-analysis:

pytest tests/unit-test/ --html=report.html --self-contained-html

📊 Monitoring & Aesthetics

We use pytest-sugar to provide a better developer experience:

  • Real-time Progress: A percentage bar shows the current status of the test suite.
  • Color Coding: Instant visual feedback for passes (green) and failures (red).
  • Clearer Failures: Detailed error messages are shown immediately.

✍️ Writing New Tests

All unit tests should be placed in tests/unit-test/. Follow these conventions:

  • File names should start with test_ (e.g., test_auth.py).
  • Function names should start with test_ (e.g., def test_login_success():).
  • Use pytest.mark.parametrize for redundant test cases with different inputs.

Example Template:

import pytest
from src.your_module import your_function

def test_your_feature():
    result = your_function("input")
    assert result == "expected_output"

🏗 CI/CD Integration

To ensure code quality, unit tests should be integrated into the deployment pipeline.

Integration with Jenkins

Add a "Test" stage to your Jenkinsfile before the "Build Docker Image" stage:

stage('Unit Tests') {
    steps {
        sh '''
            source venv/bin/activate
            export PYTHONPATH=${PYTHONPATH}:$(pwd)
            make test
        '''
    }
}

Integration with GitHub Actions

If using GitHub, create .github/workflows/test.yml:

name: Unit Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install pytest pytest-sugar          
      - name: Run Tests
        run: |
          export PYTHONPATH=$PYTHONPATH:$(pwd)
          make test          

Maintained by the RCFA Backend Team.