-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_upload_simple.py
More file actions
206 lines (173 loc) Β· 6.95 KB
/
test_upload_simple.py
File metadata and controls
206 lines (173 loc) Β· 6.95 KB
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
"""
Simple TF4M Upload Test
A focused test script that demonstrates the upload workflow step by step.
"""
import os
import sys
import json
import tempfile
from datetime import datetime
# Add the project root to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from core.api_client import TF4MAPIClient
from core.models import PatientData, FileData, DataType
def create_test_patient() -> PatientData:
"""Create a test patient with mock files."""
print("π Creating test patient data...")
# Create temporary directory
temp_dir = tempfile.mkdtemp(prefix="tf4m_test_")
# Create mock files
def create_mock_file(filename: str, content: str = "Mock content") -> str:
file_path = os.path.join(temp_dir, filename)
with open(file_path, 'w') as f:
f.write(content + f" - Created at {datetime.now()}")
return file_path
# Create patient
patient = PatientData(
patient_id="TEST_PATIENT_001",
folder_path=temp_dir
)
# Add files
patient.ios_upper = FileData(
path=create_mock_file("upper.stl"),
data_type=DataType.IOS_UPPER
)
patient.ios_lower = FileData(
path=create_mock_file("lower.stl"),
data_type=DataType.IOS_LOWER
)
patient.teleradiography = FileData(
path=create_mock_file("teleradiography.jpg"),
data_type=DataType.TELERADIOGRAPHY
)
print(f" β
Created patient '{patient.patient_id}' with {len(patient.get_all_files())} files")
print(f" π Files: {[f.filename for f in patient.get_all_files()]}")
return patient
def test_upload_workflow():
"""Test the complete upload workflow."""
print("π§ͺ TF4M Upload Workflow Test")
print("=" * 40)
# Load settings
print("\n1οΈβ£ Loading settings...")
settings = {}
if os.path.exists("settings.json"):
try:
with open("settings.json", 'r') as f:
settings = json.load(f)
print(" β
Settings loaded from settings.json")
except Exception as e:
print(f" β οΈ Failed to load settings: {e}")
else:
print(" β οΈ No settings.json found, using defaults")
# Initialize API client
print("\n2οΈβ£ Initializing API client...")
base_url = settings.get("api_url", "https://toothfairy4m.ing.unimore.it")
username = settings.get("username", "")
password = settings.get("password", "")
api_client = TF4MAPIClient(base_url, username, password)
print(f" π Base URL: {base_url}")
print(f" π€ Username: {username if username else 'Not set'}")
print(f" π Password: {'Set' if password else 'Not set'}")
# Test connection
print("\n3οΈβ£ Testing connection...")
if username and password:
success, message = api_client.test_connection()
if success:
print(f" β
Connection successful: {message}")
else:
print(f" β Connection failed: {message}")
print(" β οΈ Upload test will continue but may fail")
else:
print(" β οΈ No credentials provided, skipping connection test")
# Create test patient
print("\n4οΈβ£ Creating test patient...")
patient = create_test_patient()
# Test upload
print("\n5οΈβ£ Testing upload...")
def progress_callback(current: int, total: int, message: str):
percentage = (current / total * 100) if total > 0 else 0
print(f" π Progress: {current}/{total} ({percentage:.1f}%) - {message}")
try:
print(" π Starting upload...")
success, message = api_client.upload_patient_data(
patient,
progress_callback=progress_callback
)
if success:
print(f" β
Upload successful: {message}")
else:
print(f" β Upload failed: {message}")
except Exception as e:
print(f" π₯ Upload error: {str(e)}")
import traceback
print(f" π Traceback:")
traceback.print_exc()
# Test patient lookup
print("\n6οΈβ£ Testing patient lookup...")
try:
found, patient_info, lookup_message = api_client.find_patient_by_name(patient.patient_id)
if found:
print(f" β
Patient found: {patient_info}")
else:
print(f" β Patient not found: {lookup_message}")
except Exception as e:
print(f" π₯ Lookup error: {str(e)}")
# Test getting all patients
print("\n7οΈβ£ Testing patient list...")
try:
success, patients, list_message = api_client.get_patients()
if success:
print(f" β
Retrieved {len(patients)} patients from server")
for patient_info in patients[:3]: # Show first 3
print(f" β’ {patient_info.get('name', 'Unknown')} (ID: {patient_info.get('patient_id', 'Unknown')})")
if len(patients) > 3:
print(f" ... and {len(patients) - 3} more")
else:
print(f" β Failed to get patient list: {list_message}")
except Exception as e:
print(f" π₯ Patient list error: {str(e)}")
print("\nπ― Upload workflow test completed!")
print("\nπ Next steps:")
print(" 1. Check the TF4M server to verify the patient was created")
print(" 2. Verify that files were uploaded correctly")
print(" 3. Test with different patient configurations")
def show_upload_request_example():
"""Show what an actual upload request looks like."""
print("\nπ‘ Example Upload Request Structure")
print("=" * 40)
example_request = {
"method": "POST",
"url": "https://toothfairy4m.ing.unimore.it/upload/",
"headers": {
"Content-Type": "multipart/form-data",
"Cookie": "csrftoken=...; sessionid=..."
},
"form_data": {
"name": "TEST_PATIENT_001",
"visibility": "private",
"csrfmiddlewaretoken": "csrf_token_value"
},
"files": {
"upper_scan_raw": "upper.stl (binary data)",
"lower_scan_raw": "lower.stl (binary data)",
"cbct": "cbct_scan.dcm (binary data)",
"cbct_upload_type": "file"
}
}
print("Request structure:")
import json
print(json.dumps(example_request, indent=2))
print("\nπ Upload Process Flow:")
print("1. Login to TF4M with credentials")
print("2. Get CSRF token from login page")
print("3. Check if patient exists on server")
print("4. If patient exists:")
print(" - Get existing files and compare hashes")
print(" - Upload only new/changed files")
print("5. If patient doesn't exist:")
print(" - Create new patient with initial files")
print(" - Upload remaining files")
print("6. Update local cache with upload status")
if __name__ == "__main__":
test_upload_workflow()
show_upload_request_example()