-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathBuiltInFunctions.py
More file actions
5154 lines (4629 loc) · 202 KB
/
BuiltInFunctions.py
File metadata and controls
5154 lines (4629 loc) · 202 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
# -*- coding: utf-8 -*-
# -*- coding: cp1252 -*-
"""
Created on May 15, 2016
@author: Built_In_Automation Solutionz Inc.
Name: Built In Functions - Selenium
Description: Sequential Actions for controlling Web Browsers - All main Web Browsers supported on Linux/Windows/Mac
"""
#########################
# #
# Modules #
# #
#########################
import platform
import sys, os, time, inspect, shutil, subprocess, json, re
import socket
import requests
import psutil
import pyperclip
import base64, imghdr
from pathlib import Path
from urllib.parse import urlparse
sys.path.append("..")
from selenium import webdriver
if "linux" in platform.system().lower():
from xvfbwrapper import Xvfb
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import IEDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_manager.opera import OperaDriverManager
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import (
ElementClickInterceptedException,
WebDriverException,
SessionNotCreatedException,
TimeoutException,
NoSuchFrameException,
StaleElementReferenceException,
TimeoutException,
)
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support import expected_conditions as EC
import selenium
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
from Framework.Utilities import CommonUtil, ConfigModule
from Framework.Built_In_Automation.Shared_Resources import (
BuiltInFunctionSharedResources as Shared_Resources,
)
from Framework.Utilities.decorators import logger, deprecated
from Framework.Built_In_Automation.Shared_Resources import LocateElement
from Framework.Utilities.CommonUtil import (
passed_tag_list,
failed_tag_list,
skipped_tag_list,
)
from Framework.AI.NLP import binary_classification
from .utils import ChromeForTesting, ChromeExtensionDownloader
#########################
# #
# Global Variables #
# #
#########################
MODULE_NAME = inspect.getmodulename(__file__)
temp_config = os.path.join(
os.path.join(
os.path.abspath(__file__).split("Framework")[0],
os.path.join(
"AutomationLog", ConfigModule.get_config_value("Advanced Options", "_file")
),
)
)
temp_config = str(
Path(os.path.abspath(__file__).split("Framework")[0])
/ "AutomationLog"
/ ConfigModule.get_config_value("Advanced Options", "_file")
)
aiplugin_path = str(
Path(os.path.abspath(__file__).split("Framework")[0]) / "Apps" / "Web" / "aiplugin"
)
ai_recorder_path = str(
Path(os.path.abspath(__file__).split("Framework")[0])
/ "Apps"
/ "Web"
/ "AI_Recorder_2"
/ "dist"
)
ai_recorder_public_path = str(
Path(os.path.abspath(__file__).split("Framework")[0])
/ "Apps"
/ "Web"
/ "AI_Recorder_2"
/ "public"
)
# Disable WebdriverManager SSL verification.
os.environ["WDM_SSL_VERIFY"] = "0"
current_driver_id = None
selenium_driver = None
selenium_details = {}
default_x, default_y = 1920, 1080
vdisplay = None
initial_download_folder = None
browser_map = {
"Microsoft Edge Chromium": "microsoftedge",
"Chrome": "chrome",
"FireFox": "firefox",
"Opera": "opera",
"ChromeHeadless": "chrome",
"FirefoxHeadless": "firefox",
"EdgeChromiumHeadless": "microsoftedge",
"Safari": "safari",
}
options_map = {
"Microsoft Edge Chromium": "edge",
"Chrome": "chrome",
"FireFox": "firefox",
"Opera": "opera",
"ChromeHeadless": "chrome",
"FirefoxHeadless": "firefox",
"EdgeChromiumHeadless": "edge",
"Safari": "safari",
}
from typing import Literal, TypedDict, Any, Union, NotRequired
Dataset = list[tuple[str, str, str]]
ReturnType = Literal["passed", "zeuz_failed"]
class DefaultChromiumArguments(TypedDict):
add_argument: list[str]
add_experimental_option: dict[str, Any]
add_extension: list[str]
add_encoded_extension: list[str]
page_load_strategy: NotRequired[Literal["normal", "eager", "none"]]
class FirefoxArguments(TypedDict):
add_argument: list[str]
set_preference: dict[str, Any]
class SafariArguments(TypedDict):
add_argument: list[str]
class BrowserOptions(TypedDict):
capabilities: dict[str, Any]
chrome: DefaultChromiumArguments
edge: DefaultChromiumArguments
firefox: FirefoxArguments
safari: SafariArguments
from selenium.webdriver.common.options import ArgOptions
# JavaScript for collecting First Contentful Paint value.
JS_FCP = """
return performance.getEntriesByName("first-contentful-paint")[0].startTime
"""
# JavaScript for collecting Largest Contentful Paint value.
JS_LCP = """
var args = arguments;
const po = new PerformanceObserver(list => {
const entries = list.getEntries();
const entry = entries[entries.length - 1];
// Process entry as the latest LCP candidate
// LCP is accurate when the renderTime is available.
// Try to avoid this being false by adding Timing-Allow-Origin headers!
const accurateLCP = entry.renderTime ? true : false;
// Use startTime as the LCP timestamp. It will be renderTime if available, or loadTime otherwise.
const largestPaintTime = entry.startTime;
// Send the LCP information for processing.
console.log("[ZeuZ Node] Largest Contentful Paint: ", largestPaintTime);
args[0](largestPaintTime);
});
po.observe({ type: 'largest-contentful-paint', buffered: true });
"""
# if Shared_Resources.Test_Shared_Variables('selenium_driver'): # Check if driver is already set in shared variables
# selenium_driver = Shared_Resources.Get_Shared_Variables('selenium_driver') # Retreive appium driver
# Recall dependency, if not already set
dependency = None
if Shared_Resources.Test_Shared_Variables(
"dependency"
): # Check if driver is already set in shared variables
dependency = Shared_Resources.Get_Shared_Variables(
"dependency"
) # Retreive appium driver
else:
raise ValueError("No dependency set - Cannot run")
@logger
def get_driver():
return selenium_driver
@logger
def is_headless_environment():
"""
Detect if the current environment is headless (no display available).
This includes cloud instances, Docker containers, CI/CD environments, etc.
Returns:
bool: True if headless environment is detected, False otherwise
"""
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
try:
# Check for common headless environment indicators
headless_indicators = [
# Environment variables commonly set in headless environments
os.getenv('CI') is not None, # CI/CD environments
os.getenv('GITHUB_ACTIONS') is not None, # GitHub Actions
os.getenv('JENKINS_URL') is not None, # Jenkins
os.getenv('BUILDKITE') is not None, # Buildkite
os.getenv('TRAVIS') is not None, # Travis CI
os.getenv('CIRCLECI') is not None, # CircleCI
os.getenv('GITLAB_CI') is not None, # GitLab CI
os.getenv('TEAMCITY_VERSION') is not None, # TeamCity
os.getenv('TF_BUILD') is not None, # Azure DevOps
os.getenv('CODEBUILD_BUILD_ID') is not None, # AWS CodeBuild
os.getenv('DOCKER_CONTAINER') is not None, # Docker container
os.path.exists('/.dockerenv'), # Docker container indicator
os.getenv('KUBERNETES_SERVICE_HOST') is not None, # Kubernetes
os.getenv('HEADLESS') == '1', # Explicit headless flag
os.getenv('DISPLAY') is None and platform.system() == 'Linux', # No display on Linux
]
# Check if any headless indicator is present
if any(headless_indicators):
CommonUtil.ExecLog(sModuleInfo, "Headless environment detected based on environment variables", 1)
return True
display_vars = ['DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY']
for var in display_vars:
if os.environ.get(var) is not None:
CommonUtil.ExecLog(sModuleInfo, "Headless environment detection failed on environment variables", 2)
return False
CommonUtil.ExecLog(sModuleInfo, "Headless environment detected based on environment variables", 1)
return True
except Exception as e:
CommonUtil.ExecLog(sModuleInfo, f"Error detecting headless environment: {str(e)}", 2)
# If we can't determine, assume non-headless to be safe
return False
@logger
def find_exe_in_path(exe):
"""Search the path for an executable"""
try:
path = os.getenv("PATH") # Linux/Windows path
if ";" in path: # Windows delimiter
dirs = path.split(";")
elif ":" in path: # Linux delimiter
dirs = path.split(":")
else:
return "zeuz_failed"
for directory in dirs: # Try each directory
filename = os.path.join(directory, exe) # Create full path
if os.path.isfile(filename): # If it exists, return it and stop
return filename
# No matches
return "zeuz_failed"
except Exception:
errMsg = "Error searching PATH"
return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
@logger
def find_appium():
"""Do our very best to find the appium executable"""
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
# Expected locations
appium_list = [
"/usr/bin/appium",
os.path.join(str(os.getenv("HOME")), ".linuxbrew/bin/appium"),
os.path.join(str(os.getenv("ProgramFiles")), "APPIUM", "Appium.exe"),
os.path.join(
str(os.getenv("USERPROFILE")), "AppData", "Roaming", "npm", "appium.cmd"
),
os.path.join(str(os.getenv("ProgramFiles(x86)")), "APPIUM", "Appium.exe"),
] # getenv() must be wrapped in str(), so it doesn't fail on other platforms
# Try to find the appium executable
appium_binary = ""
for binary in appium_list:
if os.path.exists(binary):
appium_binary = binary
break
# Try to find the appium executable in the PATH variable
if appium_binary == "": # Didn't find where appium was installed
CommonUtil.ExecLog(sModuleInfo, "Searching PATH for appium", 0)
for exe in ("appium", "appium.exe", "appium.bat", "appium.cmd"):
result = find_exe_in_path(exe) # Get path and search for executable with in
if result != "zeuz_failed":
appium_binary = result
break
# Verify if we have the binary location
if appium_binary == "": # Didn't find where appium was installed
CommonUtil.ExecLog(
sModuleInfo, "Appium not found. Trying to locate via which", 0
)
try:
appium_binary = subprocess.check_output(
"which appium", encoding="utf-8", shell=True
).strip()
except:
pass
if appium_binary == "": # Didn't find where appium was installed
appium_binary = "appium" # Default filename of appium, assume in the PATH
CommonUtil.ExecLog(
sModuleInfo, "Appium still not found. Assuming it's in the PATH.", 2
)
else:
CommonUtil.ExecLog(sModuleInfo, "Found appium: %s" % appium_binary, 1)
else: # Found appium's path
CommonUtil.ExecLog(sModuleInfo, "Found appium: %s" % appium_binary, 1)
return appium_binary
@logger
def start_appium_server():
"""Starts the external Appium server.
Returns appium_port on success.
"""
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
appium_binary = find_appium()
def is_port_in_use(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("localhost", port)) == 0
try:
appium_port = 4723
tries = 0
while is_port_in_use(appium_port) and tries < 20:
appium_port += 2
if tries >= 20:
CommonUtil.ExecLog(
sModuleInfo,
"Failed to find a free port for running appium after 20 tries.",
1,
)
return "zeuz_failed"
try:
appium_server = None
if (
sys.platform == "win32"
): # We need to open appium in it's own command dos box on Windows
cmd = (
'start "Appium Server" /wait /min cmd /c %s --allow-insecure chromedriver_autodownload -p %d'
% (appium_binary, appium_port)
) # Use start to execute and minimize, then cmd /c will remove the dos box when appium is killed
appium_server = subprocess.Popen(
cmd, shell=True
) # Needs to run in a shell due to the execution command
elif sys.platform == "darwin":
appium_server = subprocess.Popen(
"%s --allow-insecure chromedriver_autodownload -p %s"
% (appium_binary, str(appium_port)),
shell=True,
)
elif sys.platform == "linux" or sys.platform == "linux2":
appium_server = subprocess.Popen(
"%s --allow-insecure chromedriver_autodownload -p %s"
% (appium_binary, str(appium_port)),
shell=True,
)
else:
try:
appium_binary_path = os.path.normpath(appium_binary)
appium_binary_path = os.path.abspath(
os.path.join(appium_binary_path, os.pardir)
)
env = {"PATH": str(appium_binary_path)}
appium_server = subprocess.Popen(
"%s --allow-insecure chromedriver_autodownload -p %s"
% (appium_binary, str(appium_port)),
shell=True,
env=env,
)
except:
CommonUtil.ExecLog(
sModuleInfo,
"Couldn't launch appium server, please do it manually by typing 'appium &' in the terminal",
2,
)
except Exception as returncode: # Couldn't run server
return CommonUtil.Exception_Handler(
sys.exc_info(),
None,
"Couldn't start Appium server. May not be installed, or not in your PATH: %s"
% returncode,
)
# Wait for server to startup and return
CommonUtil.ExecLog(
sModuleInfo,
"Waiting for server to start on port %d: %s" % (appium_port, appium_binary),
0,
)
maxtime = time.time() + 10 # Maximum time to wait for appium server
while True: # Dynamically wait for appium to start by polling it
if time.time() > maxtime:
break # Give up if max time was hit
try: # If this works, then stop waiting for appium
r = requests.get(
"http://localhost:%d/sessions" % appium_port
) # Poll appium server
if r.status_code:
break
except:
time.sleep(0.1) # sleep for 0.1 sec before retrying.
if appium_server:
CommonUtil.ExecLog(sModuleInfo, "Server started", 1)
return appium_port
else:
CommonUtil.ExecLog(sModuleInfo, "Server failed to start", 3)
return "zeuz_failed"
except Exception:
return CommonUtil.Exception_Handler(
sys.exc_info(), None, "Error starting Appium server"
)
@logger
def Open_Electron_App(data_set):
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
global selenium_driver
global selenium_details
global current_driver_id
try:
desktop_app_path = ""
driver_id = ""
for left, _, right in data_set:
left = left.replace(" ", "").replace("_", "").replace("-", "").lower()
if "windows" in left and platform.system() == "Windows":
desktop_app_path = right.strip()
elif "mac" in left and platform.system() == "Darwin":
desktop_app_path = right.strip()
elif "linux" in left and platform.system() == "Linux":
desktop_app_path = right.strip()
elif left == "driverid":
driver_id = right.strip()
if not desktop_app_path:
CommonUtil.ExecLog(
sModuleInfo,
"You did not provide an Electron app path for %s OS"
% platform.system(),
3,
)
return "zeuz_failed"
if not driver_id:
driver_id = "default"
desktop_app_path = CommonUtil.path_parser(desktop_app_path)
electron_chrome_path = ConfigModule.get_config_value(
"Selenium_driver_paths", "electron_chrome_path"
)
if not electron_chrome_path:
electron_chrome_path = ChromeDriverManager().install()
try:
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
opts = Options()
opts.binary_location = desktop_app_path
selenium_driver = webdriver.Chrome(opts, Service())
selenium_driver.implicitly_wait(0.5)
CommonUtil.ExecLog(sModuleInfo, "Started Electron App", 1)
Shared_Resources.Set_Shared_Variables("selenium_driver", selenium_driver)
CommonUtil.set_screenshot_vars(Shared_Resources.Shared_Variable_Export())
except Exception:
return CommonUtil.Exception_Handler(sys.exc_info())
if driver_id in selenium_details:
pass # we need to decide later based on the situation
else:
selenium_details[driver_id] = {"driver": selenium_driver}
current_driver_id = driver_id
return "passed"
except:
return CommonUtil.Exception_Handler(sys.exc_info())
@logger
def use_xvfb_or_headless(callback):
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
if platform.system() == "Linux":
try:
global vdisplay
vdisplay = Xvfb(width=1920, height=1080, colordepth=16)
vdisplay.start()
except:
CommonUtil.ExecLog(
sModuleInfo,
"Failed to initialize xvfb. "
"Perhaps xvfb is not installed?\n"
"For apt-get: `sudo apt-get install xvfb`\n"
"For yum: `sudo yum install xvfb`.\n"
"Falling back to headless mode.",
2,
)
callback()
else:
callback()
def set_extension_variables():
try:
url = ConfigModule.get_config_value("Authentication", "server_address").strip()
apiKey = ConfigModule.get_config_value("Authentication", "api-key").strip()
jwtKey = CommonUtil.jwt_token.strip()
metaData = {
"testNo": CommonUtil.current_tc_no,
"testName": CommonUtil.current_tc_name,
"stepNo": CommonUtil.current_step_sequence,
"stepName": CommonUtil.current_step_name,
"url": url,
"apiKey": apiKey,
"jwtKey": jwtKey,
"nodeId": Shared_Resources.Get_Shared_Variables("node_id"),
}
with open(Path(aiplugin_path) / "data.json", "w") as file:
json.dump(metaData, file, indent=4)
except:
return CommonUtil.Exception_Handler(
sys.exc_info(), None, "Could not load inspector extension"
)
try:
with open(Path(ai_recorder_path) / "background" / "data.json", "w") as file:
json.dump(metaData, file, indent=4)
with open(
Path(ai_recorder_public_path) / "background" / "data.json", "w"
) as file:
json.dump(metaData, file, indent=4)
except:
return CommonUtil.Exception_Handler(
sys.exc_info(), None, "Could not load recorder extension"
)
def generate_options(browser: str, browser_options: BrowserOptions):
"""Adds capabilities and options for Browser/WebDriver"""
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
chromium_condition = browser in ("android", "chrome", "chromeheadless", "microsoft edge chromium", "edgechromiumheadless")
# Check if we're in a headless environment and need to auto-enable headless mode
auto_headless = False
if "headless" not in browser.lower() and is_headless_environment():
auto_headless = True
CommonUtil.ExecLog(sModuleInfo, f"Headless environment detected. Auto-enabling headless mode for {browser}", 2)
msg = ""
if chromium_condition:
b = "edge" if "edge" in browser else "chrome"
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
options = ChromeOptions() if b == "chrome" else EdgeOptions()
# from selenium.webdriver.chromium.options import ChromiumOptions
# options = ChromiumOptions()
if browser == "android":
mobile_emulation = {"deviceName": "Pixel 2 XL"}
options.add_experimental_option("mobileEmulation", mobile_emulation)
for argument in browser_options[b]["add_argument"]:
options.add_argument(argument)
for key, val in browser_options[b]["add_experimental_option"].items():
options.add_experimental_option(key, val)
for extension in browser_options[b]["add_extension"]:
options.add_extension(extension)
for extension in browser_options[b]["add_encoded_extension"]:
options.add_encoded_extension(extension)
if "page_load_strategy" in browser_options[b]:
options.page_load_strategy = browser_options[b]["page_load_strategy"]
if "debugger_address" in browser_options[b]:
# When debugger_address is mentioned, the Service() object should be ignored by default
# Users need to remove experimental options by setting it to {}
options.debugger_address = browser_options[b]["debugger_address"]
msg += f"Debugger address: {options.debugger_address}\n"
msg += (
f"Experimental_options: {json.dumps(options.experimental_options, indent=2)}\n"
f"Extensions: {len(options.extensions)} added\n"
)
elif browser in ("firefox", "firefoxheadless"):
from selenium.webdriver.firefox.options import Options as FirefoxOptions
options = FirefoxOptions()
for argument in browser_options["firefox"]["add_argument"]:
options.add_argument(argument)
for key, val in browser_options["firefox"]["set_preference"].items():
options.set_preference(key, val)
if "page_load_strategy" in browser_options["firefox"]:
options.page_load_strategy = browser_options["firefox"][
"page_load_strategy"
]
msg += f"Preferences: {json.dumps(options.preferences, indent=2)}\n"
elif "safari" in browser:
from selenium.webdriver.safari.options import Options as SafariOptions
options = SafariOptions()
for argument in browser_options["safari"]["add_argument"]:
options.add_argument(argument)
if "page_load_strategy" in browser_options["safari"]:
options.page_load_strategy = browser_options["safari"]["page_load_strategy"]
else:
from selenium.webdriver.common.options import ArgOptions
return ArgOptions()
# Add headless arguments if explicitly requested or auto-detected
if "headless" in browser or auto_headless:
def headless():
if "chrome" in browser or "edge" in browser:
arg = "--headless=new"
else:
arg = "--headless"
# Check if headless argument is already present
headless_already_added = any(
"--headless" in str(arg) for arg in getattr(options, 'arguments', [])
)
if not headless_already_added:
options.add_argument(arg)
if auto_headless:
CommonUtil.ExecLog(sModuleInfo, f"Added {arg} argument due to headless environment detection", 1)
use_xvfb_or_headless(headless)
for key, value in browser_options["capabilities"].items():
options.set_capability(key, value)
# On Debug run open inspector with credentials
if (
CommonUtil.debug_status
and ConfigModule.get_config_value("Inspector", "ai_plugin").strip().lower()
in ("true", "on", "enable", "yes", "on_debug")
and browser in ("chrome", "microsoft edge chromium")
):
set_extension_variables()
options.add_argument("--disable-features=DisableLoadExtensionCommandLineSwitch")
options.add_argument(f"load-extension={aiplugin_path},{ai_recorder_path}")
# This is for running extension on a http server to call a https request
options.add_argument("--allow-running-insecure-content")
msg += (
f"Capabilities: {json.dumps(options.capabilities, indent=2)}\n"
+ f"Arguments: {json.dumps(options.arguments, indent=2)}\n"
+ f"Page load strategy: {options.page_load_strategy}\n"
)
CommonUtil.ExecLog(sModuleInfo, msg, 5)
return options
@logger
def Open_Browser(browser, browser_options: BrowserOptions):
"""Launch browser from options and service object"""
try:
global selenium_driver
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
browser = browser.lower().strip()
if browser == "ios":
# Finds the appium binary and starts the server.
appium_port = start_appium_server()
if appium_port == "zeuz_failed":
return "zeuz_failed"
capabilities = {
"platformName": "iOS",
"automationName": "XCUITest",
"browserName": "Safari",
}
from appium import webdriver as appiumdriver
from appium.options.android import UiAutomator2Options
capabilities_options = UiAutomator2Options().load_capabilities(capabilities)
selenium_driver = appiumdriver.Remote(
"http://localhost:%d" % appium_port, options=capabilities_options
)
return "passed"
options = generate_options(browser, browser_options)
if browser in ("android", "chrome", "chromeheadless"):
from selenium.webdriver.chrome.service import Service
chrome_bin = browser_options["chrome"].get("binary_location", None)
driver_bin = browser_options["chrome"].get("driver_path", None)
if chrome_bin and driver_bin:
# Use Chrome for Testing binaries
service = Service(executable_path=driver_bin)
options.binary_location = chrome_bin
CommonUtil.ExecLog(sModuleInfo, "Using Chrome for Testing binaries", 1)
else:
# Use standard ChromeDriverManager
service = Service()
CommonUtil.ExecLog(sModuleInfo, "Using standard Chrome binaries", 1)
selenium_driver = webdriver.Chrome(
service=service,
options=options,
)
# service = Service()
# selenium_driver = webdriver.Chrome(
# service=service,
# options=options,
# )
elif browser in ("microsoft edge chromium", "edgechromiumheadless"):
from selenium.webdriver.edge.service import Service
service = Service()
selenium_driver = webdriver.Edge(
service=service,
options=options,
)
elif browser in ("firefox", "firefoxheadless"):
from selenium.webdriver.firefox.service import Service
service = Service()
selenium_driver = webdriver.Firefox(
service=service,
options=options,
)
elif "safari" in browser:
from selenium.webdriver.safari.service import Service
service = Service()
selenium_driver = webdriver.Safari(
service=service,
options=options,
)
else:
CommonUtil.ExecLog(
sModuleInfo, "You did not select a valid browser: %s" % browser, 3
)
return "zeuz_failed"
CommonUtil.ExecLog(sModuleInfo, f"Started {browser} browser", 1)
Shared_Resources.Set_Shared_Variables("selenium_driver", selenium_driver)
CommonUtil.set_screenshot_vars(Shared_Resources.Shared_Variable_Export())
return "passed"
except Exception:
return CommonUtil.Exception_Handler(sys.exc_info())
@logger
def Go_To_Link_V2(step_data):
from selenium.webdriver.chrome.options import Options
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
global dependency
global selenium_driver
global selenium_details
global current_driver_id
url = None
driver_tag = "default"
page_load_timeout_sec = 120
options = Options()
page_load_strategy = "normal"
for left, _, right in step_data:
left = left.strip().lower()
if "add argument" == left:
options.add_argument(right.strip())
CommonUtil.ExecLog(sModuleInfo, "Added argument: " + right.strip(), 1)
elif "add extension" == left:
filepath = CommonUtil.path_parser(right.strip())
options.add_extension(filepath)
CommonUtil.ExecLog(sModuleInfo, "Added extension: " + filepath, 1)
elif "add experimental option" in left:
options.add_experimental_option(
eval(right.split(",", 1)[0].strip()),
eval(right.split(",", 1)[1].strip()),
)
CommonUtil.ExecLog(
sModuleInfo, "Added experimental option: " + right.strip(), 1
)
elif "set capability" in left:
options.set_capability(
eval(right.split(",", 1)[0].strip()),
eval(right.split(",", 1)[1].strip()),
)
CommonUtil.ExecLog(sModuleInfo, "Added capability: " + right.strip(), 1)
elif "go to link v2" == left:
url = right.strip() if right.strip() != "" else None
elif "driver tag" == left:
driver_tag = right.strip()
elif "wait for element" == left:
Shared_Resources.Set_Shared_Variables("element_wait", float(right.strip()))
elif "page load timeout" == left:
page_load_timeout_sec = float(right.strip())
elif "page load strategy" == left:
page_load_strategy = right.strip()
options.page_load_strategy = page_load_strategy
if driver_tag in selenium_details.keys():
selenium_driver = selenium_details[driver_tag]["driver"]
else:
if Shared_Resources.Test_Shared_Variables("dependency"):
dependency = Shared_Resources.Get_Shared_Variables("dependency")
else:
raise ValueError("No dependency set - Cannot run")
dependency_browser = dependency["Browser"].lower()
if "headless" in dependency_browser:
options.add_argument("--headless")
CommonUtil.ExecLog(sModuleInfo, "Added headless argument", 1)
if "chrome" in dependency_browser:
selenium_driver = webdriver.Chrome(options=options)
elif "firefox" in dependency_browser:
selenium_driver = webdriver.Firefox(options=options)
selenium_driver.set_page_load_timeout(page_load_timeout_sec)
selenium_details[driver_tag] = dict()
selenium_details[driver_tag]["driver"] = selenium_driver
current_driver_id = selenium_driver
Shared_Resources.Set_Shared_Variables("selenium_driver", selenium_driver)
# Handle headless mode window maximize
if (
"--headless" in options.arguments
and "--start-maximized" in options.arguments
):
selenium_driver.set_window_size(default_x, default_y)
if url:
selenium_driver.get(url)
selenium_driver.maximize_window()
Shared_Resources.Set_Shared_Variables("selenium_driver", selenium_driver)
CommonUtil.set_screenshot_vars(Shared_Resources.Shared_Variable_Export())
return "passed"
def parse_and_verify_datatype(left: str, right: str, chrome_version=None):
val = CommonUtil.parse_value_into_object(right)
if left == "addargument":
if isinstance(val, list) and all(isinstance(item, str) for item in val):
return val
raise ValueError(
"Argument must be list of strings. Example: ['--ignore-ssl-errors', '--no-sandbox']"
)
if left == "addextension":
if isinstance(val, list) and all(isinstance(item, str) for item in val):
extension_ids = []
extension_crxs = []
for item in val:
if item.lower().endswith(".crx") or os.path.isfile(item):
extension_crxs.append(item)
elif re.match(r"^[a-p]{32}$", item):
extension_ids.append(item)
else:
raise ValueError(
f"Invalid extension: {item}. Must be .crx file path or Chrome extension ID."
)
# download all extensions from ids
for ext_id in extension_ids:
downloader = ChromeExtensionDownloader(chrome_version=chrome_version)
result = downloader.setup_chrome_extension_download(extension_id=ext_id)
if result.get("crx_path"):
extension_crxs.append(result["crx_path"])
return extension_crxs
raise ValueError(
"Extensions must be list of strings. Example: ['path/to/ex1.crx', 'path/to/ex2.crx']"
)
if left == "addencodedextension":
if isinstance(val, list) and all(isinstance(item, str) for item in val):
return val
raise ValueError(
"Encoded_extenions must be list of strings. Example: ['ex1_encoded_str', 'ex2_encoded_str']"
)
elif left == "addexperimentaloption":
if isinstance(val, dict):
return val
raise ValueError(
'Experimental_option must be dictionary. Example: {"mobileEmulation":{"deviceName": "Pixel 2 XL"}}'
)
elif left == "setpreference":
if isinstance(val, dict):
return val
raise ValueError(
'Preference must be dictionary. Example: {"security.mixed_content.block_active_content": False}'
)
@logger
def Go_To_Link(dataset: Dataset) -> ReturnType:
try:
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
window_size_X = None
window_size_Y = None
global initial_download_folder
initial_download_folder = download_dir = ConfigModule.get_config_value(
"sectionOne", "initial_download_folder", temp_config
)
apps = "application/pdf;text/plain;application/text;text/xml;application/xml;application/xlsx;application/csv;application/zip"
default_chromium_arguments = {
"add_argument": [
"--ignore-certificate-errors",
"--ignore-ssl-errors",
"--zeuz_pid_finder",
# "--remote-debugging-port=9222", # Required for playright
# "--no-sandbox"
],
"add_experimental_option": {
"prefs": {
# "profile.default_content_settings.popups": 0,
"download.default_directory": download_dir,
"download.prompt_for_download": False,
# "download.directory_upgrade": True,
# 'safebrowsing.enabled': 'false'
}
},
"add_extension": [],
"add_encoded_extension": [],
# "page_load_strategy": "normal"
}
browser_options: BrowserOptions = {
"capabilities": {
"unhandledPromptBehavior": "ignore",
# "goog:loggingPrefs": {"performance": "ALL"},
},
"chrome": default_chromium_arguments,
"edge": default_chromium_arguments,
"firefox": {
"add_argument": [],
"set_preference": {
"browser.download.folderList": 2,
"browser.download.manager.showWhenStarting": False,
"browser.download.dir": download_dir,
"browser.helperApps.neverAsk.saveToDisk": apps,
"browser.download.useDownloadDir": True,