Back to Repositories

Testing YAML Configuration Environment Variable Loading in private-gpt

This test suite validates the YAML configuration loading functionality in private-gpt, focusing on environment variable substitution and default value handling. The tests ensure proper loading of environment variables into YAML configurations while maintaining security and flexibility.

Test Coverage Overview

The test suite provides comprehensive coverage of YAML configuration loading scenarios.

Key areas tested include:
  • Basic environment variable substitution
  • Default value handling
  • Edge cases with duplicated delimiters
  • Error handling for missing variables

Implementation Analysis

The testing approach utilizes pytest fixtures and StringIO for isolated YAML content testing. The implementation follows a systematic pattern of testing both successful and failure scenarios, leveraging pytest’s exception handling capabilities for validation.

Technical patterns include:
  • Mock environment variable injection
  • StringIO for file-like objects
  • Pytest assertion mechanisms

Technical Details

Testing tools and configuration:
  • pytest framework for test execution
  • io.StringIO for YAML content simulation
  • Environment variable manipulation
  • Custom YAML loader with environment variable support

Best Practices Demonstrated

The test suite exemplifies several testing best practices in Python.

Notable practices include:
  • Isolated test cases with clear scope
  • Proper exception testing
  • Clean setup and teardown
  • Comprehensive edge case coverage

zylon-ai/private-gpt

tests/settings/test_settings_loader.py

            
import io
import os

import pytest

from private_gpt.settings.yaml import load_yaml_with_envvars


def test_environment_variables_are_loaded() -> None:
    sample_yaml = """
    replaced: ${TEST_REPLACE_ME}
    """
    env = {"TEST_REPLACE_ME": "replaced"}
    loaded = load_yaml_with_envvars(io.StringIO(sample_yaml), env)
    os.environ.copy()
    assert loaded["replaced"] == "replaced"


def test_environment_defaults_variables_are_loaded() -> None:
    sample_yaml = """
    replaced: ${PGPT_EMBEDDING_HF_MODEL_NAME:BAAI/bge-small-en-v1.5}
    """
    loaded = load_yaml_with_envvars(io.StringIO(sample_yaml), {})
    assert loaded["replaced"] == "BAAI/bge-small-en-v1.5"


def test_environment_defaults_variables_are_loaded_with_duplicated_delimiters() -> None:
    sample_yaml = """
    replaced: ${PGPT_EMBEDDING_HF_MODEL_NAME::duped::}
    """
    loaded = load_yaml_with_envvars(io.StringIO(sample_yaml), {})
    assert loaded["replaced"] == ":duped::"


def test_environment_without_defaults_fails() -> None:
    sample_yaml = """
    replaced: ${TEST_REPLACE_ME}
    """
    with pytest.raises(ValueError) as error:
        load_yaml_with_envvars(io.StringIO(sample_yaml), {})
    assert error is not None