File size: 7,440 Bytes
7466735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Test script for the AI model and payment integration

"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from ai_model.parking_slot_classifier import ParkingSlotClassifier, generate_training_data
from backend.payment_service import PaymentService, PaymentSimulator
import json


def test_ai_model():
    """Test the parking slot classifier"""
    print("=" * 50)
    print("Testing AI Model")
    print("=" * 50)
    
    # Initialize classifier
    classifier = ParkingSlotClassifier()
    
    # Generate and train with synthetic data
    print("\n1. Generating training data...")
    training_data, labels = generate_training_data(100)
    print(f"   Generated {len(training_data)} training samples")
    
    print("\n2. Training model...")
    classifier.train(training_data, labels)
    print("   Model trained successfully")
    
    # Test prediction
    print("\n3. Testing predictions...")
    test_slots = [
        {
            'slot_id': 'A1',
            'latitude': 28.6139,
            'longitude': 77.2090,
            'avg_feedback': 4.5,
            'popularity_score': 0.8,
            'is_available': True,
            'price_factor': 0.7,
            'price_per_hour': 50.0
        },
        {
            'slot_id': 'B2',
            'latitude': 28.6150,
            'longitude': 77.2100,
            'avg_feedback': 3.2,
            'popularity_score': 0.4,
            'is_available': True,
            'price_factor': 0.5,
            'price_per_hour': 40.0
        },
        {
            'slot_id': 'C3',
            'latitude': 28.6145,
            'longitude': 77.2095,
            'avg_feedback': 4.8,
            'popularity_score': 0.9,
            'is_available': True,
            'price_factor': 0.9,
            'price_per_hour': 60.0
        }
    ]
    
    user_location = (28.6139, 77.2090)
    best_slots = classifier.predict_best_slots(test_slots, user_location, top_k=3)
    
    print("\n   Top 3 Recommended Slots:")
    for i, slot in enumerate(best_slots, 1):
        print(f"   {i}. {slot['slot_id']} - Score: {slot['recommendation_score']:.3f}")
        print(f"      Proximity: {slot['proximity_score']:.3f}, Rating: {slot['avg_feedback']}")
    
    print("\nโœ… AI Model Test Passed!")
    return classifier


def test_payment_service():
    """Test the payment service"""
    print("\n" + "=" * 50)
    print("Testing Payment Service")
    print("=" * 50)
    
    # Use simulator (doesn't require actual Razorpay connection)
    print("\n1. Testing Payment Simulator...")
    simulator = PaymentSimulator()
    
    # Simulate payment
    order_id = "order_test_123"
    amount = 100.0
    
    payment_result = simulator.simulate_payment(order_id, amount)
    print(f"   Payment ID: {payment_result['payment_id']}")
    print(f"   Amount: โ‚น{payment_result['amount']}")
    print(f"   Status: {payment_result['status']}")
    
    # Retrieve simulated payment
    payment_details = simulator.get_simulated_payment(payment_result['payment_id'])
    print(f"\n   Retrieved Payment: {json.dumps(payment_details, indent=2)}")
    
    print("\nโœ… Payment Service Test Passed!")
    
    # Try real Razorpay (will fail gracefully if credentials are invalid)
    print("\n2. Testing Real Razorpay Connection...")
    try:
        payment_service = PaymentService(
            "rzp_test_RYlqJbc24Sl6jz",
            "bghQe0L7iort9vmqb6Jlf8Ec"
        )
        print("   โœ… Razorpay client initialized")
        
        # Try creating an order
        order = payment_service.create_payment_order(
            amount=50.0,
            booking_id="TEST_123",
            notes={'test': 'true'}
        )
        
        if order['success']:
            print(f"   โœ… Order created: {order['order_id']}")
        else:
            print(f"   โš ๏ธ  Order creation failed: {order.get('error')}")
            
    except Exception as e:
        print(f"   โš ๏ธ  Razorpay connection failed: {e}")
        print("   (This is expected if credentials are invalid)")


def test_integration():
    """Test integration between AI model and payment"""
    print("\n" + "=" * 50)
    print("Testing Full Integration")
    print("=" * 50)
    
    print("\n1. User searches for parking...")
    user_location = (28.6139, 77.2090)
    print(f"   User location: {user_location}")
    
    print("\n2. AI recommends best slots...")
    classifier = ParkingSlotClassifier()
    
    # Quick train with small dataset
    training_data, labels = generate_training_data(50)
    classifier.train(training_data, labels)
    
    # Sample available slots
    available_slots = [
        {
            'slot_id': 'P101',
            'latitude': 28.6145,
            'longitude': 77.2095,
            'avg_feedback': 4.2,
            'popularity_score': 0.7,
            'is_available': True,
            'price_factor': 0.6,
            'price_per_hour': 45.0
        },
        {
            'slot_id': 'P102',
            'latitude': 28.6140,
            'longitude': 77.2088,
            'avg_feedback': 4.8,
            'popularity_score': 0.9,
            'is_available': True,
            'price_factor': 0.8,
            'price_per_hour': 55.0
        }
    ]
    
    recommendations = classifier.predict_best_slots(available_slots, user_location, top_k=2)
    
    print("\n   Recommendations:")
    for i, slot in enumerate(recommendations, 1):
        print(f"   {i}. Slot {slot['slot_id']} - Score: {slot['recommendation_score']:.3f}")
    
    print("\n3. User selects a slot...")
    selected_slot = recommendations[0]
    print(f"   Selected: {selected_slot['slot_id']}")
    
    print("\n4. Creating payment order...")
    simulator = PaymentSimulator()
    booking_id = "BKG_TEST_001"
    duration = 2
    amount = selected_slot['price_per_hour'] * duration
    
    payment = simulator.simulate_payment(f"order_{booking_id}", amount)
    print(f"   Payment ID: {payment['payment_id']}")
    print(f"   Amount: โ‚น{amount}")
    
    print("\n5. User provides feedback...")
    feedback = {
        'booking_id': booking_id,
        'slot_id': selected_slot['slot_id'],
        'rating': 5.0,
        'satisfaction': True
    }
    print(f"   Rating: {feedback['rating']}/5")
    print(f"   Satisfied: {feedback['satisfaction']}")
    
    print("\nโœ… Full Integration Test Passed!")


if __name__ == "__main__":
    print("\n๐Ÿš€ Starting Smart Parking System Tests\n")
    
    try:
        # Test AI Model
        classifier = test_ai_model()
        
        # Test Payment Service
        test_payment_service()
        
        # Test Integration
        test_integration()
        
        print("\n" + "=" * 50)
        print("โœ… ALL TESTS PASSED!")
        print("=" * 50)
        print("\n๐Ÿ“ Next Steps:")
        print("1. Set up real parking slot database")
        print("2. Configure Twilio WhatsApp webhook")
        print("3. Deploy backend to Render")
        print("4. Deploy WhatsApp bot to production")
        print("5. Test with real users")
        
    except Exception as e:
        print(f"\nโŒ Test Failed: {e}")
        import traceback
        traceback.print_exc()