Arpit-Bansal commited on
Commit
1f20aac
·
1 Parent(s): 9e6eb68

example test for integration

Browse files
DataService/api.py CHANGED
@@ -2,6 +2,10 @@
2
  FastAPI Service for Metro Train Schedule Generation
3
  Provides endpoints for synthetic data generation and schedule optimization
4
  """
 
 
 
 
5
  from fastapi import FastAPI, HTTPException
6
  from fastapi.responses import JSONResponse
7
  from fastapi.middleware.cors import CORSMiddleware
@@ -9,11 +13,11 @@ from pydantic import ValidationError
9
  from datetime import datetime
10
  import logging
11
 
12
- from .metro_models import (
13
  DaySchedule, ScheduleRequest, Route, TrainHealthStatus
14
  )
15
- from .metro_data_generator import MetroDataGenerator
16
- from .schedule_optimizer import MetroScheduleOptimizer
17
 
18
  # Configure logging
19
  logging.basicConfig(level=logging.INFO)
 
2
  FastAPI Service for Metro Train Schedule Generation
3
  Provides endpoints for synthetic data generation and schedule optimization
4
  """
5
+ import sys
6
+ import os
7
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
+
9
  from fastapi import FastAPI, HTTPException
10
  from fastapi.responses import JSONResponse
11
  from fastapi.middleware.cors import CORSMiddleware
 
13
  from datetime import datetime
14
  import logging
15
 
16
+ from DataService.metro_models import (
17
  DaySchedule, ScheduleRequest, Route, TrainHealthStatus
18
  )
19
+ from DataService.metro_data_generator import MetroDataGenerator
20
+ from DataService.schedule_optimizer import MetroScheduleOptimizer
21
 
22
  # Configure logging
23
  logging.basicConfig(level=logging.INFO)
DataService/metro_data_generator.py CHANGED
@@ -2,11 +2,16 @@
2
  Enhanced Metro Synthetic Data Generator
3
  Generates realistic metro train scheduling data with time-based constraints
4
  """
 
 
 
 
5
  import random
6
  import uuid
7
  from datetime import datetime, timedelta, time
8
  from typing import List, Dict, Tuple
9
- from .metro_models import (
 
10
  TrainHealthStatus, Station, Route, FitnessCertificates,
11
  FitnessCertificate, CertificateStatus, JobCards, Branding
12
  )
 
2
  Enhanced Metro Synthetic Data Generator
3
  Generates realistic metro train scheduling data with time-based constraints
4
  """
5
+ import sys
6
+ import os
7
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
+
9
  import random
10
  import uuid
11
  from datetime import datetime, timedelta, time
12
  from typing import List, Dict, Tuple
13
+
14
+ from DataService.metro_models import (
15
  TrainHealthStatus, Station, Route, FitnessCertificates,
16
  FitnessCertificate, CertificateStatus, JobCards, Branding
17
  )
DataService/schedule_optimizer.py CHANGED
@@ -3,16 +3,21 @@ Metro Train Schedule Optimizer
3
  Generates optimal daily schedules from 5:00 AM to 11:00 PM
4
  Considers train health, maintenance, branding, and mileage balancing
5
  """
 
 
 
 
6
  import random
7
  from datetime import datetime, time, timedelta
8
  from typing import List, Dict, Tuple, Optional
9
- from .metro_models import (
 
10
  DaySchedule, Trainset, TrainStatus, ServiceBlock, FleetSummary,
11
  OptimizationMetrics, Alert, Severity, DecisionRationale,
12
  TrainHealthStatus, Route, OperationalHours, FitnessCertificates,
13
  JobCards, Branding, CertificateStatus, MaintenanceType
14
  )
15
- from .metro_data_generator import MetroDataGenerator
16
 
17
 
18
  class MetroScheduleOptimizer:
 
3
  Generates optimal daily schedules from 5:00 AM to 11:00 PM
4
  Considers train health, maintenance, branding, and mileage balancing
5
  """
