File size: 5,018 Bytes
5fde056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import os
import sys
import uuid
from datetime import date

# Base URL for the FastAPI server
BASE_URL = "http://localhost:8000"

# Path to the test image
IMAGE_PATH = "test_face.jpg"

def download_test_image():
    if not os.path.exists(IMAGE_PATH):
        print(f"Downloading test image to {IMAGE_PATH}...")
        url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/lena.jpg"
        response = requests.get(url)
        if response.status_code == 200:
            with open(IMAGE_PATH, 'wb') as f:
                f.write(response.content)
            print("Downloaded successfully.")
        else:
            print("Failed to download test image.")
            sys.exit(1)

def run_tests():
    print("--- VisionAttend Integration Tests ---")
    
    # Generate unique roll number to avoid constraint errors
    roll_number = f"TEST-{uuid.uuid4().hex[:6].upper()}"
    student_name = "Test Student"
    student_id = None
    
    print("\n[1] Testing Registration...")
    try:
        with open(IMAGE_PATH, 'rb') as f:
            files = {'image': (IMAGE_PATH, f, 'image/jpeg')}
            data = {'name': student_name, 'roll_number': roll_number}
            response = requests.post(f"{BASE_URL}/api/register", data=data, files=files)
            
            if response.status_code == 200:
                result = response.json()
                student_id = result.get('student_id')
                print(f"βœ… Registration successful. Student ID: {student_id}")
            else:
                print(f"❌ Registration failed: {response.text}")
                return
    except Exception as e:
        print(f"❌ Registration exception: {e}")
        return

    print("\n[2] Testing Recognition & Attendance Marking...")
    try:
        with open(IMAGE_PATH, 'rb') as f:
            files = {'image': (IMAGE_PATH, f, 'image/jpeg')}
            response = requests.post(f"{BASE_URL}/api/recognize", files=files)
            
            if response.status_code == 200:
                result = response.json()
                print(f"βœ… Recognition successful: {result['message']} - {result['student_name']} ({result['roll_number']})")
                assert result['roll_number'] == roll_number
            else:
                print(f"❌ Recognition failed: {response.text}")
    except Exception as e:
         print(f"❌ Recognition exception: {e}")

    print("\n[3] Testing Attendance Logs Query...")
    try:
        today_str = date.today().strftime("%Y-%m-%d")
        response = requests.get(f"{BASE_URL}/api/attendance?date_filter={today_str}")
        if response.status_code == 200:
            logs = response.json().get('logs', [])
            found = False
            for log in logs:
                if log.get('student_id') == str(student_id):
                    found = True
                    print(f"βœ… Found student in logs. Status: {log.get('status')}")
                    assert log.get('status') == 'Present'
                    break
            if not found:
                print("❌ Student not found in attendance logs.")
        else:
           print(f"❌ Attendance query failed: {response.text}")
    except Exception as e:
         print(f"❌ Attendance query exception: {e}")

    print("\n[4] Testing Manual Attendance Update...")
    try:
        data = {
            "student_id": str(student_id),
            "date": date.today().strftime("%Y-%m-%d"),
            "status": "Absent"
        }
        response = requests.post(f"{BASE_URL}/api/attendance/manual", json=data)
        if response.status_code == 200:
            print("βœ… Manual attendance marked successfully.")
        else:
            print(f"❌ Manual attendance failed: {response.text}")
    except Exception as e:
         print(f"❌ Manual attendance exception: {e}")

    print("\n[5] Testing Student Details Update...")
    try:
        new_name = "Updated Test Student"
        # We'll use the same roll_number as checking existing logic
        data = {
            "name": new_name,
            "roll_number": roll_number
        }
        response = requests.put(f"{BASE_URL}/api/students/{student_id}", json=data)
        if response.status_code == 200:
            print("βœ… Student details updated successfully.")
        else:
            print(f"❌ Student detail update failed: {response.text}")
    except Exception as e:
         print(f"❌ Student detail update exception: {e}")

    print("\n[6] Testing Student Deletion (Cleanup)...")
    if student_id:
        try:
             response = requests.delete(f"{BASE_URL}/api/students/{student_id}")
             if response.status_code == 200:
                  print("βœ… Student deleted successfully.")
             else:
                  print(f"❌ Student deletion failed: {response.text}")
        except Exception as e:
             print(f"❌ Student deletion exception: {e}")


if __name__ == "__main__":
    download_test_image()
    run_tests()