import os
import logging
from typing import Optional
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def load_environment_variables() -> None:
"""
Loads environment variables and validates them.
Raises:
ValueError: If RUN_FREQUENCY is not a positive integer.
EnvironmentError: If PROJECT_FOLDER or GIT_ACCESS_KEY are not set.
"""
try:
run_frequency_raw: Optional[str] = os.getenv('RUN_FREQUENCY')
project_folder: Optional[str] = os.getenv('PROJECT_FOLDER')
access_key: Optional[str] = os.getenv('GIT_ACCESS_KEY')
# Validate run_frequency
if not run_frequency_raw or not run_frequency_raw.isdigit():
logger.error("RUN_FREQUENCY is not set or not a positive integer.")
raise ValueError("RUN_FREQUENCY must be set to a positive integer.")
run_frequency: int = int(run_frequency_raw)
if run_frequency <= 0:
logger.error("RUN_FREQUENCY must be a positive integer.")
raise ValueError("RUN_FREQUENCY must be a positive integer.")
# Validate project_folder
if project_folder is None:
logger.error("PROJECT_FOLDER is not set.")
raise EnvironmentError("PROJECT_FOLDER must be set.")
# Validate access_key
if access_key is None:
logger.error("GIT_ACCESS_KEY is not set.")
raise EnvironmentError("GIT_ACCESS_KEY must be set.")
logger.info(f"Loaded environment variables successfully. RUN_FREQUENCY: {run_frequency}, PROJECT_FOLDER: {project_folder}, GIT_ACCESS_KEY: [REDACTED]")
except Exception as e:
logger.exception("An error occurred while loading environment variables.")
raise e
# This can be called when the script runs
if __name__ == "__main__":
load_environment_variables()
Tests
import os
import pytest
from your_module import load_environment_variables # Replace 'your_module' with your actual module name
def test_load_environment_variables(monkeypatch):
# Test case for valid input
monkeypatch.setenv('RUN_FREQUENCY', '5')
monkeypatch.setenv('PROJECT_FOLDER', '/path/to/project')
monkeypatch.setenv('GIT_ACCESS_KEY', 'abc123')
# Should run without exceptions
load_environment_variables()
def test_load_environment_variables_invalid_frequency(monkeypatch):
# Test case for invalid RUN_FREQUENCY
monkeypatch.setenv('RUN_FREQUENCY', '-1')
monkeypatch.setenv('PROJECT_FOLDER', '/path/to/project')
monkeypatch.setenv('GIT_ACCESS_KEY', 'abc123')
with pytest.raises(ValueError):
load_environment_variables()
def test_load_environment_variables_missing_project_folder(monkeypatch):
# Test case for missing PROJECT_FOLDER
monkeypatch.setenv('RUN_FREQUENCY', '5')
monkeypatch.setenv('GIT_ACCESS_KEY', 'abc123')
with pytest.raises(EnvironmentError):
load_environment_variables()
def test_load_environment_variables_missing_access_key(monkeypatch):
# Test case for missing GIT_ACCESS_KEY
monkeypatch.setenv('RUN_FREQUENCY', '5')
monkeypatch.setenv('PROJECT_FOLDER', '/path/to/project')
with pytest.raises(EnvironmentError):
load_environment_variables()
Code
Tests