File size: 12,794 Bytes
a8f56ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env python3
"""
Automated API Testing Script for Stock Monitoring API
Tests authentication, endpoints, and security features.

Updated for new API architecture:
- Removed /data/download endpoint (now uses only /data/download-all)
- Removed force_refresh parameter (uses automatic 24h freshness check)
- Updated bulk download strategy testing
"""

import requests
import json
import time
import os
from dotenv import load_dotenv

# Load environment variables from parent directory
load_dotenv(dotenv_path="../.env")
PORT = os.getenv("PORT", "8000")
print(f"Using PORT: {PORT}")


# Configuration
BASE_URL = f"http://localhost:{PORT}"
API_KEY = os.getenv("API_KEY")
INVALID_API_KEY = "invalid_key_for_testing"

# Headers
HEADERS_NO_AUTH = {"Content-Type": "application/json"}
HEADERS_VALID_AUTH = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {API_KEY}"
}
HEADERS_INVALID_AUTH = {
    "Content-Type": "application/json", 
    "Authorization": f"Bearer {INVALID_API_KEY}"
}

def print_test_header(test_name):
    """Print formatted test header."""
    print(f"\n{'='*60}")
    print(f"πŸ§ͺ {test_name}")
    print(f"{'='*60}")

def print_result(endpoint, method, expected_status, actual_status, passed):
    """Print test result."""
    status_icon = "βœ…" if passed else "❌"
    print(f"{status_icon} {method} {endpoint}")
    print(f"   Expected: {expected_status}, Got: {actual_status}")
    if not passed:
        print(f"   ❌ TEST FAILED")
    return passed

def test_health_check():
    """Test the health check endpoint (should be public)."""
    print_test_header("Health Check (Public Endpoint)")
    
    try:
        response = requests.get(f"{BASE_URL}/", headers=HEADERS_NO_AUTH, timeout=10)
        passed = response.status_code == 200
        print_result("/", "GET", 200, response.status_code, passed)
        
        if passed:
            data = response.json()
            print(f"   πŸ“Š Status: {data.get('status')}")
            print(f"   πŸ• Timestamp: {data.get('timestamp')}")
            print(f"   πŸ’Ύ DB Connected: {data.get('database', {}).get('connected')}")
        
        return passed
    except Exception as e:
        print(f"❌ Health check failed: {e}")
        return False

def test_public_endpoints():
    """Test public endpoints that should work without authentication."""
    print_test_header("Public Endpoints (No Auth Required)")
    
    all_passed = True
    
    # Test GET /tickers
    try:
        response = requests.get(f"{BASE_URL}/tickers?limit=5", headers=HEADERS_NO_AUTH, timeout=10)
        passed = response.status_code == 200
        all_passed &= print_result("/tickers", "GET", 200, response.status_code, passed)
        
        if passed:
            data = response.json()
            print(f"   πŸ“ˆ Returned {len(data)} tickers")
    except Exception as e:
        print(f"❌ GET /tickers failed: {e}")
        all_passed = False
    
    return all_passed

def test_protected_endpoints_no_auth():
    """Test protected endpoints without authentication (should fail)."""
    print_test_header("Protected Endpoints - No Auth (Should Fail)")
    
    all_passed = True
    
    protected_endpoints = [
        ("POST", "/tickers/update", {"force_refresh": False}),
        ("POST", "/tickers/update-async", {"force_refresh": False}),
        ("POST", "/data/download-all", None),
        ("GET", "/tasks", None),
        ("DELETE", "/tasks/old", None)
    ]
    
    for method, endpoint, payload in protected_endpoints:
        try:
            if method == "GET":
                response = requests.get(f"{BASE_URL}{endpoint}", headers=HEADERS_NO_AUTH, timeout=10)
            elif method == "POST":
                response = requests.post(f"{BASE_URL}{endpoint}", headers=HEADERS_NO_AUTH, json=payload, timeout=10)
            elif method == "DELETE":
                response = requests.delete(f"{BASE_URL}{endpoint}", headers=HEADERS_NO_AUTH, timeout=10)
            
            # Should return 403 (Forbidden) or 401 (Unauthorized)
            passed = response.status_code in [401, 403]
            all_passed &= print_result(endpoint, method, "401/403", response.status_code, passed)
            
        except Exception as e:
            print(f"❌ {method} {endpoint} failed: {e}")
            all_passed = False
    
    return all_passed

