File size: 5,556 Bytes
af9984a
0035111
af9984a
0035111
af9984a
 
0035111
 
 
 
 
 
af9984a
0035111
 
af9984a
 
 
0035111
 
 
 
af9984a
 
0035111
af9984a
 
0035111
af9984a
 
 
0035111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af9984a
0035111
 
 
 
 
af9984a
0035111
af9984a
 
0035111
 
 
 
 
 
 
 
 
 
 
af9984a
0035111
 
af9984a
 
0035111
 
af9984a
 
0035111
af9984a
0035111
 
af9984a
0035111
 
af9984a
 
0035111
af9984a
0035111
af9984a
0035111
 
af9984a
0035111
 
 
af9984a
 
 
 
0035111
 
af9984a
 
 
 
0035111
af9984a
 
 
 
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
import time
import json
import os
from playwright.sync_api import sync_playwright

# Configuration
BASE_URL = "http://localhost:8080"
# Use specific credentials provided by the user
TEST_EMAIL = "kaifulimaan@gmail.com"
TEST_PASSWORD = "Kk123456,"
REAL_IMAGE_PATH = r"D:\Projects\CytoSight\cytosight\test_sampe.png"
EVIDENCE_DIR = "test_evidence"

if not os.path.exists(EVIDENCE_DIR):
    os.makedirs(EVIDENCE_DIR)


def run_test():
    if not os.path.exists(REAL_IMAGE_PATH):
        print(f"❌ ERROR: Real image not found at {REAL_IMAGE_PATH}")
        return

    with sync_playwright() as p:
        print("\n" + "="*50)
        print("πŸš€ STARTING CYTOSIGHT EVIDENCE-BASED PERFORMANCE TEST")
        print("="*50 + "\n")
        
        browser = p.chromium.launch(headless=False, slow_mo=500)
        context = browser.new_context()
        page = context.new_page()

        # Storage for performance metrics
        request_start_times = {}

        def handle_request(request):
            if "/api/" in request.url:
                request_start_times[request.url] = time.time()

        def handle_response(response):
            url = response.url
            if "/api/" in url and response.status in [200, 201]:
                try:
                    # Calculate duration
                    start_time = request_start_times.get(url)
                    duration = round(time.time() - start_time, 2) if start_time else None
                    
                    # Capture JSON data
                    data = response.json()
                    
                    # Add Performance Metadata
                    data["_performance_metrics"] = {
                        "total_response_time_seconds": duration,
                        "captured_at": time.strftime("%Y-%m-%d %H:%M:%S")
                    }

                    # Determine specific category for naming
                    category = "API_RESPONSE"
                    if "auth/login" in url:
                        category = "LOGIN"
                    elif "diagnosis/history" in url:
                        category = "HISTORY_LOAD"
                    elif "upload" in url:
                        category = "IMAGE_UPLOAD"
                    elif "diagnosis/predict" in url:
                        category = "DIAGNOSIS_MODEL"
                    elif "segmentation/predict" in url:
                        category = "SEGMENTATION_MODEL"
                    elif "explain" in url:
                        category = "EXPLAINABLE_AI"

                    filename = f"{EVIDENCE_DIR}/{category}_{int(time.time())}.json"
                    with open(filename, "w") as f:
                        json.dump(data, f, indent=4)
                    
                    print(f"   πŸ“₯ Captured {category} Response ({duration}s): {filename}")
                except Exception:
                    pass

        page.on("request", handle_request)
        page.on("response", handle_response)

        try:
            # --- 1. LOGIN ---
            print(f"πŸ” STEP 1: Logging in as {TEST_EMAIL}...")
            page.goto(f"{BASE_URL}/login")
            
            page.fill('input[name="email"]', TEST_EMAIL)
            page.fill('input[name="password"]', TEST_PASSWORD)
            
            page.click('button[type="submit"]')
            
            # Wait for dashboard to load
            page.wait_for_selector('text=Welcome back', timeout=30000)
            print("   βœ… Login Successful!\n")

            # --- 2. HISTORY ---
            print("πŸ“œ STEP 2: Loading History Page...")
            page.click('text=View Past Diagnosis') # Navigate from dashboard
            page.wait_for_selector('text=Diagnosis History', timeout=30000)
            # Give it a second to fetch history
            time.sleep(2) 
            print("   βœ… History Loaded.\n")

            # --- 3. UPLOAD & DIAGNOSIS ---
            print("πŸ“€ STEP 3: Running Diagnosis...")
            page.goto(f"{BASE_URL}/upload")
            
            page.set_input_files('input[type="file"]', REAL_IMAGE_PATH)
            print(f"   βœ… Image Selected: {REAL_IMAGE_PATH}")
            
            page.click('button:has-text("Disease Diagnosis")')
            print("   ⏳ Processing Diagnosis...")
            
            page.wait_for_selector('text=Diagnosis Completed', timeout=120000)
            print("   βœ… Diagnosis Completed.\n")

            # --- 4. UPLOAD & SEGMENTATION ---
            print("πŸ“€ STEP 4: Running Segmentation...")
            page.goto(f"{BASE_URL}/upload")
            
            page.set_input_files('input[type="file"]', REAL_IMAGE_PATH)
            page.click('button:has-text("Binary Segmentation")')
            print("   ⏳ Processing Segmentation...")
            
            page.wait_for_selector('text=Segmentation Results', timeout=120000)
            print("   βœ… Segmentation Completed.\n")

            print("*"*50)
            print("πŸŽ‰ ALL TESTS PASSED. PERFORMANCE DATA SAVED.")
            print(f"πŸ“ Evidence available in: {os.path.abspath(EVIDENCE_DIR)}")
            print("*"*50 + "\n")
            
        except Exception as e:
            print(f"\n❌ TEST FAILED: {str(e)}")
            # Optional: capture error screenshot if it failed
            # page.screenshot(path=f"{EVIDENCE_DIR}/ERROR_STATE.png")
            raise e
            
        finally:
            print("🧹 Cleaning up...")
            time.sleep(2)
            browser.close()

if __name__ == "__main__":
    run_test()