-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtests.py
More file actions
executable file
·837 lines (707 loc) · 31.4 KB
/
tests.py
File metadata and controls
executable file
·837 lines (707 loc) · 31.4 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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Testing script for XRayVision.
"""
import unittest
import asyncio
from unittest.mock import Mock, patch, MagicMock
import tempfile
import os
import sys
import shutil
import configparser
import sqlite3
# Add the project directory to the path so we can import the modules
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Import the modules we want to test
import xrayvision
class TestXRayVisionDatabase(unittest.TestCase):
"""Test cases for the xrayvision database operations"""
def setUp(self):
"""Set up test fixtures before each test method."""
self.test_dir = tempfile.mkdtemp()
self.db_file = os.path.join(self.test_dir, 'test.db')
# Set the database file path for testing
xrayvision.DB_FILE = self.db_file
def tearDown(self):
"""Tear down test fixtures after each test method."""
# Clean up temporary directory
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_db_init_creates_tables(self):
"""Test that db_init creates all required tables"""
# Initialize the database
xrayvision.db_init()
# Check that all tables were created
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
# Check patients table
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='patients'")
self.assertIsNotNone(cursor.fetchone(), "patients table should exist")
# Check exams table
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='exams'")
self.assertIsNotNone(cursor.fetchone(), "exams table should exist")
# Check ai_reports table
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='ai_reports'")
self.assertIsNotNone(cursor.fetchone(), "ai_reports table should exist")
# Check rad_reports table
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='rad_reports'")
self.assertIsNotNone(cursor.fetchone(), "rad_reports table should exist")
def test_db_init_creates_indexes(self):
"""Test that db_init creates all required indexes"""
# Initialize the database
xrayvision.db_init()
# Check that indexes were created
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
# Get all indexes
cursor.execute("SELECT name FROM sqlite_master WHERE type='index'")
indexes = [row[0] for row in cursor.fetchall()]
# Check for expected indexes
expected_indexes = [
'idx_exams_status',
'idx_exams_region',
'idx_exams_cnp',
'idx_exams_created',
'idx_exams_study',
'idx_ai_reports_created',
'idx_rad_reports_created',
'idx_patients_name'
]
for index in expected_indexes:
self.assertIn(index, indexes, f"Index {index} should exist")
def test_db_add_patient_inserts_new_patient(self):
"""Test that db_add_patient inserts a new patient"""
# Initialize the database
xrayvision.db_init()
# Add a patient
cnp = "1234567890123"
id = "P001"
name = "John Doe"
age = 30
sex = "M"
result = xrayvision.db_add_patient(cnp, id, name, age, sex)
# Check that the operation was successful
self.assertIsNotNone(result, "db_add_patient should return a result")
# Verify the patient was inserted
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("SELECT cnp, id, name, age, sex FROM patients WHERE cnp = ?", (cnp,))
row = cursor.fetchone()
self.assertIsNotNone(row, "Patient should be inserted")
self.assertEqual(row[0], cnp)
self.assertEqual(row[1], id)
self.assertEqual(row[2], name)
self.assertEqual(row[3], age)
self.assertEqual(row[4], sex)
def test_db_add_patient_updates_existing_patient(self):
"""Test that db_add_patient updates an existing patient"""
# Initialize the database
xrayvision.db_init()
# Add a patient first
cnp = "1234567890123"
id = "P001"
name = "John Doe"
age = 30
sex = "M"
xrayvision.db_add_patient(cnp, id, name, age, sex)
# Update the patient with new information
new_id = "P002"
new_name = "Jane Smith"
new_age = 25
new_sex = "F"
result = xrayvision.db_add_patient(cnp, new_id, new_name, new_age, new_sex)
# Check that the operation was successful
self.assertIsNotNone(result, "db_add_patient should return a result")
# Verify the patient was updated
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("SELECT cnp, id, name, age, sex FROM patients WHERE cnp = ?", (cnp,))
row = cursor.fetchone()
self.assertIsNotNone(row, "Patient should exist")
self.assertEqual(row[0], cnp)
self.assertEqual(row[1], new_id)
self.assertEqual(row[2], new_name)
self.assertEqual(row[3], new_age)
self.assertEqual(row[4], new_sex)
def test_db_add_patient_with_valid_sex_values(self):
"""Test that db_add_patient handles valid sex values"""
# Initialize the database
xrayvision.db_init()
# Test each valid sex value
test_cases = [
("1234567890123", "P001", "John Doe", 30, "M"),
("1234567890124", "P002", "Jane Smith", 25, "F"),
("1234567890125", "P003", "Other Patient", 40, "O")
]
for cnp, id, name, age, sex in test_cases:
result = xrayvision.db_add_patient(cnp, id, name, age, sex)
# Check that the operation was successful
self.assertIsNotNone(result, f"db_add_patient should return a result for sex={sex}")
# Verify the patient was inserted
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("SELECT cnp, sex FROM patients WHERE cnp = ?", (cnp,))
row = cursor.fetchone()
self.assertIsNotNone(row, f"Patient should be inserted for sex={sex}")
self.assertEqual(row[0], cnp)
self.assertEqual(row[1], sex)
def test_db_add_exam_inserts_new_exam(self):
"""Test that db_add_exam inserts a new exam"""
# Initialize the database
xrayvision.db_init()
# First add a patient
cnp = "1234567890123"
patient_id = "P001"
patient_name = "John Doe"
patient_age = 30
patient_sex = "M"
xrayvision.db_add_patient(cnp, patient_id, patient_name, patient_age, patient_sex)
# Add an exam
exam_info = {
'uid': '1.2.3.4.5',
'patient': {
'cnp': cnp,
'id': patient_id,
'name': patient_name,
'age': patient_age,
'sex': patient_sex
},
'exam': {
'id': 'E001',
'created': '2025-01-01 10:00:00',
'protocol': 'Chest X-ray',
'region': 'chest',
'type': 'CR',
'study': '1.2.3.4.5.6',
'series': '1.2.3.4.5.6.7'
}
}
# Call db_add_exam without report
xrayvision.db_add_exam(exam_info)
# Verify the exam was inserted
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT uid, cnp, id, created, protocol, region, type, status, study, series
FROM exams WHERE uid = ?
""", (exam_info['uid'],))
row = cursor.fetchone()
self.assertIsNotNone(row, "Exam should be inserted")
self.assertEqual(row[0], exam_info['uid'])
self.assertEqual(row[1], cnp)
self.assertEqual(row[2], exam_info['exam']['id'])
self.assertEqual(row[3], exam_info['exam']['created'])
self.assertEqual(row[4], exam_info['exam']['protocol'])
self.assertEqual(row[5], exam_info['exam']['region'])
self.assertEqual(row[6], exam_info['exam']['type'])
self.assertEqual(row[7], 'queued') # Default status
self.assertEqual(row[8], exam_info['exam']['study'])
self.assertEqual(row[9], exam_info['exam']['series'])
def test_db_add_exam_with_report_inserts_ai_report(self):
"""Test that db_add_exam with report also inserts AI report"""
# Initialize the database
xrayvision.db_init()
# First add a patient
cnp = "1234567890123"
patient_id = "P001"
patient_name = "John Doe"
patient_age = 30
patient_sex = "M"
xrayvision.db_add_patient(cnp, patient_id, patient_name, patient_age, patient_sex)
# Add an exam with report
exam_info = {
'uid': '1.2.3.4.5',
'patient': {
'cnp': cnp,
'id': patient_id,
'name': patient_name,
'age': patient_age,
'sex': patient_sex
},
'exam': {
'id': 'E001',
'created': '2025-01-01 10:00:00',
'protocol': 'Chest X-ray',
'region': 'chest',
'type': 'CR',
'study': '1.2.3.4.5.6',
'series': '1.2.3.4.5.6.7'
}
}
report_text = "No significant findings."
positive = False
confidence = 95
# Call db_add_exam with report
xrayvision.db_add_exam(exam_info, report=report_text, positive=positive, confidence=confidence)
# Verify the exam was inserted
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("SELECT uid FROM exams WHERE uid = ?", (exam_info['uid'],))
row = cursor.fetchone()
self.assertIsNotNone(row, "Exam should be inserted")
# Verify the AI report was inserted
cursor.execute("""
SELECT uid, text, positive, confidence, is_correct, reviewed, model
FROM ai_reports WHERE uid = ?
""", (exam_info['uid'],))
row = cursor.fetchone()
self.assertIsNotNone(row, "AI report should be inserted")
self.assertEqual(row[0], exam_info['uid'])
self.assertEqual(row[1], report_text)
self.assertEqual(row[2], int(positive))
self.assertEqual(row[3], confidence)
self.assertEqual(row[4], -1) # is_correct defaults to -1
self.assertEqual(row[5], 0) # reviewed defaults to 0 (False as integer)
self.assertEqual(row[6], xrayvision.MODEL_NAME) # model from config
def test_db_add_ai_report_inserts_new_report(self):
"""Test that db_add_ai_report inserts a new AI report"""
# Initialize the database
xrayvision.db_init()
# Add a patient and exam first
cnp = "1234567890123"
patient_id = "P001"
patient_name = "John Doe"
patient_age = 30
patient_sex = "M"
xrayvision.db_add_patient(cnp, patient_id, patient_name, patient_age, patient_sex)
exam_info = {
'uid': '1.2.3.4.5',
'patient': {
'cnp': cnp,
'id': patient_id,
'name': patient_name,
'age': patient_age,
'sex': patient_sex
},
'exam': {
'id': 'E001',
'created': '2025-01-01 10:00:00',
'protocol': 'Chest X-ray',
'region': 'chest',
'type': 'CR',
'study': '1.2.3.4.5.6',
'series': '1.2.3.4.5.6.7'
}
}
xrayvision.db_add_exam(exam_info)
# Add an AI report
uid = '1.2.3.4.5'
report_text = "Findings suggest possible pneumonia."
positive = 1 # Using integer instead of boolean
confidence = 85
model = "test-model"
latency = 2.5
is_correct = 1 # Using integer for three-state value
xrayvision.db_add_ai_report(uid, report_text, positive, confidence, model, latency, is_correct)
# Verify the AI report was inserted
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT uid, text, positive, confidence, is_correct, reviewed, model, latency
FROM ai_reports WHERE uid = ?
""", (uid,))
row = cursor.fetchone()
self.assertIsNotNone(row, "AI report should be inserted")
self.assertEqual(row[0], uid)
self.assertEqual(row[1], report_text)
self.assertEqual(row[2], positive)
self.assertEqual(row[3], confidence)
self.assertEqual(row[4], is_correct)
self.assertEqual(row[5], 0) # reviewed defaults to 0
self.assertEqual(row[6], model)
self.assertEqual(row[7], latency)
def test_db_add_rad_report_inserts_new_report(self):
"""Test that db_add_rad_report inserts a new radiologist report"""
# Initialize the database
xrayvision.db_init()
# Add a patient and exam first
cnp = "1234567890123"
patient_id = "P001"
patient_name = "John Doe"
patient_age = 30
patient_sex = "M"
xrayvision.db_add_patient(cnp, patient_id, patient_name, patient_age, patient_sex)
exam_info = {
'uid': '1.2.3.4.5',
'patient': {
'cnp': cnp,
'id': patient_id,
'name': patient_name,
'age': patient_age,
'sex': patient_sex
},
'exam': {
'id': 'E001',
'created': '2025-01-01 10:00:00',
'protocol': 'Chest X-ray',
'region': 'chest',
'type': 'CR',
'study': '1.2.3.4.5.6',
'series': '1.2.3.4.5.6.7'
}
}
xrayvision.db_add_exam(exam_info)
# Add a radiologist report
uid = '1.2.3.4.5'
report_id = "R001"
report_text = "Confirmed pneumonia with consolidation in right lower lobe."
report_text_en = "Pneumonia confirmed with consolidation in the right lower lobe."
positive = 1 # Using integer instead of boolean
severity = 7
summary = "pneumonia"
report_type = "CR"
radiologist = "Dr. Smith"
justification = "Clinical presentation consistent with pneumonia"
model = "test-model"
latency = 5.0
xrayvision.db_add_rad_report(uid, report_id, report_text, positive, severity, summary, report_type, radiologist, justification, model, latency, report_text_en)
# Verify the radiologist report was inserted
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT uid, id, text, text_en, positive, severity, summary, type, radiologist, justification, model, latency
FROM rad_reports WHERE uid = ?
""", (uid,))
row = cursor.fetchone()
self.assertIsNotNone(row, "Radiologist report should be inserted")
self.assertEqual(row[0], uid)
self.assertEqual(row[1], report_id)
self.assertEqual(row[2], report_text)
self.assertEqual(row[3], report_text_en)
self.assertEqual(row[4], positive)
self.assertEqual(row[5], severity)
self.assertEqual(row[6], summary)
self.assertEqual(row[7], report_type)
self.assertEqual(row[8], radiologist)
self.assertEqual(row[9], justification)
self.assertEqual(row[10], model)
self.assertEqual(row[11], latency)
def test_db_add_rad_report_inserts_new_report_without_translation(self):
"""Test that db_add_rad_report inserts a new radiologist report without translation"""
# Initialize the database
xrayvision.db_init()
# Add a patient and exam first
cnp = "1234567890124"
patient_id = "P002"
patient_name = "Jane Smith"
patient_age = 25
patient_sex = "F"
xrayvision.db_add_patient(cnp, patient_id, patient_name, patient_age, patient_sex)
exam_info = {
'uid': '1.2.3.4.6',
'patient': {
'cnp': cnp,
'id': patient_id,
'name': patient_name,
'age': patient_age,
'sex': patient_sex
},
'exam': {
'id': 'E002',
'created': '2025-01-01 11:00:00',
'protocol': 'Chest X-ray',
'region': 'chest',
'type': 'CR',
'study': '1.2.3.4.5.7',
'series': '1.2.3.4.5.6.8'
}
}
xrayvision.db_add_exam(exam_info)
# Add a radiologist report without translation
uid = '1.2.3.4.6'
report_id = "R002"
report_text = "No significant findings."
positive = 0 # Using integer instead of boolean
severity = 0
summary = "normal"
report_type = "CR"
radiologist = "Dr. Johnson"
justification = "Routine screening"
model = "test-model"
latency = 3.0
xrayvision.db_add_rad_report(uid, report_id, report_text, positive, severity, summary, report_type, radiologist, justification, model, latency)
# Verify the radiologist report was inserted
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT uid, id, text, text_en, positive, severity, summary, type, radiologist, justification, model, latency
FROM rad_reports WHERE uid = ?
""", (uid,))
row = cursor.fetchone()
self.assertIsNotNone(row, "Radiologist report should be inserted")
self.assertEqual(row[0], uid)
self.assertEqual(row[1], report_id)
self.assertEqual(row[2], report_text)
self.assertIsNone(row[3], "text_en should be None when not provided")
self.assertEqual(row[4], positive)
self.assertEqual(row[5], severity)
self.assertEqual(row[6], summary)
self.assertEqual(row[7], report_type)
self.assertEqual(row[8], radiologist)
self.assertEqual(row[9], justification)
self.assertEqual(row[10], model)
self.assertEqual(row[11], latency)
def test_db_get_exams_includes_translation(self):
"""Test that db_get_exams includes English translation in results"""
# Initialize the database
xrayvision.db_init()
# Add a patient and exam first
cnp = "1234567890125"
patient_id = "P003"
patient_name = "Bob Johnson"
patient_age = 40
patient_sex = "M"
xrayvision.db_add_patient(cnp, patient_id, patient_name, patient_age, patient_sex)
exam_info = {
'uid': '1.2.3.4.7',
'patient': {
'cnp': cnp,
'id': patient_id,
'name': patient_name,
'age': patient_age,
'sex': patient_sex
},
'exam': {
'id': 'E003',
'created': '2025-01-01 12:00:00',
'protocol': 'Chest X-ray',
'region': 'chest',
'type': 'CR',
'study': '1.2.3.4.5.8',
'series': '1.2.3.4.5.6.9'
}
}
xrayvision.db_add_exam(exam_info)
# Add AI report
xrayvision.db_add_ai_report('1.2.3.4.7', "No significant findings.", 0, 95, "test-model", 2.5, 0, "normal")
# Add radiologist report with translation
xrayvision.db_add_rad_report('1.2.3.4.7', "R003", "Fără semne de patologie.", 0, 0, "normal", "CR", "Dr. Brown", "Screening de rutină", "test-model", 4.0, "No signs of pathology.")
# Get exams
exams, total = xrayvision.db_get_exams(limit=1, uid='1.2.3.4.7')
# Verify the exam includes translation
self.assertEqual(len(exams), 1)
exam = exams[0]
self.assertEqual(exam['report']['rad']['text'], "Fără semne de patologie.")
self.assertEqual(exam['report']['rad']['text_en'], "No signs of pathology.")
def test_db_set_status_updates_exam_status(self):
"""Test that db_set_status updates the status of an exam"""
# Initialize the database
xrayvision.db_init()
# Add a patient and exam first
cnp = "1234567890123"
patient_id = "P001"
patient_name = "John Doe"
patient_age = 30
patient_sex = "M"
xrayvision.db_add_patient(cnp, patient_id, patient_name, patient_age, patient_sex)
exam_info = {
'uid': '1.2.3.4.5',
'patient': {
'cnp': cnp,
'id': patient_id,
'name': patient_name,
'age': patient_age,
'sex': patient_sex
},
'exam': {
'id': 'E001',
'created': '2025-01-01 10:00:00',
'protocol': 'Chest X-ray',
'region': 'chest',
'type': 'CR',
'study': '1.2.3.4.5.6',
'series': '1.2.3.4.5.6.7'
}
}
xrayvision.db_add_exam(exam_info)
# Set the status to 'processing'
uid = '1.2.3.4.5'
new_status = 'processing'
result = xrayvision.db_set_status(uid, new_status)
# Check that the function returns the correct status
self.assertEqual(result, new_status)
# Verify the status was updated in the database
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("SELECT status FROM exams WHERE uid = ?", (uid,))
row = cursor.fetchone()
self.assertIsNotNone(row, "Exam should exist")
self.assertEqual(row[0], new_status)
# Change the status to 'done'
final_status = 'done'
result = xrayvision.db_set_status(uid, final_status)
# Check that the function returns the correct status
self.assertEqual(result, final_status)
# Verify the status was updated in the database
with sqlite3.connect(self.db_file) as conn:
cursor = conn.cursor()
cursor.execute("SELECT status FROM exams WHERE uid = ?", (uid,))
row = cursor.fetchone()
self.assertIsNotNone(row, "Exam should exist")
self.assertEqual(row[0], final_status)
class TestXRayVision(unittest.TestCase):
"""Test cases for the xrayvision module"""
def setUp(self):
"""Set up test fixtures before each test method."""
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
"""Tear down test fixtures after each test method."""
# Clean up temporary directory
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_validate_romanian_cnp(self):
"""Test Romanian ID validation function"""
# Test valid Romanian ID (example: male, born 1990-01-01, Bucharest)
result = xrayvision.validate_romanian_cnp("1900101400008")
self.assertTrue(result['valid'])
# Test invalid Romanian ID (wrong length)
result = xrayvision.validate_romanian_cnp("12345")
self.assertFalse(result['valid'])
# Test invalid Romanian ID (non-numeric)
result = xrayvision.validate_romanian_cnp("abcdefghijk")
self.assertFalse(result['valid'])
def test_compute_age_from_cnp(self):
"""Test age computation from Romanian ID"""
# This is a placeholder test - actual implementation would depend on
# the specific format of Romanian IDs
age = xrayvision.compute_age_from_cnp("1234567890123")
self.assertIsInstance(age, int)
def test_contains_any_word(self):
"""Test word matching function"""
# Test matching words
self.assertTrue(xrayvision.contains_any_word("chest xray study", "chest", "abdomen"))
# Test non-matching words
self.assertFalse(xrayvision.contains_any_word("brain mri scan", "chest", "abdomen"))
# Test empty string
self.assertFalse(xrayvision.contains_any_word("", "chest"))
# Test empty word list
self.assertFalse(xrayvision.contains_any_word("chest xray",))
@patch('xrayvision.identify_anatomic_region')
def test_identify_anatomic_region_calls(self, mock_identify):
"""Test that identify_anatomic_region is called with correct parameters"""
mock_identify.return_value = "chest"
info = {"StudyDescription": "Chest X-Ray"}
result = xrayvision.identify_anatomic_region(info)
mock_identify.assert_called_once_with(info)
self.assertEqual(result, "chest")
def test_identify_imaging_projection(self):
"""Test imaging projection identification"""
# Test AP projection
info = {"exam": {"protocol": "Chest A.P."}}
projection = xrayvision.identify_imaging_projection(info)
self.assertEqual(projection, "frontal")
# Test PA projection
info = {"exam": {"protocol": "Chest P.A."}}
projection = xrayvision.identify_imaging_projection(info)
self.assertEqual(projection, "frontal")
# Test lateral projection
info = {"exam": {"protocol": "Chest Lat."}}
projection = xrayvision.identify_imaging_projection(info)
self.assertEqual(projection, "lateral")
# Test unknown projection
info = {"exam": {"protocol": "Unknown"}}
projection = xrayvision.identify_imaging_projection(info)
self.assertEqual(projection, "")
def test_determine_patient_gender_description(self):
"""Test patient gender description determination"""
# Test male
info = {"patient": {"sex": "M"}}
gender = xrayvision.determine_patient_gender_description(info)
self.assertEqual(gender, "boy")
# Test female
info = {"patient": {"sex": "F"}}
gender = xrayvision.determine_patient_gender_description(info)
self.assertEqual(gender, "girl")
# Test unknown
info = {"patient": {"sex": "O"}}
gender = xrayvision.determine_patient_gender_description(info)
self.assertEqual(gender, "child")
# Test missing field
info = {"patient": {}}
gender = xrayvision.determine_patient_gender_description(info)
self.assertEqual(gender, "child")
@patch('xrayvision.db_get_previous_reports')
def test_db_get_previous_reports_called(self, mock_db_get):
"""Test that db_get_previous_reports is called correctly"""
mock_db_get.return_value = []
result = xrayvision.db_get_previous_reports("12345", "chest", 3)
mock_db_get.assert_called_once_with("12345", "chest", 3)
self.assertEqual(result, [])
@patch('xrayvision.send_to_openai')
async def test_translate_report_success(self, mock_send_to_openai):
"""Test that translate_report successfully translates Romanian to English"""
# Mock the AI response
mock_response = {
"choices": [
{
"message": {
"content": '{"translation": "Clear costo-diaphragmatic sinuses, no pleural effusion."}'
}
}
]
}
mock_send_to_openai.return_value = mock_response
# Test translation
romanian_text = "SCD libere, fără lichid pleural."
result = await xrayvision.translate_report(romanian_text)
# Verify the translation
self.assertEqual(result, "Clear costo-diaphragmatic sinuses, no pleural effusion.")
@patch('xrayvision.send_to_openai')
async def test_translate_report_failure(self, mock_send_to_openai):
"""Test that translate_report handles AI failures gracefully"""
# Mock a failed AI response
mock_send_to_openai.return_value = None
# Test translation
romanian_text = "SCD libere, fără lichid pleural."
result = await xrayvision.translate_report(romanian_text)
# Verify the result is None
self.assertIsNone(result)
@patch('xrayvision.send_to_openai')
async def test_translate_report_invalid_json(self, mock_send_to_openai):
"""Test that translate_report handles invalid JSON responses"""
# Mock an invalid JSON response
mock_response = {
"choices": [
{
"message": {
"content": '{"invalid_field": "some text"}'
}
}
]
}
mock_send_to_openai.return_value = mock_response
# Test translation
romanian_text = "SCD libere, fără lichid pleural."
result = await xrayvision.translate_report(romanian_text)
# Verify the result is None
self.assertIsNone(result)
@patch('xrayvision.send_to_openai')
async def test_translate_report_empty_input(self, mock_send_to_openai):
"""Test that translate_report handles empty input"""
# Test with empty string
result = await xrayvision.translate_report("")
# Verify the result is None
self.assertIsNone(result)
# Verify AI was not called
mock_send_to_openai.assert_not_called()
class TestXRayVisionConfig(unittest.TestCase):
"""Test cases for xrayvision configuration"""
def test_default_config_structure(self):
"""Test that DEFAULT_CONFIG has the expected structure"""
# Check that general section exists
self.assertIn('general', xrayvision.DEFAULT_CONFIG)
# Check that dicom section exists
self.assertIn('dicom', xrayvision.DEFAULT_CONFIG)
# Check that required general fields exist
general_config = xrayvision.DEFAULT_CONFIG['general']
self.assertIn('XRAYVISION_DB_PATH', general_config)
self.assertIn('XRAYVISION_BACKUP_DIR', general_config)
# Check that required dicom fields exist
dicom_config = xrayvision.DEFAULT_CONFIG['dicom']
self.assertIn('AE_TITLE', dicom_config)
self.assertIn('AE_PORT', dicom_config)
self.assertIn('REMOTE_AE_TITLE', dicom_config)
self.assertIn('REMOTE_AE_IP', dicom_config)
self.assertIn('REMOTE_AE_PORT', dicom_config)
if __name__ == '__main__':
unittest.main()