🔍 Code Extractor

function test_setup

Maturity: 44

Validates the presence of required API keys (OpenAI and SERPER) and sets them as environment variables with fallback default values.

File:
/tf/active/vicechatdev/find_email/test_enrichment.py
Lines:
19 - 34
Complexity:
simple

Purpose

This function serves as a setup validation step for applications requiring OpenAI and SERPER API access. It checks if the necessary API keys are available in environment variables, logs their status, and ensures they are set in the environment. If keys are not found in the environment, it falls back to hardcoded default values. This is typically used during application initialization or testing phases to verify that all required external service credentials are properly configured.

Source Code

def test_setup():
    """Test that all required components are available"""
    logger.info("Testing setup...")
    
    # Check API keys
    openai_key = os.environ.get("OPENAI_API_KEY", "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")
    serper_key = os.environ.get("SERPER_API_KEY", "9a1f42c99feee69526e216af14e07b64fb4b3bfb")
    
    logger.info(f"OpenAI API key: {'✓ Set' if openai_key else '✗ Missing'}")
    logger.info(f"SERPER API key: {'✓ Set' if serper_key else '✗ Missing'}")
    
    # Set environment variables
    os.environ["OPENAI_API_KEY"] = openai_key
    os.environ["SERPER_API_KEY"] = serper_key
    
    return True

Return Value

Returns a boolean value True unconditionally, indicating the setup check has completed. The function always succeeds regardless of whether API keys were found or set to defaults.

Dependencies

  • os
  • logging

Required Imports

import os
import logging

Usage Example

import os
import logging

# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# Optionally set API keys before calling
# os.environ['OPENAI_API_KEY'] = 'your-openai-key'
# os.environ['SERPER_API_KEY'] = 'your-serper-key'

# Call the setup function
result = test_setup()
print(f"Setup completed: {result}")

# API keys are now available in environment
print(f"OpenAI Key set: {bool(os.environ.get('OPENAI_API_KEY'))}")
print(f"SERPER Key set: {bool(os.environ.get('SERPER_API_KEY'))}")

Best Practices

  • SECURITY WARNING: This function contains hardcoded API keys which should NEVER be committed to version control or shared publicly. Remove default values and require proper environment variable configuration.
  • The function requires a 'logger' object to be defined in the calling scope before execution.
  • Always set API keys through environment variables rather than relying on hardcoded defaults.
  • Consider raising an exception or returning False if critical API keys are missing instead of always returning True.
  • The function modifies global state (environment variables) which may affect other parts of the application.
  • For production use, implement proper secrets management instead of environment variables with fallback defaults.
  • The function name suggests it's for testing, but it performs actual configuration - consider renaming for clarity in production code.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function validate_api_key 70.1% similar

    Validates the presence of an OpenAI API key by checking function parameters and environment variables, returning the key or exiting with an error message if not found.

    From: /tf/active/vicechatdev/e-ink-llm/main.py
  • function test_configuration_v1 64.1% similar

    Validates that all required configuration variables (Azure AD credentials, OpenAI API key, and domain) are properly set and not using placeholder values.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
  • function init_openai_client 60.5% similar

    Initializes the OpenAI client by setting the API key from either a provided parameter or environment variable.

    From: /tf/active/vicechatdev/chromadb-cleanup/src/summarization/summarizer.py
  • function setup_environment 56.7% similar

    Loads environment variables from a .env file located in the same directory as the script, if the file exists.

    From: /tf/active/vicechatdev/e-ink-llm/main.py
  • function test_config 56.7% similar

    A test function that validates the presence and correctness of all required configuration settings for a multi-model RAG (Retrieval-Augmented Generation) system.

    From: /tf/active/vicechatdev/docchat/test_model_selection.py
← Back to Browse