def test_protected_endpoints_invalid_auth():
    """Test protected endpoints with invalid authentication (should fail)."""
    print_test_header("Protected Endpoints - Invalid Auth (Should Fail)")
    
    all_passed = True
    
    protected_endpoints = [
        ("POST", "/tickers/update", {"force_refresh": False}),
        ("POST", "/data/download-all", None),
        ("GET", "/tasks", None),
    ]
    
    for method, endpoint, payload in protected_endpoints:
        try:
            if method == "GET":
                response = requests.get(f"{BASE_URL}{endpoint}", headers=HEADERS_INVALID_AUTH, timeout=10)
            elif method == "POST":
                response = requests.post(f"{BASE_URL}{endpoint}", headers=HEADERS_INVALID_AUTH, json=payload, timeout=10)
            
            # Should return 401 (Unauthorized)
            passed = response.status_code == 401
            all_passed &= print_result(endpoint, method, "401", response.status_code, passed)
            
        except Exception as e:
            print(f"❌ {method} {endpoint} failed: {e}")
            all_passed = False
    
    return all_passed

def test_protected_endpoints_valid_auth():
    """Test protected endpoints with valid authentication (should succeed)."""
    print_test_header("Protected Endpoints - Valid Auth (Should Succeed)")
    
    all_passed = True
    
    # Test GET /tasks
    try:
        response = requests.get(f"{BASE_URL}/tasks", headers=HEADERS_VALID_AUTH, timeout=10)
        passed = response.status_code == 200
        all_passed &= print_result("/tasks", "GET", 200, response.status_code, passed)
        
        if passed:
            data = response.json()
            print(f"   πŸ“‹ Found {len(data)} tasks")
    except Exception as e:
        print(f"❌ GET /tasks failed: {e}")
        all_passed = False
    
    # Test POST /tickers/update-async (safer than sync version)
    try:
        response = requests.post(
            f"{BASE_URL}/tickers/update-async", 
            headers=HEADERS_VALID_AUTH, 
            json={"force_refresh": False},
            timeout=15
        )
        passed = response.status_code == 200
        all_passed &= print_result("/tickers/update-async", "POST", 200, response.status_code, passed)
        
        if passed:
            data = response.json()
            task_id = data.get("task_id")
            print(f"   πŸš€ Task started: {task_id}")
            
            # Test GET /tasks/{task_id}
            if task_id:
                time.sleep(1)  # Give task a moment to start
                response = requests.get(f"{BASE_URL}/tasks/{task_id}", headers=HEADERS_VALID_AUTH, timeout=10)
                passed = response.status_code == 200
                all_passed &= print_result(f"/tasks/{task_id}", "GET", 200, response.status_code, passed)
                
                if passed:
                    task_data = response.json()
                    print(f"   πŸ“Š Task status: {task_data.get('status')}")
                    
    except Exception as e:
        print(f"❌ POST /tickers/update-async failed: {e}")
        all_passed = False
    
    # Test DELETE /tasks/old
    try:
        response = requests.delete(f"{BASE_URL}/tasks/old", headers=HEADERS_VALID_AUTH, timeout=10)
        passed = response.status_code == 200
        all_passed &= print_result("/tasks/old", "DELETE", 200, response.status_code, passed)
        
        if passed:
            data = response.json()
            print(f"   πŸ—‘οΈ  Deleted {data.get('deleted', 0)} old tasks")
    except Exception as e:
        print(f"❌ DELETE /tasks/old failed: {e}")
        all_passed = False
    
    return all_passed