6
+ import sys
7
+ import os
8
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
+
10
  import random
11
  from datetime import datetime, time, timedelta
12
  from typing import List, Dict, Tuple, Optional
13
+
14
+ from DataService.metro_models import (
15
  DaySchedule, Trainset, TrainStatus, ServiceBlock, FleetSummary,
16
  OptimizationMetrics, Alert, Severity, DecisionRationale,
17
  TrainHealthStatus, Route, OperationalHours, FitnessCertificates,
18
  JobCards, Branding, CertificateStatus, MaintenanceType
19
  )
20
+ from DataService.metro_data_generator import MetroDataGenerator
21
 
22
 
23
  class MetroScheduleOptimizer:
api_test_results_20251026_153104.json ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt CHANGED
@@ -2,4 +2,5 @@ ortools==9.14.6206
2
  fastapi==0.104.1
3
  uvicorn[standard]==0.24.0
4
  pydantic==2.5.0
5
- python-multipart==0.0.6
 
 
2
  fastapi==0.104.1
3
  uvicorn[standard]==0.24.0
4
  pydantic==2.5.0
5
+ python-multipart==0.0.6
6
+ requests==2.31.0
test_api.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ API Test Suite for DataService
3
+ Tests all endpoints and saves results to JSON
4
+ """
5
+ import requests
6
+ import json
7
+ from datetime import datetime
8
+
9
+
10
+ BASE_URL = "http://localhost:8000"
11
+ results = {
12
+ "test_run": datetime.now().isoformat(),
13
+ "base_url": BASE_URL,
14
+ "tests": []
15
+ }
16
+
17
+
18
+ def test_endpoint(name, method, endpoint, **kwargs):
19
+ """Test an API endpoint and record results"""
20
+ print(f"\nTesting: {name}")
21
+ print(f" {method} {endpoint}")
22
+
23
+ try:
24
+ url = f"{BASE_URL}{endpoint}"
25
+
26
+ if method == "GET":
27
+ response = requests.get(url, **kwargs)
28
+ elif method == "POST":
29
+ response = requests.post(url, **kwargs)
30
+ else:
31
+ raise ValueError(f"Unsupported method: {method}")
32
+
33
+ result = {
34
+ "name": name,
35
+ "method": method,
36
+ "endpoint": endpoint,
37
+ "status_code": response.status_code,
38
+ "success": response.status_code in [200, 201],
39
+ "response_size": len(response.text),
40
+ "timestamp": datetime.now().isoformat()
41
+ }
42
+
43
+ if response.status_code == 200:
44
+ try:
45
+ result["response_data"] = response.json()
46
+ print(f" ✓ Success - {response.status_code}")
47
+ except:
48
+ result["response_text"] = response.text[:200]
49
+ print(f" ✓ Success - {response.status_code} (non-JSON)")
50
+ else:
51
+ result["error"] = response.text[:500]
52
+ print(f" ✗ Failed - {response.status_code}")
53
+
54
+ results["tests"].append(result)
55
+ return result
56
+
57
+ except Exception as e:
58
+ result = {
59
+ "name": name,
60
+ "method": method,
61
+ "endpoint": endpoint,
62
+ "success": False,
63
+ "error": str(e),
64
+ "timestamp": datetime.now().isoformat()
65
+ }
66
+ results["tests"].append(result)
67
+ print(f" ✗ Error: {e}")
68
+ return result
69
+
70
+
71
+ def run_tests():
72
+ """Run all API tests"""
73
+ print("=" * 70)
74
+ print("DataService API Test Suite")
75
+ print("=" * 70)
76
+
77
+ # Test 1: Root endpoint
78
+ test_endpoint(
79
+ "Root Endpoint",
80
+ "GET",
81
+ "/"
82
+ )
83
+
84
+ # Test 2: Health check
85
+ test_endpoint(
86
+ "Health Check",
87
+ "GET",
88
+ "/health"
89
+ )
90
+
91
+ # Test 3: Quick schedule generation
92
+ test_endpoint(
93
+ "Quick Schedule Generation",
94
+ "POST",
95
+ "/api/v1/generate/quick?date=2025-10-26&num_trains=25&num_stations=25"
96
+ )
97
+
98
+ # Test 4: Full schedule generation
99
+ test_endpoint(
100
+ "Full Schedule Generation",
101
+ "POST",
102
+ "/api/v1/generate",
103
+ json={
104
+ "date": "2025-10-26",
105
+ "num_trains": 30,
106
+ "num_stations": 25,
107
+ "min_service_trains": 22,
108
+ "min_standby_trains": 3
109
+ },
110
+ headers={"Content-Type": "application/json"}
111
+ )
112
+
113
+ # Test 5: Example schedule
114
+ test_endpoint(
115
+ "Example Schedule",
116
+ "GET",
117
+ "/api/v1/schedule/example"
118
+ )
119
+
120
+ # Test 6: Route information
121
+ test_endpoint(
122
+ "Route Information (25 stations)",
123
+ "GET",
124
+ "/api/v1/route/25"
125
+ )
126
+
127
+ # Test 7: Train health data
128
+ test_endpoint(
129
+ "Train Health Data (30 trains)",
130
+ "GET",
131
+ "/api/v1/trains/health/30"
132
+ )
133
+
134
+ # Test 8: Depot layout
135
+ test_endpoint(
136
+ "Depot Layout",
137
+ "GET",
138
+ "/api/v1/depot/layout"
139
+ )
140
+
141
+ # Test 9: Custom schedule with all parameters
142
+ test_endpoint(
143
+ "Custom Schedule Full Parameters",
144
+ "POST",
145
+ "/api/v1/generate",
146
+ json={
147
+ "date": "2025-11-01",
148
+ "num_trains": 35,
149
+ "num_stations": 25,
150
+ "route_name": "Aluva-Pettah Line",
151
+ "depot_name": "Muttom_Depot",
152
+ "min_service_trains": 25,
153
+ "min_standby_trains": 5,
154
+ "max_daily_km_per_train": 280,
155
+ "balance_mileage": True,
156
+ "prioritize_branding": True
157
+ },
158
+ headers={"Content-Type": "application/json"}
159
+ )
160
+
161
+ # Test 10: Quick generation with minimal params
162
+ test_endpoint(
163
+ "Quick Generation Minimal",
164
+ "POST",
165
+ "/api/v1/generate/quick?date=2025-10-27&num_trains=20"
166
+ )
167
+
168
+
169
+ def save_results():
170
+ """Save test results to JSON file"""
171
+ # Summary
172
+ total = len(results["tests"])
173
+ passed = sum(1 for t in results["tests"] if t.get("success", False))
174
+
175
+ results["summary"] = {
176
+ "total_tests": total,
177
+ "passed": passed,
178
+ "failed": total - passed,
179
+ "success_rate": f"{(passed/total)*100:.1f}%" if total > 0 else "0%"
180
+ }
181
+
182
+ filename = f"api_test_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
183
+
184
+ with open(filename, 'w') as f:
185
+ json.dump(results, f, indent=2, default=str)
186
+
187
+ print("\n" + "=" * 70)
188
+ print("Test Summary")
189
+ print("=" * 70)
190
+ print(f"Total Tests: {total}")
191
+ print(f"Passed: {passed}")
192
+ print(f"Failed: {total - passed}")
193
+ print(f"Success Rate: {results['summary']['success_rate']}")
194
+ print(f"\nResults saved to: {filename}")
195
+ print("=" * 70)
196
+
197
+
198
+ if __name__ == "__main__":
199
+ try:
200
+ run_tests()
201
+ save_results()
202
+ except KeyboardInterrupt:
203
+ print("\n\nTests interrupted by user")
204
+ save_results()
205
+ except Exception as e:
206
+ print(f"\n\nError during testing: {e}")
207
+ save_results()