Back to Repositories

Testing Simple Authentication Mechanism in private-gpt

This test suite validates the simple authentication mechanism in private-gpt, focusing on request authentication handling and authorization header validation. The tests ensure proper 401/200 response codes based on authentication status.

Test Coverage Overview

The test suite provides comprehensive coverage of the simple authentication mechanism.

Key areas tested include:
  • Authentication failure scenarios (401 responses)
  • Successful authentication with valid secret (200 responses)
  • Authorization header validation
  • Dependency injection for authentication

Implementation Analysis

The testing approach utilizes pytest fixtures and FastAPI’s TestClient for authentication validation.

Key implementation patterns include:
  • Dependency override for authentication mechanism
  • Fixture-based test configuration
  • Request simulation with TestClient
  • Status code verification

Technical Details

Testing tools and configuration:
  • pytest framework for test organization
  • FastAPI TestClient for HTTP request simulation
  • Dependency injection for authentication override
  • Fixture-based test setup and teardown
  • Type annotations for improved code clarity

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Isolated test cases with proper setup/teardown
  • Clear test naming conventions
  • Proper assertion usage
  • Efficient test dependency management
  • Clean separation of concerns

zylon-ai/private-gpt

tests/server/utils/test_simple_auth.py

            
"""Tests to validate that the simple authentication mechanism is working.

NOTE: We are not testing the switch based on the config in
      `private_gpt.server.utils.auth`. This is not done because of the way the code
      is currently architecture (it is hard to patch the `settings` and the app while
      the tests are directly importing them).
"""

from typing import Annotated

import pytest
from fastapi import Depends
from fastapi.testclient import TestClient

from private_gpt.server.utils.auth import (
    NOT_AUTHENTICATED,
    _simple_authentication,
    authenticated,
)
from private_gpt.settings.settings import settings


def _copy_simple_authenticated(
    _simple_authentication: Annotated[bool, Depends(_simple_authentication)]
) -> bool:
    """Check if the request is authenticated."""
    if not _simple_authentication:
        raise NOT_AUTHENTICATED
    return True


@pytest.fixture(autouse=True)
def _patch_authenticated_dependency(test_client: TestClient):
    # Patch the server to use simple authentication

    test_client.app.dependency_overrides[authenticated] = _copy_simple_authenticated

    # Call the actual test
    yield

    # Remove the patch for other tests
    test_client.app.dependency_overrides = {}


def test_default_auth_working_when_enabled_401(test_client: TestClient) -> None:
    response = test_client.get("/v1/ingest/list")
    assert response.status_code == 401


def test_default_auth_working_when_enabled_200(test_client: TestClient) -> None:
    response_fail = test_client.get("/v1/ingest/list")
    assert response_fail.status_code == 401

    response_success = test_client.get(
        "/v1/ingest/list", headers={"Authorization": settings().server.auth.secret}
    )
    assert response_success.status_code == 200