Skip to content

Commit fabe980

Browse files
Merge pull request #235 from AutomationSolutionz/selenium_deprecation_fix
Selenium deprecation fix
2 parents 15e60f1 + e3ad53c commit fabe980

File tree

6 files changed

+105
-37
lines changed

6 files changed

+105
-37
lines changed

Framework/Built_In_Automation/Sequential_Actions/common_functions.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -790,7 +790,9 @@ def save_into_variable(data_set):
790790

791791
try:
792792
if extra_operation:
793-
if "length" in extra_operation:
793+
if "path" in extra_operation or "directory" in extra_operation:
794+
variable_value = CommonUtil.path_parser(variable_value)
795+
elif "length" in extra_operation:
794796
variable_value = len(variable_value)
795797
elif "no duplicate" in extra_operation:
796798
variable_value = list(set(variable_value))

Framework/Built_In_Automation/Sequential_Actions/sequential_actions.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,7 @@ def for_loop_action(step_data, data_set_no):
587587
iterable = CommonUtil.ZeuZ_map_code_decoder(iterable) # Decode if this is a ZeuZ_map_code
588588
else:
589589
iterable = CommonUtil.parse_value_into_object(left)
590-
CommonUtil.ExecLog(sModuleInfo, "Looping through a %s: %s" % (type(iterable).__name__, str(iterable)), 1)
590+
CommonUtil.ExecLog(sModuleInfo, "Looping through a %s: %s" % (type(iterable).__name__, str(iterable)), 1)
591591
elif row[0].strip().lower().startswith("exit loop"):
592592
if not row[2].lower().startswith("if"):
593593
CommonUtil.ExecLog(
@@ -2135,6 +2135,7 @@ def Action_Handler(_data_set, action_row, _bypass_bug=True):
21352135
return "zeuz_failed"
21362136

21372137
module, function, original_module, screenshot = common.get_module_and_function(action_name, action_subfield) # New, get the module to execute
2138+
CommonUtil.prettify_limit = sr.Get_Shared_Variables("zeuz_prettify_limit")
21382139

21392140
if module in failed_tag_list or module == "" or function == "": # New, make sure we have a function
21402141
CommonUtil.ExecLog(sModuleInfo, "You probably didn't add the module as part of the action. Eg: appium action", 3)
@@ -2157,11 +2158,16 @@ def Action_Handler(_data_set, action_row, _bypass_bug=True):
21572158
data_set = []
21582159
for row in _data_set:
21592160
new_row = list(row)
2160-
if row[1].strip().lower() in ("optional parameter", "optional option") and row[0].strip().lower() in ("screen capture", "screenshot", "ss"):
2161-
screenshot = row[2].strip().lower()
2162-
if screenshot in ("false", "no", "none", "disable"):
2163-
screenshot = "none"
2164-
continue
2161+
if row[1].strip().lower() in ("optional parameter", "optional option"):
2162+
if row[0].strip().lower() in ("screen capture", "screenshot", "ss"):
2163+
screenshot = row[2].strip().lower()
2164+
if screenshot in ("false", "no", "none", "disable"):
2165+
screenshot = "none"
2166+
continue
2167+
if row[0].replace(" ", "").lower() in ("prettifylimit"):
2168+
CommonUtil.prettify_limit = CommonUtil.parse_value_into_object(row[2].split(" ")[-1])
2169+
continue
2170+
21652171
if "optional" in row[1]:
21662172
new_row[1] = new_row[1].replace("optional", "").strip()
21672173
if "bypass" in row[1]:

Framework/Built_In_Automation/Shared_Resources/LocateElement.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ def Get_Element(step_data_set, driver, query_debug=False, return_all_elements=Fa
219219
pass
220220
if save_parameter != "": # save element to a variable
221221
sr.Set_Shared_Variables(save_parameter, result)
222+
sr.Set_Shared_Variables("zeuz_element", result)
222223
return result # Return on pass
223224
elif result == "zeuz_failed":
224225
try:

Framework/Built_In_Automation/Web/Selenium/BuiltInFunctions.py

Lines changed: 73 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,31 @@
8282
selenium_details = {}
8383
default_x, default_y = 1920, 1080
8484

85+
# JavaScript for collecting First Contentful Paint value.
86+
JS_FCP = '''
87+
return performance.getEntriesByName("first-contentful-paint")[0].startTime
88+
'''
89+
90+
# JavaScript for collecting Largest Contentful Paint value.
91+
JS_LCP = '''
92+
var args = arguments;
93+
const po = new PerformanceObserver(list => {
94+
const entries = list.getEntries();
95+
const entry = entries[entries.length - 1];
96+
// Process entry as the latest LCP candidate
97+
// LCP is accurate when the renderTime is available.
98+
// Try to avoid this being false by adding Timing-Allow-Origin headers!
99+
const accurateLCP = entry.renderTime ? true : false;
100+
// Use startTime as the LCP timestamp. It will be renderTime if available, or loadTime otherwise.
101+
const largestPaintTime = entry.startTime;
102+
// Send the LCP information for processing.
103+
104+
console.log("[ZeuZ Node] Largest Contentful Paint: ", largestPaintTime);
105+
args[0](largestPaintTime);
106+
});
107+
po.observe({ type: 'largest-contentful-paint', buffered: true });
108+
'''
109+
85110
# if Shared_Resources.Test_Shared_Variables('selenium_driver'): # Check if driver is already set in shared variables
86111
# selenium_driver = Shared_Resources.Get_Shared_Variables('selenium_driver') # Retreive appium driver
87112

@@ -387,6 +412,7 @@ def get_performance_metrics(dataset):
387412
metrics = selenium_details[driver_id]["driver"].execute_cdp_cmd('Performance.getMetrics', {})
388413
perf_json_data = {data["name"]: data["value"] for data in metrics["metrics"]}
389414
Shared_Resources.Set_Shared_Variables(var_name,perf_json_data)
415+
CommonUtil.browser_perf[current_driver_id].append(perf_json_data)
390416
return "passed"
391417
except:
392418
return CommonUtil.Exception_Handler(sys.exc_info())
@@ -975,15 +1001,28 @@ def Go_To_Link(step_data, page_title=False):
9751001
except Exception:
9761002
ErrorMessage = "failed to open your link: %s" % (web_link)
9771003
return CommonUtil.Exception_Handler(sys.exc_info(), None, ErrorMessage)
1004+
1005+
# Collect custom performance metrics
9781006
try:
9791007
if current_driver_id not in CommonUtil.browser_perf:
9801008
metrics = selenium_driver.execute_cdp_cmd('Performance.getMetrics', {})
9811009
metrics_dict = {data["name"]: data["value"] for data in metrics["metrics"]}
1010+
1011+
# FCP - First Contentful Paint
9821012
try:
983-
metrics_dict["first-contentful-paint"] = selenium_driver.execute_script('return performance.getEntriesByName("first-contentful-paint")[0].startTime')
1013+
metrics_dict["first-contentful-paint"] = selenium_driver.execute_script(JS_FCP)
9841014
except:
9851015
metrics_dict["first-contentful-paint"] = 0
1016+
1017+
# LCP - Largest Contenful Paint
1018+
try:
1019+
metrics_dict["largest-contentful-paint"] = selenium_driver.execute_async_script(JS_LCP)
1020+
except:
1021+
metrics_dict["largest-contentful-paint"] = 0
1022+
9861023
CommonUtil.browser_perf[current_driver_id] = [metrics_dict]
1024+
1025+
# CommonUtil.prettify(key="metrics", val=metrics_dict)
9871026
return "passed"
9881027
except:
9891028
return CommonUtil.Exception_Handler(sys.exc_info())
@@ -1167,7 +1206,7 @@ def Enter_Text_In_Text_Box(step_data):
11671206
selenium_driver.execute_script("arguments[0].click();", Element)
11681207
else:
11691208
try:
1170-
handle_clickability_and_click(step_data, Element)
1209+
Element = handle_clickability_and_click(step_data, Element)
11711210
except:
11721211
CommonUtil.ExecLog(sModuleInfo, "Entering text without clicking the element", 2)
11731212
if clear:
@@ -1358,28 +1397,38 @@ def execute_javascript(data_set):
13581397

13591398
def handle_clickability_and_click(dataset, Element:selenium.webdriver.remote.webelement.WebElement):
13601399
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
1361-
wait_clickable = 0
1362-
for left, mid, right in dataset:
1363-
if mid.strip().lower() == "option":
1364-
left = left.strip().lower()
1365-
if "wait" in left and "clickable" in left:
1366-
wait_clickable = int(right.strip())
1367-
if not wait_clickable:
1368-
Element.click() # no need of try except here. we need to return the exact exception upto this point
1369-
else:
1370-
log_flag = True
1371-
start = time.time()
1372-
while True:
1373-
try:
1374-
Element.click()
1375-
break
1376-
except ElementClickInterceptedException:
1377-
if log_flag:
1378-
CommonUtil.ExecLog(sModuleInfo, "The Element is overlapped. Waiting %s seconds max for the element to become clickable" % wait_clickable, 2)
1379-
log_flag = False
1380-
if time.time() > start + wait_clickable:
1381-
raise Exception # not ElementClickInterceptedException. we dont want js to perform click
1382-
1400+
wait_clickable = Shared_Resources.Get_Shared_Variables("element_wait")
1401+
# for left, mid, right in dataset:
1402+
# if mid.strip().lower() == "option":
1403+
# left = left.strip().lower()
1404+
# if "wait" in left and "clickable" in left:
1405+
# wait_clickable = int(right.strip())
1406+
# if not wait_clickable:
1407+
# Element.click() # no need of try except here. we need to return the exact exception upto this point
1408+
# else:
1409+
log_flag = True
1410+
log_flag2 = True
1411+
start = time.perf_counter()
1412+
stale_i = 0
1413+
while True:
1414+
try:
1415+
Element.click()
1416+
CommonUtil.ExecLog(sModuleInfo, "Element has become clickable after %s seconds" % round(time.perf_counter() - start, 2), 2)
1417+
return Element
1418+
except ElementClickInterceptedException:
1419+
if log_flag:
1420+
CommonUtil.ExecLog(sModuleInfo, "Click is Intercepted. Waiting %s seconds max for the element to become clickable" % wait_clickable, 2)
1421+
log_flag = False
1422+
except StaleElementReferenceException:
1423+
if log_flag2:
1424+
CommonUtil.ExecLog(sModuleInfo, "Element is stale. Waiting %s seconds max for the element to become clickable" % wait_clickable, 2)
1425+
log_flag2 = False
1426+
Element = LocateElement.Get_Element(dataset, selenium_driver) # Element may need to be relocated in stale
1427+
if stale_i == 0:
1428+
stale_i += 1
1429+
continue
1430+
if time.perf_counter() > start + wait_clickable:
1431+
raise Exception # not StaleElementReferenceException. we don't want js to perform click
13831432

13841433
# Method to click on element; step data passed on by the user
13851434
@logger

Framework/MainDriverApi.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -867,6 +867,10 @@ def run_test_case(
867867
TestCaseName = testcase_info["title"]
868868
shared.Set_Shared_Variables("zeuz_current_tc", testcase_info, print_variable=False, pretty=False)
869869
shared.Set_Shared_Variables("zeuz_auto_teardown", "on")
870+
if not CommonUtil.debug_status or not shared.Test_Shared_Variables("zeuz_prettify_limit"):
871+
shared.Set_Shared_Variables("zeuz_prettify_limit", None)
872+
CommonUtil.prettify_limit = None
873+
870874
# shared.Set_Shared_Variables("zeuz_automation_log", Path(temp_ini_file).parent.__str__())
871875
shared.Set_Shared_Variables("zeuz_attachments_dir", (Path(temp_ini_file).parent/"attachments").__str__())
872876
if not shared.Test_Shared_Variables("element_wait"):

Framework/Utilities/CommonUtil.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@
106106
previous_log_line = None
107107
teardown = True
108108
print_execlog = True
109+
prettify_limit = None
109110

110111
step_module_name = None
111112

@@ -216,17 +217,22 @@ def prettify(key, val):
216217
"""Tries to pretty print the given value."""
217218
color = Fore.MAGENTA
218219
try:
219-
if type(val) == str:
220-
val = parse_value_into_object(val)
221-
print(color + "%s = " % (key), end="")
222-
print_json(data=val)
223-
expression = "%s = %s" % (key, json.dumps(val, indent=2, sort_keys=True))
220+
if prettify_limit is None:
221+
if type(val) == str:
222+
val = parse_value_into_object(val)
223+
print(color + "%s = " % (key), end="")
224+
print_json(data=val)
225+
else:
226+
print(color + "%s = " % (key), end="")
227+
print(json.dumps(val,indent=2)[:prettify_limit])
228+
229+
expression = "%s = %s" % (key, json.dumps(val, indent=2, sort_keys=True)[:prettify_limit])
224230
if debug_status and key not in dont_prettify_on_server:
225231
live_log_service.log("VARIABLE", 4, expression.replace("\n", "<br>").replace(" ", "&nbsp;"))
226232
# 4 means console log which is Magenta color in server console
227233
except:
228234
# expression = "%s" % (key, val)
229-
print(color + str(val))
235+
print(color + str(val)[:prettify_limit])
230236
if debug_status and key not in dont_prettify_on_server:
231237
live_log_service.log("VARIABLE", 4, str(val).replace("\n", "<br>").replace(" ", "&nbsp;"))
232238

0 commit comments

Comments
 (0)