File size: 8,848 Bytes
01a7921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ContextFlow Test Suite

Tests all API endpoints and core functionality.
"""

import requests
import json
import time

BASE_URL = "http://localhost:5001/api"

def test_health():
    """Test health endpoint"""
    print("\n=== Testing Health Endpoint ===")
    try:
        response = requests.get(f"{BASE_URL}/health")
        print(f"Status: {response.status_code}")
        print(f"Response: {response.json()}")
        return response.status_code == 200
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_session():
    """Test session management"""
    print("\n=== Testing Session Management ===")
    try:
        response = requests.post(f"{BASE_URL}/session/start", json={
            "user_id": "test_user",
            "topic": "Machine Learning"
        })
        print(f"Status: {response.status_code}")
        data = response.json()
        print(f"Session ID: {data.get('session_id')}")
        print(f"Predictions: {len(data.get('predictions', []))} doubts predicted")
        
        update_response = requests.post(f"{BASE_URL}/session/update", json={
            "user_id": "test_user",
            "behavioral_data": {
                "mouse_hesitation": 0.3,
                "scroll_reversals": 5
            }
        })
        print(f"Update Status: {update_response.status_code}")
        
        return response.status_code == 200
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_gestures():
    """Test gesture management"""
    print("\n=== Testing Gesture Management ===")
    try:
        response = requests.get(f"{BASE_URL}/gesture/list?user_id=test_user")
        print(f"List Status: {response.status_code}")
        data = response.json()
        print(f"Gestures: {data.get('count')} available")
        
        response = requests.post(f"{BASE_URL}/gesture/add", json={
            "user_id": "test_user",
            "name": "Test Gesture",
            "description": "A test gesture"
        })
        print(f"Add Status: {response.status_code}")
        
        response = requests.post(f"{BASE_URL}/gesture/training/start", json={
            "user_id": "test_user",
            "gesture_id": "thinking"
        })
        print(f"Training Start Status: {response.status_code}")
        print(f"Instructions: {response.json().get('instructions')}")
        
        sample_landmarks = [[0.1, 0.2, 0.0]] * 21
        response = requests.post(f"{BASE_URL}/gesture/training/sample", json={
            "user_id": "test_user",
            "landmarks": sample_landmarks
        })
        print(f"Training Sample Status: {response.status_code}")
        
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_doubt_prediction():
    """Test doubt prediction"""
    print("\n=== Testing Doubt Prediction ===")
    try:
        response = requests.post(f"{BASE_URL}/predict/doubts", json={
            "user_id": "test_user",
            "context": {
                "topic": "Neural Networks",
                "progress": 0.5,
                "confusion_signals": 0.7
            }
        })
        print(f"Status: {response.status_code}")
        data = response.json()
        print(f"Predictions: {len(data.get('predictions', []))} doubts")
        for pred in data.get('predictions', [])[:3]:
            print(f"  - {pred.get('doubt')} ({pred.get('confidence')*100:.0f}%)")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_knowledge_graph():
    """Test knowledge graph"""
    print("\n=== Testing Knowledge Graph ===")
    try:
        response = requests.post(f"{BASE_URL}/graph/add", json={
            "user_id": "test_user",
            "doubt": {
                "topic": "Deep Learning",
                "concept": "Backpropagation",
                "content": "How does gradient descent work?"
            }
        })
        print(f"Add Node Status: {response.status_code}")
        
        response = requests.post(f"{BASE_URL}/graph/query", json={
            "user_id": "test_user",
            "query": "gradient descent",
            "top_k": 3
        })
        print(f"Query Status: {response.status_code}")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_recall():
    """Test spaced repetition recall"""
    print("\n=== Testing Spaced Repetition ===")
    try:
        response = requests.get(f"{BASE_URL}/review/due?user_id=test_user")
        print(f"Due Reviews Status: {response.status_code}")
        data = response.json()
        print(f"Due Count: {data.get('due_count')}")
        
        if data.get('cards'):
            card = data['cards'][0]
            response = requests.post(f"{BASE_URL}/review/complete", json={
                "user_id": "test_user",
                "card_id": card['card_id'],
                "quality": 4
            })
            print(f"Complete Review Status: {response.status_code}")
            print(f"XP Earned: {response.json().get('xp_earned')}")
        
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_peer_learning():
    """Test peer learning network"""
    print("\n=== Testing Peer Learning ===")
    try:
        response = requests.get(f"{BASE_URL}/peer/insights?topic=ML")
        print(f"Peer Insights Status: {response.status_code}")
        data = response.json()
        print(f"Insights: {len(data.get('insights', []))}")
        
        response = requests.get(f"{BASE_URL}/peer/doubts?topic=ML&limit=5")
        print(f"Peer Doubts Status: {response.status_code}")
        
        response = requests.get(f"{BASE_URL}/peer/trending")
        print(f"Trending Status: {response.status_code}")
        print(f"Trending: {response.json().get('trending', [])[:3]}")
        
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_llm_flow():
    """Test LLM Flow (browser launch simulation)"""
    print("\n=== Testing LLM Flow ===")
    try:
        response = requests.get(f"{BASE_URL}/llm/gesture-actions?user_id=test_user")
        print(f"Gesture Actions Status: {response.status_code}")
        data = response.json()
        print(f"Available Actions: {len(data.get('actions', []))}")
        for action in data.get('actions', [])[:5]:
            print(f"  - {action.get('action')}: {action.get('gesture')}")
        
        response = requests.post(f"{BASE_URL}/llm/rl/start", json={
            "user_id": "test_user",
            "context": {"topic": "Learning"}
        })
        print(f"RL Loop Start Status: {response.status_code}")
        
        response = requests.get(f"{BASE_URL}/llm/rl/status?user_id=test_user")
        print(f"RL Status: {response.json()}")
        
        response = requests.post(f"{BASE_URL}/llm/rl/feedback", json={
            "user_id": "test_user",
            "quality": 4,
            "comment": "Great explanation!"
        })
        print(f"RL Feedback Status: {response.status_code}")
        
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

def run_all_tests():
    """Run all tests"""
    print("=" * 50)
    print("ContextFlow Test Suite")
    print("=" * 50)
    
    tests = [
        ("Health Check", test_health),
        ("Session Management", test_session),
        ("Gesture Management", test_gestures),
        ("Doubt Prediction", test_doubt_prediction),
        ("Knowledge Graph", test_knowledge_graph),
        ("Spaced Repetition", test_recall),
        ("Peer Learning", test_peer_learning),
        ("LLM Flow", test_llm_flow),
    ]
    
    results = []
    for name, test_func in tests:
        try:
            result = test_func()
            results.append((name, result))
            status = "PASS" if result else "FAIL"
            print(f"\n{'='*40}")
            print(f"Result: {status}")
        except Exception as e:
            print(f"\nException: {e}")
            results.append((name, False))
    
    print("\n" + "=" * 50)
    print("SUMMARY")
    print("=" * 50)
    
    passed = sum(1 for _, r in results if r)
    total = len(results)
    
    for name, result in results:
        status = "PASS ✓" if result else "FAIL ✗"
        print(f"{status}: {name}")
    
    print(f"\nTotal: {passed}/{total} passed")
    
    return passed == total

if __name__ == "__main__":
    import sys
    
    print("Starting ContextFlow Test Suite...")
    print("Make sure the backend server is running on http://localhost:5001")
    print("Press Ctrl+C to cancel, or Enter to continue...")
    
    try:
        input()
    except:
        pass
    
    success = run_all_tests()
    sys.exit(0 if success else 1)