File size: 7,044 Bytes
82fcb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d54c92
82fcb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d54c92
82fcb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d54c92
82fcb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d54c92
82fcb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d54c92
82fcb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Test script for attendance check-in API.
Generates a JWT token and tests the check-in endpoint.
"""
import requests
import json
from datetime import datetime, timedelta
from jose import jwt
import os
from dotenv import load_dotenv

load_dotenv()

# Configuration
BASE_URL = "http://localhost:8003"
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
ALGORITHM = os.getenv("ALGORITHM", "HS256")


def generate_test_token(
    user_id: str = "550e8400-e29b-41d4-a716-446655440000",
    username: str = "test.employee@example.com",
    merchant_id: str = "660e8400-e29b-41d4-a716-446655440000",
    role: str = "employee"
) -> str:
    """Generate a test JWT token"""
    
    payload = {
        "sub": user_id,
        "username": username,
        "merchant_id": merchant_id,
        "role": role,
        "exp": datetime.utcnow() + timedelta(hours=8)
    }
    
    token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
    return token


def test_health_check():
    """Test health check endpoint"""
    print("\n" + "=" * 80)
    print("TEST 1: Health Check")
    print("=" * 80)
    
    response = requests.get(f"{BASE_URL}/health")
    print(f"Status Code: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    assert response.status_code == 200
    print("βœ… Health check passed")


def test_attendance_health():
    """Test attendance module health check"""
    print("\n" + "=" * 80)
    print("TEST 2: Attendance Module Health Check")
    print("=" * 80)
    
    response = requests.get(f"{BASE_URL}/tracker/attendance/health")
    print(f"Status Code: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    assert response.status_code == 200
    print("βœ… Attendance health check passed")


def test_checkin_without_auth():
    """Test check-in without authentication (should fail)"""
    print("\n" + "=" * 80)
    print("TEST 3: Check-in Without Authentication (Should Fail)")
    print("=" * 80)
    
    payload = {
        "timestamp": int(datetime.now().timestamp() * 1000),
        "latitude": 19.0760,
        "longitude": 72.8777,
        "location_id": "loc_mumbai_office_001"
    }
    
    response = requests.post(
        f"{BASE_URL}/tracker/attendance/check-in",
        json=payload
    )
    
    print(f"Status Code: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    assert response.status_code == 403  # Forbidden without auth
    print("βœ… Correctly rejected unauthenticated request")


def test_checkin_with_auth():
    """Test check-in with authentication"""
    print("\n" + "=" * 80)
    print("TEST 4: Check-in With Authentication")
    print("=" * 80)
    
    # Generate token
    token = generate_test_token()
    print(f"Generated JWT Token: {token[:50]}...")
    
    # Prepare payload
    payload = {
        "timestamp": int(datetime.now().timestamp() * 1000),
        "latitude": 19.0760,
        "longitude": 72.8777,
        "location_id": "loc_mumbai_office_001"
    }
    
    print(f"\nRequest Payload:")
    print(json.dumps(payload, indent=2))
    
    # Make request
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    response = requests.post(
        f"{BASE_URL}/tracker/attendance/check-in",
        json=payload,
        headers=headers
    )
    
    print(f"\nStatus Code: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    if response.status_code == 201:
        print("βœ… Check-in successful")
    elif response.status_code == 400:
        error_detail = response.json().get("detail", {})
        if "Already checked in" in str(error_detail):
            print("⚠️  Already checked in today (expected if running multiple times)")
        elif "GPS" in str(error_detail):
            print("⚠️  GPS tracking disabled for this employee")
            print("   To fix: Update MongoDB scm_employees collection")
            print("   Set location_settings.location_tracking_consent = true")
        else:
            print(f"❌ Check-in failed: {error_detail}")
    else:
        print(f"❌ Unexpected status code: {response.status_code}")


def test_checkin_invalid_coordinates():
    """Test check-in with invalid coordinates"""
    print("\n" + "=" * 80)
    print("TEST 5: Check-in With Invalid Coordinates (Should Fail)")
    print("=" * 80)
    
    token = generate_test_token()
    
    payload = {
        "timestamp": int(datetime.now().timestamp() * 1000),
        "latitude": 999.0,  # Invalid latitude
        "longitude": 72.8777
    }
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    response = requests.post(
        f"{BASE_URL}/tracker/attendance/check-in",
        json=payload,
        headers=headers
    )
    
    print(f"Status Code: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    assert response.status_code == 422  # Validation error
    print("βœ… Correctly rejected invalid coordinates")


def test_checkin_missing_fields():
    """Test check-in with missing required fields"""
    print("\n" + "=" * 80)
    print("TEST 6: Check-in With Missing Fields (Should Fail)")
    print("=" * 80)
    
    token = generate_test_token()
    
    payload = {
        "timestamp": int(datetime.now().timestamp() * 1000),
        # Missing latitude and longitude
    }
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    response = requests.post(
        f"{BASE_URL}/tracker/attendance/check-in",
        json=payload,
        headers=headers
    )
    
    print(f"Status Code: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    assert response.status_code == 422  # Validation error
    print("βœ… Correctly rejected request with missing fields")


def main():
    """Run all tests"""
    print("\n" + "=" * 80)
    print("ATTENDANCE CHECK-IN API TEST SUITE")
    print("=" * 80)
    print(f"Base URL: {BASE_URL}")
    print(f"Time: {datetime.now().isoformat()}")
    print("=" * 80)
    
    try:
        test_health_check()
        test_attendance_health()
        test_checkin_without_auth()
        test_checkin_invalid_coordinates()
        test_checkin_missing_fields()
        test_checkin_with_auth()  # Run this last as it may succeed
        
        print("\n" + "=" * 80)
        print("βœ… ALL TESTS COMPLETED")
        print("=" * 80)
        
    except requests.exceptions.ConnectionError:
        print("\n❌ ERROR: Could not connect to the server")
        print(f"   Make sure the service is running at {BASE_URL}")
        print("   Run: uvicorn app.main:app --host 0.0.0.0 --port 8003")
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        raise


if __name__ == "__main__":
    main()