-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecorder_server.py
More file actions
1903 lines (1567 loc) · 71.7 KB
/
recorder_server.py
File metadata and controls
1903 lines (1567 loc) · 71.7 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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request
from flask_cors import CORS
import os
import json
import re
from ollama import chat
import time
import uuid
from pydantic import BaseModel, Field
from bs4 import BeautifulSoup
from openai import OpenAI
import tiktoken
from deep_translator import GoogleTranslator
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import threading
import webbrowser
import csv
import math
from collections import defaultdict
from itertools import product
from urllib.parse import urlparse
import socket
import sys
def check_port_available(port):
"""Check if a port is available for use"""
try:
# Create a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1) # 1 second timeout
# Try to bind to the port
result = sock.bind(('localhost', port))
sock.close()
return True
except OSError:
return False
# Use cl100k_base encoding (close approximation for Llama)
encoding = tiktoken.get_encoding("cl100k_base")
def count_tokens(text):
return len(encoding.encode(text))
ollama_url = 'http://localhost:11434/v1'
openrouter_url = 'https://openrouter.ai/api/v1'
cerebras_url = "https://api.cerebras.ai/v1"
site = input(
"Do you want to use local or api? (local/api): "
).strip().lower()
if site == 'local':
token = 'ollama'
url = ollama_url
model_name = 'llama3.1'
is_local = True
elif site == 'api':
model = input("Cerebras/OpenRouter: ").strip()
token = input("Enter your API token: ").strip()
if model.lower() == 'openrouter':
url = openrouter_url
model_name = 'meta-llama/llama-3.3-8b-instruct:free'
else:
url = cerebras_url
model_name="llama-3.3-70b"
is_local = False
else:
print("Invalid input. Please enter 'local' or 'api'.")
exit(1)
app = Flask(__name__)
CORS(app)
SAVE_DIR = "snapshots"
# Create a unique run directory inside snapshots for each server run
_run_time = int(time.time())
_run_uid = uuid.uuid4().hex[:8]
RUN_ID = f"run_{_run_time}_{_run_uid}"
RUN_SAVE_DIR = os.path.join(SAVE_DIR, RUN_ID)
os.makedirs(RUN_SAVE_DIR, exist_ok=True)
client = OpenAI(
base_url=url,
api_key=token)
class FormField(BaseModel):
name: str = Field(...,
description="The 'name' attribute of the input or textarea")
id: str = Field(..., description="The 'id' attribute of the element")
type: str = Field(...,
description="Input type (text, password, etc.) or 'textarea'")
limitations: str = Field(
..., description="Validation rules inferred from attributes like minlength, maxlength, pattern, placeholder in English")
examples: list[str] = Field(...,
description="Five example values that satisfy the limitations")
bad_examples: list[str] = Field(...,
description="Five example values that violate the limitations for negative testing")
class ExampleSchema(BaseModel):
examples: list[str] = Field(...,
description="Five example values that satisfy the range")
bad_examples: list[str] = Field(...,
description="Five example values that violate the range for negative testing")
def translate_to_persian(english_text):
"""Translate English limitations to Persian using deep_translator"""
try:
translator = GoogleTranslator(source='en', target='fa')
return translator.translate(english_text)
except Exception as e:
print(f"Translation error: {e}")
return english_text # Return original if translation fails
def translate_to_english(persian_text):
"""Translate Persian text to English using deep_translator"""
try:
translator = GoogleTranslator(source='fa', target='en')
return translator.translate(persian_text)
except Exception as e:
print(f"Translation error: {e}")
return persian_text # Return original if translation fails
@app.route('/snapshot', methods=['POST'])
def snapshot():
data = request.get_json()
print("Received snapshot:", data['eventType'], data['time'])
base = f"{data['eventType']}_{data['time']}"
html_path = os.path.join(RUN_SAVE_DIR, f"{base}.html")
css_path = os.path.join(RUN_SAVE_DIR, f"{base}.css")
event_path = os.path.join(RUN_SAVE_DIR, f"{base}_event.json")
with open(html_path, "w", encoding="utf-8") as f:
f.write(data['html'])
with open(css_path, "w", encoding="utf-8") as f:
f.write(data['css'])
if data['eventType'] == 'pageload':
with open(event_path, "w", encoding="utf-8") as f:
json.dump({"eventType": "pageload",
"time": data['time'],
"url": data['url'], }, f, ensure_ascii=False, indent=2)
elif 'event' in data and data['event'] is not None:
with open(event_path, "w", encoding="utf-8") as f:
json.dump(data['event'], f, ensure_ascii=False, indent=2)
return 'ok'
def preserve_structure(soup, target_element):
"""Preserve parent structure up to target element"""
parents = []
current = target_element.parent
while current and current.name:
parents.append(current)
current = current.parent
return list(reversed(parents))
def truncate_with_context(soup, target_element, max_tokens=100000):
"""Try to keep target element with as much context as possible"""
# Get parent structure
parents = preserve_structure(soup, target_element)
# Start with target element
essential_html = str(target_element)
token_count = count_tokens(essential_html)
if token_count >= max_tokens:
return None # Target element itself is too large
# Add parent structure
for parent in parents:
# Create a copy of parent with minimal content
parent_copy = soup.new_tag(parent.name)
for attr_name, attr_value in parent.attrs.items():
parent_copy[attr_name] = attr_value
# Test if adding this parent keeps us under limit
temp_structure = str(parent_copy).replace(
'></', f'>{essential_html}</')
# Leave room for siblings
if count_tokens(temp_structure) < max_tokens * 0.8:
essential_html = temp_structure
token_count = count_tokens(essential_html)
# Try to add siblings and other content
remaining_tokens = max_tokens - token_count
# Add content before target
before_content = get_content_before(
soup, target_element, remaining_tokens // 2)
# Add content after target
after_content = get_content_after(
soup, target_element, remaining_tokens // 2)
# Combine everything
if before_content or after_content:
# Create new soup with combined content
new_soup = BeautifulSoup(
f"{before_content}{essential_html}{after_content}", 'html.parser')
return str(new_soup)
return essential_html
def get_content_before(soup, target_element, max_tokens):
"""Get content before target element within token limit"""
# Find all elements before target
all_elements = soup.find_all()
target_index = all_elements.index(target_element)
before_elements = all_elements[:target_index]
before_elements.reverse() # Start from closest to target
collected_content = []
current_tokens = 0
for element in before_elements:
element_html = str(element)
element_tokens = count_tokens(element_html)
if current_tokens + element_tokens <= max_tokens:
collected_content.insert(0, element_html) # Insert at beginning
current_tokens += element_tokens
else:
break
return ''.join(collected_content)
def get_content_after(soup, target_element, max_tokens):
"""Get content after target element within token limit"""
# Find all elements after target
all_elements = soup.find_all()
target_index = all_elements.index(target_element)
after_elements = all_elements[target_index + 1:]
collected_content = []
current_tokens = 0
for element in after_elements:
element_html = str(element)
element_tokens = count_tokens(element_html)
if current_tokens + element_tokens <= max_tokens:
collected_content.append(element_html)
current_tokens += element_tokens
else:
break
return ''.join(collected_content)
def is_element_visible(element):
style = element.get('style', '')
if style:
style_lower = style.lower()
# Check for display:none or visibility:hidden
if 'display:none' in style_lower.replace(' ', '') or 'display: none' in style_lower:
return False
if 'visibility:hidden' in style_lower.replace(' ', '') or 'visibility: hidden' in style_lower:
return False
# Check for hidden attribute
if element.get('hidden') is not None:
return False
return True
def suggest_input_values(html):
soup = BeautifulSoup(html, 'html.parser')
# Find all <input> and <textarea> elements
elements = soup.find_all(['input', 'textarea'])
valid_types = [
'text',
'password',
'email',
'number',
'date',
'datetime-local',
'month',
'range',
'search',
'tel',
'time',
'url',
'week'
]
# Filter out elements with invalid types and invisible elements
elements = [
el for el in elements if (
el.name == 'textarea' or
(el.name ==
'input' and 'type' in el.attrs and el['type'] in valid_types)
) and is_element_visible(el)
]
# Extract IDs and names (only if they exist)
target_identifiers = []
for el in elements:
if 'id' in el.attrs:
target_identifiers.append(('id', el['id']))
elif 'name' in el.attrs:
target_identifiers.append(('name', el['name']))
extracted_data = []
for identifier_type, identifier_value in target_identifiers:
if identifier_type == 'id':
target_element = soup.find(id=identifier_value)
else: # name
target_element = soup.find(attrs={'name': identifier_value})
# If the web is more than 60K tokens,
# it will be considered as an input within 60K tokens from where the desired input ID is.
if count_tokens(html) > 60000:
target_html = truncate_with_context(
soup, target_element,max_tokens=60000)
else:
target_html = html
# Build the prompt for structured extraction
system_msg = {
"role": "system",
"content": (
"You are an HTML parser. You receive HTML below and process only the element whose id or name equals the specified value. "
"For that element, create a JSON object with keys: name, id, type, limitations, examples, and bad_examples. "
"- name: The value of the 'name' attribute.\n"
"- id: The value of the 'id' attribute (use the name if id doesn't exist).\n"
"- type: Input type (text, password, etc.) or 'textarea'.\n"
"- limitations: Validation rules extracted from attributes like minlength, maxlength, pattern, or placeholder. This description should be written in English as complete sentences.\n"
"- examples: 5 example values that match these limitations and would be ACCEPTED by the field validation.\n"
"- bad_examples: 5 example values that VIOLATE these limitations and would be REJECTED by the field validation (for negative testing).\n"
"Keep the keys constant but write limitation values in English.\n"
"Provide output only as a JSON object matching the Pydantic schema.\n"
f"Process only and exclusively the element with {'id' if identifier_type == 'id' else 'name'} equal to '{identifier_value}'. Do not include any other element in the output.\n"
"Here are examples for understanding:\n\n"
"Example 1:\n"
"Input:\n"
"<input id=\"password\" name=\"password\" type=\"password\" minlength=\"8\" />\n"
"Output:\n"
"{\n"
" \"name\": \"password\",\n"
" \"id\": \"password\",\n"
" \"type\": \"password\",\n"
" \"examples\": [\"password123\", \"MySecure2024\", \"TestPass99\", \"AdminLogin1\", \"UserAccess88\"],\n"
" \"bad_examples\": [\"123\", \"pass\", \"1234567\", \"a\", \"\"],\n"
" \"limitations\": \"The password must be at least 8 characters long. English lowercase or uppercase letters are allowed. Numbers and other common characters can also be used to increase security.\"\n"
"}\n\n"
"Example 2:\n"
"Input:\n"
"<input id=\"email\" name=\"email\" type=\"email\" />\n"
"Output:\n"
"{\n"
" \"name\": \"email\",\n"
" \"id\": \"email\",\n"
" \"type\": \"email\",\n"
" \"examples\": [\"user@example.com\", \"test.email@domain.org\", \"admin@company.co.uk\", \"developer@site.net\", \"contact@business.info\"],\n"
" \"bad_examples\": [\"invalid-email\", \"@domain.com\", \"user@\", \"plaintext\", \"user.domain.com\"],\n"
" \"limitations\": \"Must be a valid email address with @ symbol and proper domain format.\"\n"
"}\n\n"
"Example 3:\n"
"Input:\n"
"<input id=\"phone\" name=\"phone\" type=\"text\" pattern=\"\\d{11}\" />\n"
"Output:\n"
"{\n"
" \"name\": \"phone\",\n"
" \"id\": \"phone\",\n"
" \"type\": \"text\",\n"
" \"examples\": [\"09123456789\", \"09351234567\", \"09221234567\", \"09901234567\", \"09111111111\"],\n"
" \"bad_examples\": [\"0912345678\", \"091234567890\", \"abc1234567\", \"09-123-456\", \"123456789\"],\n"
" \"limitations\": \"The phone number must contain exactly 11 numeric digits with no spaces, symbols, or letters allowed.\"\n"
"}\n"
)
}
user_msg = {"role": "user", "content": target_html}
# Call the LLM with the JSON schema
if is_local:
response = chat(model="llama3.1",
messages=[system_msg, user_msg],
format=FormField.model_json_schema(),
options={"num_ctx": 32768}
)
raw = response['message']['content']
else:
response = client.beta.chat.completions.parse(
model=model_name,
messages=[system_msg, user_msg],
response_format=FormField,
)
raw = response.choices[0].message.content
# Parse the structured JSON content
data = json.loads(raw)
# Translate limitations to Persian
data['limitations'] = translate_to_persian(data['limitations'])
extracted_data.append(data)
return {'fields': extracted_data}
class KatalonTestImprover:
def __init__(self, katalon_html, katalon_path, events_data):
self.katalon_html = katalon_html
self.katalon_path = katalon_path
self.events_data = events_data
self.current_katalon = katalon_html
# Add chat history to maintain context
self.chat_history = []
# Create the main window
self.root = tk.Tk()
self.root.title("Katalon Test Improver")
self.root.geometry("1200x800")
# Handle window close event
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.setup_ui()
self.get_initial_suggestions()
def on_closing(self):
"""Handle window close event and shutdown all applications"""
try:
# Ask for confirmation
if messagebox.askokcancel("Quit", "Do you want to quit? This will close all applications."):
print(
"KatalonTestImprover window closed. Shutting down all applications...")
# Destroy the tkinter window
self.root.destroy()
# Shutdown the Flask server and exit the entire application
import threading
def shutdown_app():
try:
# Send shutdown signal to Flask server
import requests
requests.post(
'http://localhost:5000/shutdown', timeout=1)
except:
pass
# Force exit the entire application
os._exit(0)
# Run shutdown in a separate thread to avoid blocking
threading.Thread(target=shutdown_app, daemon=True).start()
except Exception as e:
print(f"Error during shutdown: {e}")
# Force exit if normal shutdown fails
os._exit(0)
def add_to_chat_history(self, role, content):
"""Add message to chat history for context"""
self.chat_history.append({"role": role, "content": content})
# Keep only last 20 messages to avoid token limit issues
if len(self.chat_history) > 20:
self.chat_history = self.chat_history[-20:]
def setup_ui(self):
# Create main frame
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Title
title_label = ttk.Label(main_frame, text="Katalon Test Improvement Assistant",
font=('Arial', 16, 'bold'))
title_label.pack(pady=(0, 10))
# Create notebook for tabs
notebook = ttk.Notebook(main_frame)
notebook.pack(fill=tk.BOTH, expand=True)
# Tab 1: Current Test
test_frame = ttk.Frame(notebook)
notebook.add(test_frame, text="Current Test")
# Current test display
ttk.Label(test_frame, text="Current Katalon Test:", font=(
'Arial', 12, 'bold')).pack(anchor=tk.W, pady=(0, 5))
self.test_display = scrolledtext.ScrolledText(
test_frame, height=15, wrap=tk.WORD)
self.test_display.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
self.test_display.insert(
tk.END, self.extract_table_content(self.katalon_html))
# Buttons frame for test tab
test_buttons_frame = ttk.Frame(test_frame)
test_buttons_frame.pack(fill=tk.X, pady=5)
ttk.Button(test_buttons_frame, text="Open in Browser",
command=self.open_in_browser).pack(side=tk.LEFT, padx=(0, 5))
ttk.Button(test_buttons_frame, text="Save Current Test",
command=self.save_current_test).pack(side=tk.LEFT, padx=5)
ttk.Button(test_buttons_frame, text="Regenerate Test",
command=self.regenerate_test).pack(side=tk.LEFT, padx=5)
# Tab 2: Chat with AI
chat_frame = ttk.Frame(notebook)
notebook.add(chat_frame, text="AI Assistant")
# AI suggestions display
ttk.Label(chat_frame, text="AI Suggestions & Chat:", font=(
'Arial', 12, 'bold')).pack(anchor=tk.W, pady=(0, 5))
self.chat_display = scrolledtext.ScrolledText(
chat_frame, height=20, wrap=tk.WORD, state=tk.DISABLED)
self.chat_display.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
# User input frame
input_frame = ttk.Frame(chat_frame)
input_frame.pack(fill=tk.X, pady=5)
ttk.Label(input_frame, text="Your message:").pack(anchor=tk.W)
self.user_input = tk.Text(input_frame, height=3, wrap=tk.WORD)
self.user_input.pack(fill=tk.X, pady=(5, 5))
# Buttons frame for chat
chat_buttons_frame = ttk.Frame(input_frame)
chat_buttons_frame.pack(fill=tk.X, pady=5)
ttk.Button(chat_buttons_frame, text="Send Message",
command=self.send_message).pack(side=tk.LEFT, padx=(0, 5))
ttk.Button(chat_buttons_frame, text="Apply AI Suggestions",
command=self.apply_suggestions).pack(side=tk.LEFT, padx=5)
ttk.Button(chat_buttons_frame, text="Get New Suggestions",
command=self.get_new_suggestions).pack(side=tk.LEFT, padx=5)
ttk.Button(chat_buttons_frame, text="Clear History",
command=self.clear_chat_history).pack(side=tk.LEFT, padx=5)
# Status bar
self.status_var = tk.StringVar(value="Ready")
status_bar = ttk.Label(
main_frame, textvariable=self.status_var, relief=tk.SUNKEN)
status_bar.pack(fill=tk.X, pady=(10, 0))
# Bind Enter key to send message
self.user_input.bind('<Control-Return>', lambda e: self.send_message())
def extract_table_content(self, html):
"""Extract just the table content for display"""
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table')
if table:
rows = table.find_all('tr')
content = []
for row in rows[1:]: # Skip header row
cells = row.find_all('td')
if len(cells) >= 3:
command = cells[0].get_text().strip()
target = cells[1].get_text().strip()
value = cells[2].get_text().strip()
content.append(f"{command:<15} | {target:<30} | {value}")
return '\n'.join(content)
return "No table found"
def add_chat_message(self, sender, message, color="black"):
"""Add a message to the chat display"""
self.chat_display.config(state=tk.NORMAL)
self.chat_display.insert(tk.END, f"\n{sender}: ", f"{sender.lower()}")
self.chat_display.insert(tk.END, f"{message}\n")
# Configure tags for different senders
self.chat_display.tag_configure(
"ai", foreground="blue", font=('Arial', 10, 'bold'))
self.chat_display.tag_configure(
"user", foreground="green", font=('Arial', 10, 'bold'))
self.chat_display.tag_configure(
"system", foreground="red", font=('Arial', 10, 'bold'))
self.chat_display.config(state=tk.DISABLED)
self.chat_display.see(tk.END)
def get_initial_suggestions(self):
"""Get initial AI suggestions for the test"""
self.status_var.set("Getting AI suggestions...")
self.add_chat_message(
"System", "Analyzing your Katalon test and generating suggestions...")
def get_suggestions():
try:
current_test = self.extract_table_content(self.current_katalon)
prompt = f"""You are a test automation expert. Analyze this Katalon Recorder test and provide specific suggestions for improvement:
Current Test:
{current_test}
Please analyze and suggest improvements in these areas:
1. **Wait Times**: Are the pause commands appropriate? Too long or too short?
2. **Element Locators**: Are xpath selectors reliable? Should we use id or css selectors instead?
3. **Test Structure**: Is the test flow logical and maintainable?
4. **Missing Steps**: Are there any verification steps or assertions missing?
5. **Optimization**: Can any steps be combined or simplified?
Provide specific, actionable suggestions in Katalon command format only. Do not provide explanations or code - just suggest commands in this format:
command | target | value
Example suggestions:
- assertTitle | Google |
- verifyElementPresent | id=search-button |
- pause | 2000 | Wait 2s
- type | id=username | testuser
- click | css=.submit-btn |"""
# Add system context to chat history
system_context = f"I am analyzing a Katalon test with the following structure:\n{current_test}"
self.add_to_chat_history("system", system_context)
self.add_to_chat_history("user", prompt)
if is_local:
response = chat(model="llama3.1",
messages=self.chat_history)
suggestions = response['message']['content']
else:
response = client.chat.completions.create(
model=model_name,
messages=self.chat_history,
temperature=0.7,
max_tokens=1000
)
suggestions = response.choices[0].message.content
# Add AI response to history
self.add_to_chat_history("assistant", suggestions)
self.root.after(
0, lambda: self.add_chat_message("AI", suggestions))
self.root.after(0, lambda: self.status_var.set("Ready"))
except Exception as e:
self.root.after(0, lambda: self.add_chat_message(
"System", f"Error getting suggestions: {str(e)}"))
self.root.after(0, lambda: self.status_var.set("Error"))
threading.Thread(target=get_suggestions, daemon=True).start()
def send_message(self):
"""Send user message to AI"""
message = self.user_input.get(1.0, tk.END).strip()
if not message:
return
self.add_chat_message("User", message)
self.user_input.delete(1.0, tk.END)
self.status_var.set("AI is thinking...")
def get_response():
try:
current_test = self.extract_table_content(self.current_katalon)
# Create context-aware prompt that includes current test state
contextual_prompt = f"""{message}"""
# Add user message to history
self.add_to_chat_history("user", contextual_prompt)
if is_local:
response = chat(model="llama3.1",
messages=self.chat_history)
ai_response = response['message']['content']
else:
response = client.chat.completions.create(
model=model_name,
messages=self.chat_history,
temperature=0.7,
max_tokens=1000
)
ai_response = response.choices[0].message.content
# Add AI response to history
self.add_to_chat_history("assistant", ai_response)
self.root.after(
0, lambda: self.add_chat_message("AI", ai_response))
self.root.after(0, lambda: self.status_var.set("Ready"))
except Exception as e:
self.root.after(0, lambda: self.add_chat_message(
"System", f"Error: {str(e)}"))
self.root.after(0, lambda: self.status_var.set("Error"))
threading.Thread(target=get_response, daemon=True).start()
def apply_suggestions(self):
"""Let AI apply its suggestions to improve the test"""
self.status_var.set("Applying AI suggestions...")
def apply_improvements():
try:
current_test = self.extract_table_content(self.current_katalon)
prompt = f"""Based on our previous conversation and suggestions, please improve this Katalon test by applying the best practices we discussed:
Current Test:
{current_test}
Please generate an improved version of this test considering:
1. Our previous suggestions and discussion
2. Better element locators (prefer id > css > xpath)
3. Appropriate wait times (not too long, not too short)
4. Added verification steps where appropriate
5. Better test structure
Return the improved test in the same format as the input, with each line containing:
command | target | value
Only return the improved test commands, nothing else."""
# Add to chat history
self.add_to_chat_history("user", prompt)
if is_local:
response = chat(model="llama3.1",
messages=self.chat_history)
improved_test = response['message']['content']
else:
response = client.chat.completions.create(
model=model_name,
messages=self.chat_history,
temperature=0.3,
max_tokens=2000
)
improved_test = response.choices[0].message.content
# Add AI response to history
self.add_to_chat_history("assistant", improved_test)
# Convert improved test back to HTML format
new_html = self.convert_text_to_katalon_html(improved_test)
self.current_katalon = new_html
self.root.after(0, lambda: self.update_test_display())
self.root.after(0, lambda: self.add_chat_message(
"AI", "Test has been improved based on our previous discussion! Check the 'Current Test' tab to see the changes."))
self.root.after(
0, lambda: self.status_var.set("Test improved"))
except Exception as e:
self.root.after(0, lambda: self.add_chat_message(
"System", f"Error applying suggestions: {str(e)}"))
self.root.after(0, lambda: self.status_var.set("Error"))
threading.Thread(target=apply_improvements, daemon=True).start()
def get_new_suggestions(self):
"""Get fresh AI suggestions while maintaining context"""
self.status_var.set("Getting new suggestions...")
def get_fresh_suggestions():
try:
current_test = self.extract_table_content(self.current_katalon)
prompt = f"""Based on our previous conversation, please analyze the current state of this Katalon test and provide new suggestions:
Current Test:
{current_test}
Considering our previous discussion and any changes made, please provide fresh suggestions for further improvements. Focus on areas we haven't addressed yet or new issues you notice.
Provide specific, actionable suggestions in Katalon command format:
command | target | value"""
# Add to chat history
self.add_to_chat_history("user", prompt)
if is_local:
response = chat(model="llama3.1",
messages=self.chat_history)
suggestions = response['message']['content']
else:
response = client.chat.completions.create(
model=model_name,
messages=self.chat_history,
temperature=0.7,
max_tokens=1000
)
suggestions = response.choices[0].message.content
# Add AI response to history
self.add_to_chat_history("assistant", suggestions)
self.root.after(
0, lambda: self.add_chat_message("AI", f"Fresh suggestions based on our conversation:\n{suggestions}"))
self.root.after(0, lambda: self.status_var.set("Ready"))
except Exception as e:
self.root.after(0, lambda: self.add_chat_message(
"System", f"Error getting new suggestions: {str(e)}"))
self.root.after(0, lambda: self.status_var.set("Error"))
threading.Thread(target=get_fresh_suggestions, daemon=True).start()
def convert_text_to_katalon_html(self, text_commands):
"""Convert text commands back to Katalon HTML format"""
lines = text_commands.strip().split('\n')
rows = []
for line in lines:
line = line.strip()
if '|' in line:
parts = [part.strip() for part in line.split('|')]
if len(parts) >= 3:
command, target, value = parts[0], parts[1], parts[2]
rows.append(f'''<tr>
<td>{command}</td>
<td>{target}</td>
<td>{value}</td>
</tr>''')
# Get base URL from original HTML
soup = BeautifulSoup(self.katalon_html, 'html.parser')
base_link = soup.find('link', rel='selenium.base')
base_url = base_link['href'] if base_link else "http://localhost:3000"
html_template = '''<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="selenium.base" href="{base_url}">
<title>Improved Katalon Test</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Improved Katalon Test</td></tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</body>
</html>'''
return html_template.format(base_url=base_url, rows='\n'.join(rows))
def update_test_display(self):
"""Update the test display with current HTML"""
self.test_display.delete(1.0, tk.END)
self.test_display.insert(
tk.END, self.extract_table_content(self.current_katalon))
def open_in_browser(self):
"""Open the current test in browser"""
temp_path = os.path.join(RUN_SAVE_DIR, 'temp_katalon_test.html')
with open(temp_path, 'w', encoding='utf-8') as f:
f.write(self.current_katalon)
webbrowser.open(f'file://{os.path.abspath(temp_path)}')
def save_current_test(self):
"""Save the current improved test"""
with open(self.katalon_path, 'w', encoding='utf-8') as f:
f.write(self.current_katalon)
self.add_chat_message("System", "Test saved successfully!")
self.status_var.set("Test saved")
def regenerate_test(self):
"""Regenerate the test from original events"""
try:
new_katalon = convert_to_katalon_format(self.events_data)
self.current_katalon = new_katalon
self.update_test_display()
self.add_chat_message(
"System", "Test regenerated from original events.")
self.status_var.set("Test regenerated")
except Exception as e:
self.add_chat_message(
"System", f"Error regenerating test: {str(e)}")
def clear_chat_history(self):
"""Clear chat history and start fresh"""
self.chat_history = []
self.add_chat_message(
"System", "Chat history cleared. Starting fresh conversation.")
self.status_var.set("History cleared")
def show(self):
"""Show the window"""
self.root.mainloop()
def show_katalon_improver(katalon_html, katalon_path, events_data):
"""Show the Katalon test improver window"""
def run_improver():
improver = KatalonTestImprover(katalon_html, katalon_path, events_data)
improver.show()
# Run in a separate thread to not block the Flask server
threading.Thread(target=run_improver, daemon=True).start()
@app.route('/events', methods=['POST'])
def events():
data = request.get_json()
events_path = os.path.join(RUN_SAVE_DIR, 'recorded_events.json')
with open(events_path, 'w', encoding='utf-8') as f:
json.dump(data['events'], f, ensure_ascii=False, indent=2)
# Create Katalon Recorder table
katalon_table = convert_to_katalon_format(data['events'])
katalon_path = os.path.join(RUN_SAVE_DIR, 'katalon_test.html')
with open(katalon_path, 'w', encoding='utf-8') as f:
f.write(katalon_table)
print(f"Saved {len(data['events'])} events to recorded_events.json")
print(f"Saved Katalon Recorder table to katalon_test.html")
# Show the Katalon test improver window
show_katalon_improver(katalon_table, katalon_path, data['events'])
return 'ok'
def convert_to_katalon_format(events):
"""Convert recorded events to Katalon Recorder HTML table format"""
# Filter out extension-specific events
extension_events = [
'suggest_inputs_start',
'suggest_inputs_complete',
'suggestion_question_mark_click',
'suggestion_modal_open',
'suggestion_modal_cancel',
'suggestion_modal_confirm',
'suggestion_modal_submit_start',
'suggestion_modal_submit_success',
'suggestion_modal_submit_failure'
]
# Extension-specific element IDs or prefixes
extension_element_ids = [
'edit-range',
'edit-examples',
'edit-cancel',
'edit-confirm',
'edit-submit',
'input-suggestion-modal',
'suggest-inputs'
]
# Filter valid events and calculate extension durations
valid_events = []
extension_durations = {} # Track extension processing times between events
for i, event in enumerate(events):
event_type = event.get('type', '')
element_id = event.get('id', '')
# Skip extension-specific event types
if event_type in extension_events:
continue
# Skip clicks on extension-specific elements
if event_type == 'click' and any(element_id.startswith(prefix) for prefix in extension_element_ids):
continue
# Skip typing in extension-specific elements
if event_type == 'change' and any(element_id.startswith(prefix) for prefix in extension_element_ids):
continue
# Skip events from the extension's popup
if event.get('url', '').startswith('chrome-extension://'):
continue
# Calculate extension duration since last valid event
extension_duration = 0
if len(valid_events) > 0:
last_valid_time = valid_events[-1]['time']
current_time = event.get('time')
# Find extension events between last valid event and current event
for check_event in events: