-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_redis_implementation.py
More file actions
193 lines (160 loc) Β· 6.36 KB
/
test_redis_implementation.py
File metadata and controls
193 lines (160 loc) Β· 6.36 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
#!/usr/bin/env python3
"""
Test script for Redis implementations in Envoyou API.
Tests rate limiting, session management, and response caching.
"""
import os
import sys
from datetime import datetime
# Add the app directory to Python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'app'))
def test_redis_connection():
"""Test Redis connection."""
print("π Testing Redis Connection...")
try:
from utils.redis_utils import _get_redis_client, redis_health_check
client = _get_redis_client()
if client:
health = redis_health_check()
print(f"β
Redis Status: {health['status']}")
print(f" Available: {health['available']}")
return True
else:
print("β Redis client not available")
return False
except Exception as e:
print(f"β Redis connection test failed: {e}")
return False
def test_rate_limiting():
"""Test Redis-based rate limiting."""
print("\nπ¦ Testing Rate Limiting...")
try:
from utils.redis_utils import redis_rate_limit
test_key = f"test_rate_limit_{datetime.now().timestamp()}"
# Test allowing requests within limit
for i in range(3): # Test with limit of 5, so 3 should pass
allowed = redis_rate_limit(test_key, 5, 60)
print(f" Request {i+1}: {'β
Allowed' if allowed else 'β Blocked'}")
# Test blocking after limit exceeded
for i in range(3): # These should be blocked
allowed = redis_rate_limit(test_key, 5, 60)
print(f" Request {i+4}: {'β
Allowed' if allowed else 'β Blocked'}")
print("β
Rate limiting test completed")
return True
except Exception as e:
print(f"β Rate limiting test failed: {e}")
return False
def test_session_management():
"""Test Redis-based session management."""
print("\nπ Testing Session Management...")
try:
from utils.session_manager import create_user_session, get_user_session, validate_user_session, delete_user_session
# Create test session
user_id = "test_user_123"
user_data = {"email": "test@example.com", "name": "Test User"}
device_info = {"browser": "Chrome", "os": "Linux"}
ip_address = "127.0.0.1"
session_id = create_user_session(user_id, user_data, device_info, ip_address)
if session_id:
print(f"β
Session created: {session_id}")
# Get session
session_data = get_user_session(session_id)
if session_data:
print("β
Session retrieved successfully")
print(f" User ID: {session_data.get('user_id')}")
print(f" Created: {session_data.get('created_at')}")
# Validate session
valid = validate_user_session(session_id, user_id)
print(f"β
Session validation: {'Valid' if valid else 'Invalid'}")
# Delete session
deleted = delete_user_session(session_id)
print(f"β
Session deletion: {'Success' if deleted else 'Failed'}")
return True
else:
print("β Failed to retrieve session")
return False
else:
print("β Failed to create session")
return False
except Exception as e:
print(f"β Session management test failed: {e}")
return False
def test_response_caching():
"""Test Redis-based response caching."""
print("\nπΎ Testing Response Caching...")
try:
from utils.redis_utils import redis_cache_response, redis_get_cached_response, redis_clear_response_cache
from fastapi import Request
from unittest.mock import Mock
# Create mock request
mock_request = Mock()
mock_request.method = "GET"
mock_request.url = "http://test.com/api/test"
mock_request.query_params = {}
mock_request.headers = {}
# Test caching
cache_key = "test_response_cache"
test_data = {"status": "success", "data": "test response"}
# Cache response
cached = redis_cache_response(cache_key, test_data, ttl=300)
if cached:
print("β
Response cached successfully")
# Retrieve cached response
retrieved = redis_get_cached_response(cache_key)
if retrieved == test_data:
print("β
Cached response retrieved successfully")
# Clear cache
cleared = redis_clear_response_cache(cache_key)
print(f"β
Cache cleared: {'Success' if cleared else 'Failed'}")
return True
else:
print("β Retrieved data doesn't match cached data")
return False
else:
print("β Failed to cache response")
return False
except Exception as e:
print(f"β Response caching test failed: {e}")
return False
def main():
"""Run all tests."""
print("π§ͺ Starting Redis Implementation Tests")
print("=" * 50)
# Change to the correct directory
os.chdir(os.path.dirname(__file__))
# Load environment variables
from dotenv import load_dotenv
load_dotenv()
tests = [
("Redis Connection", test_redis_connection),
("Rate Limiting", test_rate_limiting),
("Session Management", test_session_management),
("Response Caching", test_response_caching),
]
results = []
for test_name, test_func in tests:
try:
result = test_func()
results.append((test_name, result))
except Exception as e:
print(f"β {test_name} test crashed: {e}")
results.append((test_name, False))
# Summary
print("\n" + "=" * 50)
print("π Test Results Summary:")
passed = 0
total = len(results)
for test_name, result in results:
status = "β
PASSED" if result else "β FAILED"
print(f" {test_name}: {status}")
if result:
passed += 1
print(f"\nπ― Overall: {passed}/{total} tests passed")
if passed == total:
print("π All tests passed! Redis implementation is working correctly.")
return 0
else:
print("β οΈ Some tests failed. Please check the implementation.")
return 1
if __name__ == "__main__":
exit(main())