-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_package.py
More file actions
279 lines (222 loc) Β· 9.1 KB
/
test_package.py
File metadata and controls
279 lines (222 loc) Β· 9.1 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python3
"""
Comprehensive test script for envvar-validator package
Demonstrates all major features and functionality
"""
import os
import sys
import subprocess
from pathlib import Path
def test_basic_validation():
"""Test basic environment variable validation"""
print("π Testing Basic Validation...")
# Set up test environment variables
os.environ['DATABASE_URL'] = 'postgresql://user:pass@localhost:5432/db'
os.environ['API_KEY'] = 'sk_test_1234567890abcdef'
os.environ['DEBUG'] = 'true'
os.environ['PORT'] = '8000'
os.environ['EMAIL'] = 'test@example.com'
try:
from env_validator import EnvironmentValidator, ValidationError
# Define schema
schema = {
"DATABASE_URL": {
"type": "str",
"required": True,
"validators": ["database_url"]
},
"API_KEY": {
"type": "str",
"required": True,
"validators": ["api_key"],
"sensitive": True
},
"DEBUG": {
"type": "bool",
"default": False
},
"PORT": {
"type": "int",
"default": 8000,
"validators": ["port_range"]
},
"EMAIL": {
"type": "str",
"validators": ["email"]
}
}
# Create validator
validator = EnvironmentValidator(schema)
# Validate environment
config = validator.validate()
print("β
Basic validation successful!")
print(f" Database URL: {config.DATABASE_URL}")
print(f" API Key: {config.API_KEY}") # Should show as redacted
print(f" Debug: {config.DEBUG}")
print(f" Port: {config.PORT}")
print(f" Email: {config.EMAIL}")
return True
except Exception as e:
print(f"β Basic validation failed: {e}")
return False
def test_framework_integrations():
"""Test framework-specific integrations"""
print("\nποΈ Testing Framework Integrations...")
# Django integration test
try:
from env_validator.frameworks.django import DjangoEnvironmentValidator
django_schema = {
"SECRET_KEY": {"type": "str", "required": True, "validators": ["secret_key"]},
"DATABASE_URL": {"type": "str", "required": True, "validators": ["database_url"]},
"DEBUG": {"type": "bool", "default": False},
"ALLOWED_HOSTS": {"type": "list", "default": ["localhost"]},
}
django_env = DjangoEnvironmentValidator(django_schema)
config = django_env.validate()
print("β
Django integration successful!")
print(f" Secret Key: {config.SECRET_KEY[:10]}...")
print(f" Debug: {config.DEBUG}")
print(f" Allowed Hosts: {config.ALLOWED_HOSTS}")
except Exception as e:
print(f"β Django integration failed: {e}")
# FastAPI integration test
try:
from env_validator.frameworks.fastapi import FastAPIEnvironmentValidator
fastapi_schema = {
"DATABASE_URL": {"type": "str", "required": True},
"API_KEY": {"type": "str", "required": True, "sensitive": True},
"ENVIRONMENT": {"type": "str", "default": "development"},
}
fastapi_env = FastAPIEnvironmentValidator(fastapi_schema)
config = fastapi_env.validate()
print("β
FastAPI integration successful!")
print(f" Environment: {config.ENVIRONMENT}")
except Exception as e:
print(f"β FastAPI integration failed: {e}")
def test_cli_commands():
"""Test CLI commands"""
print("\nπ₯οΈ Testing CLI Commands...")
try:
# Test help command
result = subprocess.run(['envvar-validator', '--help'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
print("β
CLI help command works!")
else:
print(f"β CLI help command failed: {result.stderr}")
# Test list-validators command
result = subprocess.run(['envvar-validator', 'list-validators'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
print("β
CLI list-validators command works!")
print(" Available validators:")
for line in result.stdout.split('\n')[:5]: # Show first 5 lines
if line.strip():
print(f" - {line.strip()}")
else:
print(f"β CLI list-validators command failed: {result.stderr}")
except subprocess.TimeoutExpired:
print("β CLI command timed out")
except FileNotFoundError:
print("β CLI command not found - make sure envvar-validator is installed")
def test_advanced_features():
"""Test advanced features like custom validators and monitoring"""
print("\nπ Testing Advanced Features...")
try:
from env_validator import BaseValidator, ValidationError
from env_validator.monitoring import HealthChecker, DriftDetector
# Custom validator test
class CustomAPIValidator(BaseValidator):
def validate(self, value: str) -> str:
if not value.startswith("sk_"):
raise ValidationError("API key must start with 'sk_'")
return value
custom_schema = {
"API_KEY": {
"type": "str",
"validators": [CustomAPIValidator()]
}
}
from env_validator import EnvironmentValidator
validator = EnvironmentValidator(custom_schema)
config = validator.validate()
print("β
Custom validator works!")
# Health check test
try:
health = HealthChecker.check()
print("β
Health checker works!")
except Exception as e:
print(f"β οΈ Health checker: {e}")
# Drift detection test
try:
drift = DriftDetector.detect()
print("β
Drift detector works!")
except Exception as e:
print(f"β οΈ Drift detector: {e}")
except Exception as e:
print(f"β Advanced features test failed: {e}")
def test_security_features():
"""Test security scanning and compliance features"""
print("\nπ Testing Security Features...")
try:
from env_validator.security import SecurityScanner
# Test security scanner
scanner = SecurityScanner()
vulnerabilities = scanner.scan_environment()
print("β
Security scanner works!")
print(f" Found {len(vulnerabilities)} potential security issues")
# Test audit logging
from env_validator.security import AuditLogger
audit_logger = AuditLogger()
audit_logger.log_validation("test_validation", {"status": "success"})
print("β
Audit logging works!")
except Exception as e:
print(f"β Security features test failed: {e}")
def test_exporters():
"""Test export functionality"""
print("\nπ Testing Export Features...")
try:
from env_validator.utils.exporters import JSONExporter, YAMLExporter
# Test JSON export
test_data = {"DATABASE_URL": "postgresql://localhost/db", "DEBUG": True}
json_exporter = JSONExporter()
json_output = json_exporter.export(test_data)
print("β
JSON exporter works!")
# Test YAML export
yaml_exporter = YAMLExporter()
yaml_output = yaml_exporter.export(test_data)
print("β
YAML exporter works!")
except Exception as e:
print(f"β Export features test failed: {e}")
def main():
"""Run all tests"""
print("π§ͺ Starting envvar-validator Package Tests")
print("=" * 50)
# Set required environment variables for testing
if 'SECRET_KEY' not in os.environ:
os.environ['SECRET_KEY'] = 'django-insecure-test-key-for-validation-only'
tests = [
test_basic_validation,
test_framework_integrations,
test_cli_commands,
test_advanced_features,
test_security_features,
test_exporters
]
passed = 0
total = len(tests)
for test in tests:
try:
if test():
passed += 1
except Exception as e:
print(f"β Test {test.__name__} failed with exception: {e}")
print("\n" + "=" * 50)
print(f"π Test Results: {passed}/{total} tests passed")
if passed == total:
print("π All tests passed! Your envvar-validator package is working perfectly!")
else:
print("β οΈ Some tests failed. Check the output above for details.")
print("\nπ Your envvar-validator package is ready for production use!")
if __name__ == "__main__":
main()