def test_data_endpoints():
    """Test data download and query endpoints."""
    print_test_header("Data Endpoints - Valid Auth (Should Succeed)")
    
    all_passed = True
    
    # Test POST /data/download-all (bulk download with automatic freshness check)
    # Note: This endpoint now automatically checks if data is <24h old and skips update if fresh
    # First run will download all data, subsequent runs may return "data is fresh" message
    try:
        response = requests.post(
            f"{BASE_URL}/data/download-all", 
            headers=HEADERS_VALID_AUTH, 
            timeout=90  # Bulk download might take longer, especially first time
        )
        passed = response.status_code == 200
        all_passed &= print_result("/data/download-all", "POST", 200, response.status_code, passed)
        
        if passed:
            data = response.json()
            print(f"   πŸ“Š Processed {data.get('tickers_processed', 0)} tickers")
            print(f"   πŸ“ˆ Created {data.get('records_created', 0)} records")
            print(f"   πŸ”„ Updated {data.get('records_updated', 0)} records")
            print(f"   πŸ“… Date range: {data.get('date_range', {}).get('start_date')} to {data.get('date_range', {}).get('end_date')}")
            print(f"   πŸ’¬ Message: {data.get('message', 'N/A')}")
    except Exception as e:
        print(f"❌ POST /data/download-all failed: {e}")
        all_passed = False
    
    # Test GET /data/tickers/{ticker} (public endpoint)
    try:
        response = requests.get(f"{BASE_URL}/data/tickers/AAPL?days=5", headers=HEADERS_NO_AUTH, timeout=10)
        passed = response.status_code == 200
        all_passed &= print_result("/data/tickers/AAPL", "GET", 200, response.status_code, passed)
        
        if passed:
            data = response.json()
            print(f"   πŸ“Š Retrieved {len(data)} days of AAPL data")
            if data:
                latest = data[0]
                print(f"   πŸ’° Latest close: ${latest.get('close', 0):.2f}")
    except Exception as e:
        print(f"❌ GET /data/tickers/AAPL failed: {e}")
        all_passed = False
    
    return all_passed

def test_sql_injection_safety():
    """Test that SQL injection attempts are safely handled."""
    print_test_header("SQL Injection Safety Tests")
    
    all_passed = True
    
    # Test various SQL injection attempts in query parameters
    injection_attempts = [
        "'; DROP TABLE tickers; --",
        "' OR '1'='1",
        "1' UNION SELECT * FROM tasks --",
        "'; DELETE FROM tasks; --"
    ]
    
    for injection in injection_attempts:
        try:
            # Test in ticker endpoint (should be safely parameterized)
            response = requests.get(
                f"{BASE_URL}/tickers", 
                params={"limit": injection},
                headers=HEADERS_NO_AUTH,
                timeout=10
            )
            
            # Should either return 422 (validation error) or 200 with safe handling
            passed = response.status_code in [200, 422]
            print_result(f"/tickers?limit={injection[:20]}...", "GET", "200/422", response.status_code, passed)
            all_passed &= passed
            
        except Exception as e:
            print(f"❌ SQL injection test failed: {e}")
            all_passed = False
    
    print("   πŸ›‘οΈ  SQL injection tests completed")
    return all_passed

def main():
    """Run all tests."""
    print("πŸ§ͺ Starting Stock Monitoring API Tests")
    print(f"πŸ”— Base URL: {BASE_URL}")
    print(f"πŸ”‘ API Key: {API_KEY[:10]}...")
    
    all_tests_passed = True
    
    # Run test suites
    all_tests_passed &= test_health_check()
    all_tests_passed &= test_public_endpoints()
    all_tests_passed &= test_protected_endpoints_no_auth()
    all_tests_passed &= test_protected_endpoints_invalid_auth()
    all_tests_passed &= test_protected_endpoints_valid_auth()
    all_tests_passed &= test_data_endpoints()
    all_tests_passed &= test_sql_injection_safety()
    
    # Final results
    print(f"\n{'='*60}")
    if all_tests_passed:
        print("πŸŽ‰ ALL TESTS PASSED! βœ…")
        print("βœ… API Key authentication is working")
        print("βœ… Protected endpoints are secure")
        print("βœ… SQL injection protection is active")
        print("βœ… Public endpoints are accessible")
        print("βœ… Bulk data download with freshness check is working")
        print("βœ… New optimized API architecture is functional")
    else:
        print("❌ SOME TESTS FAILED!")
        print("⚠️  Please check the API implementation")
    print(f"{'='*60}")
    
    return 0 if all_tests_passed else 1

if __name__ == "__main__":
    exit(main())