File size: 4,430 Bytes
db7c1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/env python3
"""
Test script to verify configuration management functionality
"""
import os
import sys
from pathlib import Path

# Add the src directory to the path so we can import modules
sys.path.insert(0, str(Path(__file__).parent))

def test_config_validation():
    """Test that configuration validation works properly"""
    print("Testing configuration validation...")

    # Test 1: Check that settings can be imported and initialized
    try:
        from config.settings import settings
        print("βœ“ Settings module imported successfully")
        print(f"βœ“ Server host: {settings.server_host}")
        print(f"βœ“ Server port: {settings.server_port}")
        print(f"βœ“ Debug mode: {settings.debug}")
        print(f"βœ“ Log level: {settings.log_level}")
    except Exception as e:
        print(f"βœ— Failed to import or initialize settings: {e}")
        return False

    # Test 2: Check that required fields are validated
    # Temporarily unset a required environment variable to test validation
    original_neon_url = os.environ.get('NEON_DB_URL')

    # Remove the environment variable to test validation
    if 'NEON_DB_URL' in os.environ:
        del os.environ['NEON_DB_URL']

    # Try to create new settings instance without required env var
    try:
        from pydantic_settings import BaseSettings
        from pydantic import ValidationError

        # This should fail because we removed a required environment variable
        from config.settings import Settings
        try:
            temp_settings = Settings()
            print("βœ— Validation failed - should have raised an error for missing required field")
            return False
        except (ValidationError, ValueError) as e:
            print(f"βœ“ Validation correctly caught missing required field: {type(e).__name__}")
        except Exception as e:
            print(f"βœ“ Validation correctly caught missing required field: {type(e).__name__}")
    finally:
        # Restore the original environment variable
        if original_neon_url is not None:
            os.environ['NEON_DB_URL'] = original_neon_url

    # Test 3: Check that default values work
    print(f"βœ“ JWT algorithm default: {settings.jwt_algorithm}")
    print(f"βœ“ JWT expires in default: {settings.jwt_expires_in}")

    # Test 4: Check that debug validation works with string input
    original_debug = os.environ.get('DEBUG')
    try:
        os.environ['DEBUG'] = 'true'
        from config.settings import Settings
        temp_settings = Settings()
        assert temp_settings.debug is True
        print("βœ“ Debug validation works with 'true' string")

        os.environ['DEBUG'] = 'false'
        temp_settings = Settings()
        assert temp_settings.debug is False
        print("βœ“ Debug validation works with 'false' string")

        os.environ['DEBUG'] = '1'
        temp_settings = Settings()
        assert temp_settings.debug is True
        print("βœ“ Debug validation works with '1' string")

    except Exception as e:
        print(f"βœ— Debug validation test failed: {e}")
        return False
    finally:
        # Restore original value
        if original_debug is not None:
            os.environ['DEBUG'] = original_debug
        elif 'DEBUG' in os.environ:
            del os.environ['DEBUG']

    print("\nβœ“ All configuration validation tests passed!")
    return True

def test_database_config():
    """Test that database configuration works properly"""
    print("\nTesting database configuration...")

    try:
        from config.database import engine, AsyncSessionLocal, logger
        print("βœ“ Database engine created successfully")
        print("βœ“ Async session factory created successfully")
        print(f"βœ“ Database URL is properly configured (not shown for security)")
        print("βœ“ Connection pool settings applied")
    except Exception as e:
        print(f"βœ— Database configuration test failed: {e}")
        return False

    print("βœ“ Database configuration test passed!")
    return True

if __name__ == "__main__":
    print("Running Configuration Management Tests...\n")

    config_ok = test_config_validation()
    db_ok = test_database_config()

    if config_ok and db_ok:
        print("\nπŸŽ‰ All tests passed! Configuration management is working correctly.")
        sys.exit(0)
    else:
        print("\n❌ Some tests failed!")
        sys.exit(1)