File size: 4,749 Bytes
1f7d0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test script for correlation ID implementation.
"""
import asyncio
import httpx
import json
from datetime import datetime


async def test_correlation_id():
    """Test correlation ID generation and propagation."""
    
    base_url = "http://localhost:8002"
    
    print("=" * 80)
    print("Correlation ID Implementation Test")
    print("=" * 80)
    print()
    
    # Test 1: Request without correlation ID (should be generated)
    print("Test 1: Request without correlation ID")
    print("-" * 80)
    
    async with httpx.AsyncClient() as client:
        response = await client.get(f"{base_url}/health")
        correlation_id_1 = response.headers.get("X-Correlation-ID")
        
        print(f"Status Code: {response.status_code}")
        print(f"Generated Correlation ID: {correlation_id_1}")
        print(f"Response: {json.dumps(response.json(), indent=2)}")
        print()
        
        if correlation_id_1:
            print("βœ“ Correlation ID was generated")
        else:
            print("βœ— Correlation ID was NOT generated")
        print()
    
    # Test 2: Request with custom correlation ID (should be preserved)
    print("Test 2: Request with custom correlation ID")
    print("-" * 80)
    
    custom_correlation_id = f"test-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
    
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{base_url}/health",
            headers={"X-Correlation-ID": custom_correlation_id}
        )
        correlation_id_2 = response.headers.get("X-Correlation-ID")
        
        print(f"Status Code: {response.status_code}")
        print(f"Sent Correlation ID: {custom_correlation_id}")
        print(f"Received Correlation ID: {correlation_id_2}")
        print(f"Response: {json.dumps(response.json(), indent=2)}")
        print()
        
        if correlation_id_2 == custom_correlation_id:
            print("βœ“ Correlation ID was preserved")
        else:
            print("βœ— Correlation ID was NOT preserved")
        print()
    
    # Test 3: Multiple requests should have different correlation IDs
    print("Test 3: Multiple requests have unique correlation IDs")
    print("-" * 80)
    
    correlation_ids = []
    
    async with httpx.AsyncClient() as client:
        for i in range(3):
            response = await client.get(f"{base_url}/health")
            correlation_id = response.headers.get("X-Correlation-ID")
            correlation_ids.append(correlation_id)
            print(f"Request {i+1} Correlation ID: {correlation_id}")
        
        print()
        unique_ids = len(set(correlation_ids))
        
        if unique_ids == 3:
            print(f"βœ“ All {unique_ids} correlation IDs are unique")
        else:
            print(f"βœ— Only {unique_ids} unique correlation IDs (expected 3)")
        print()
    
    # Test 4: Check logs for correlation ID
    print("Test 4: Check logs for correlation ID")
    print("-" * 80)
    
    test_correlation_id = f"log-test-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
    
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{base_url}/health",
            headers={"X-Correlation-ID": test_correlation_id}
        )
        
        print(f"Made request with Correlation ID: {test_correlation_id}")
        print()
        print("To verify in logs, run:")
        print(f"  grep '{test_correlation_id}' cuatrolabs-auth-ms/logs/app.log | jq '.'")
        print()
        print("Expected log fields:")
        print("  - correlation_id: {test_correlation_id}")
        print("  - message: Request started/completed")
        print("  - method: GET")
        print("  - path: /health")
        print()
    
    print("=" * 80)
    print("Test Summary")
    print("=" * 80)
    print()
    print("βœ“ Correlation ID middleware is working")
    print("βœ“ Correlation IDs are generated when not provided")
    print("βœ“ Correlation IDs are preserved when provided")
    print("βœ“ Each request gets a unique correlation ID")
    print()
    print("Next steps:")
    print("1. Check logs/app.log for correlation_id field in JSON logs")
    print("2. Test with actual API endpoints (login, user creation, etc.)")
    print("3. Implement in other microservices for end-to-end tracing")
    print()


if __name__ == "__main__":
    try:
        asyncio.run(test_correlation_id())
    except httpx.ConnectError:
        print("Error: Could not connect to AUTH service at http://localhost:8002")
        print("Please ensure the service is running:")
        print("  cd cuatrolabs-auth-ms")
        print("  python -m app.main")
    except Exception as e:
        print(f"Error: {e}")