Repository navigation
Expand file tree
/
Copy pathMainDriverApi.py
More file actions
2316 lines (2021 loc) · 96.2 KB
/
Copy pathMainDriverApi.py
File metadata and controls
2316 lines (2021 loc) · 96.2 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 -*-
import asyncio
import concurrent.futures
import copy
import json
import inspect
import os
import time
import sys
from typing import Any, Dict
from urllib.parse import urlparse
import urllib.request, urllib.error, urllib.parse
import queue
import shutil
import importlib
import requests
import zipfile
from multiprocessing.pool import ThreadPool
from urllib3.exceptions import InsecureRequestWarning
import pyperclip
# Suppress the InsecureRequestWarning since we use verify=False parameter.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
import threading
import subprocess
from pathlib import Path, PurePosixPath
from sys import platform as _platform
from datetime import datetime
from datetime import timedelta
import pytz
from threading import Timer
from Framework.attachment_db import AttachmentDB, GlobalAttachment
from Framework.Built_In_Automation import Shared_Resources
from .Utilities import ConfigModule, FileUtilities as FL, CommonUtil, RequestFormatter
from Framework.Built_In_Automation.Shared_Resources import (
BuiltInFunctionSharedResources as shared,
)
from settings import PROJECT_ROOT
from reporting import junit_report
from genson import SchemaBuilder
import selenium
from rich.style import Style
from rich.table import Table
from rich.console import Console
from rich.box import ASCII_DOUBLE_HEAD, DOUBLE
from rich.padding import Padding
from jinja2 import Environment, FileSystemLoader
from time import sleep
rich_print = Console().print
top_path = os.path.dirname(os.getcwd())
drivers_path = os.path.join(top_path, "Drivers")
sys.path.append(drivers_path)
MODULE_NAME = inspect.getmodulename(__file__)
"""Constants"""
PROGRESS_TAG = "In-Progress"
PASSED_TAG = "Passed"
FAILED_TAG = "zeuz_failed"
BLOCKED_TAG = "Blocked"
CANCELLED_TAG = "Cancelled"
COMPLETE_TAG = "Complete"
passed_tag_list = [
"Pass",
"pass",
"PASS",
"PASSED",
"Passed",
"passed",
"true",
"TRUE",
"True",
"1",
"Success",
"success",
"SUCCESS",
]
failed_tag_list = [
"Fail",
"fail",
"FAIL",
"zeuz_failed",
"false",
"False",
"FALSE",
"0",
]
device_info = {}
# if other linked machine failed in a linked run
failed_due_to_linked_fail = False
def post_runid_cleanup():
"""Run node cleanup tasks that should execute after each run_id."""
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
try:
from Framework.Built_In_Automation.Web.Selenium.utils import (
ChromeExtensionDownloader,
ChromeForTesting,
)
ChromeForTesting().cleanup_old_versions()
ChromeExtensionDownloader().cleanup_extensions()
CommonUtil.ExecLog(
sModuleInfo,
"Completed post run_id cleanup for Chrome for Testing and Chrome extensions.",
1,
)
except Exception:
CommonUtil.ExecLog(
sModuleInfo,
"Post run_id cleanup failed. Continuing execution.",
2,
)
CommonUtil.debug_code_error(sys.exc_info())
# sets server variable
# TODO: remove, need alternative
def set_server_variable(run_id, key, value):
return RequestFormatter.Get(
"set_server_variable_api", {"run_id": run_id, "var_name": key, "var_val": value}
)
# gets server variable
# TODO: remove, need alternative
def get_server_variable(run_id, key):
return RequestFormatter.Get(
"get_server_variable_api", {"run_id": run_id, "var_name": key}
)
# get global list variable
# TODO: remove, need alternative
def get_global_list_variable(name):
return RequestFormatter.Get(
"set_or_get_global_server_list_variable_api", {"name": name}
)
# append to global list variable
# TODO: remove, need alternative
def append_to_global_list_variable(name, value):
return RequestFormatter.Get(
"append_value_to_global_server_list_variable_api",
{"name": name, "value": value},
)
# remove item from global list variable
# TODO: remove, need alternative
def remove_item_from_global_list_variable(name, value):
return RequestFormatter.Get(
"delete_global_server_list_variable_by_value_api",
{"name": name, "value": value},
)
# get all server variable
# TODO: remove, need alternative
def get_all_server_variable(run_id):
return RequestFormatter.Get("get_all_server_variable_api", {"run_id": run_id})
# if run is cancelled then it can be called, it cleans up the runid from database
# TODO: remove, unnecessary
def cleanup_runid_from_server(run_id):
RequestFormatter.Get("clean_up_run_api", {"run_id": run_id})
# returns current status of the runid
# TODO: remove, unnecessary
def get_status_of_runid(run_id):
return RequestFormatter.Get("get_status_of_a_run_api", {"run_id": run_id})
# TODO: Remove
def check_if_other_machines_failed_in_linked_run():
# can get multiple server variable with one action
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
try:
run_id = shared.Get_Shared_Variables("run_id")
dict = get_all_server_variable(run_id)
try:
if (
"is_failed" in dict
and dict["is_failed"] != "null"
and dict["is_failed"] == "yes"
):
global failed_due_to_linked_fail
failed_machine = ""
if "failed_machine" in dict:
failed_machine = dict["failed_machine"]
if failed_machine == (CommonUtil.MachineInfo().getLocalUser()).lower():
return "passed"
failed_due_to_linked_fail = True
failed_test_case = ""
if "failed_test_case" in dict:
failed_test_case = dict["failed_test_case"]
CommonUtil.ExecLog(
sModuleInfo,
"Linked test case '%s' failed in machine '%s'.. Test Case Failed..."
% (failed_test_case, failed_machine),
3,
)
return "zeuz_failed"
else:
time.sleep(1)
except:
pass
return "passed"
except Exception:
return CommonUtil.Exception_Handler(sys.exc_info())
# downloads attachments for a test case
def create_tc_log_ss_folder(run_id, test_case, temp_ini_file, server_version):
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
try:
log_file_path = ConfigModule.get_config_value(
"sectionOne", "temp_run_file_path", temp_ini_file
)
except Exception:
return CommonUtil.Exception_Handler(sys.exc_info())
run_id_folder = str(Path(log_file_path)/run_id.replace(":", "-"))
test_case_folder = str(Path(run_id_folder)/CommonUtil.current_session_name/test_case.replace(":", "-"))
# TODO: Use pathlib for following items
# create test_case_folder
ConfigModule.add_config_value("sectionOne", "test_case", test_case, temp_ini_file)
ConfigModule.add_config_value("sectionOne", "test_case_folder", test_case_folder, temp_ini_file)
FL.CreateFolder(test_case_folder)
# create log_folder for browser console error logs
log_folder = test_case_folder + os.sep + "Log"
ConfigModule.add_config_value("sectionOne", "log_folder", log_folder, temp_ini_file)
FL.CreateFolder(log_folder)
# create screenshot_folder
screenshot_folder = test_case_folder + os.sep + "screenshots"
ConfigModule.add_config_value("sectionOne", "screen_capture_folder", screenshot_folder, temp_ini_file)
FL.CreateFolder(screenshot_folder)
# performance report folder
performance_report = test_case_folder + os.sep + "performance_report"
ConfigModule.add_config_value("sectionOne", "performance_report", performance_report, temp_ini_file)
FL.CreateFolder(performance_report)
# TODO: we'll be breaking internal server compatibility anyway
# ! This will be unnecessary
if float(server_version.split(".")[0]) >= 7:
# json report folder
json_report = test_case_folder + os.sep + "json_report"
ConfigModule.add_config_value("sectionOne", "json_report", json_report, temp_ini_file)
FL.CreateFolder(json_report)
# create where attachments from selenium browser will be
# downloaded
# ? Why are we keeping two separate download folders?
zeuz_download_folder = test_case_folder + os.sep + "zeuz_download_folder"
FL.CreateFolder(zeuz_download_folder)
initial_download_folder = run_id_folder + os.sep + "initial_download_folder"
FL.CreateFolder(initial_download_folder)
ConfigModule.add_config_value("sectionOne", "initial_download_folder", initial_download_folder, temp_ini_file)
shared.Set_Shared_Variables("zeuz_download_folder", zeuz_download_folder)
# ? Can't we run the above folder creation codes only once when
# the node starts or when main driver is called for the first
# time?
# Store the attachments for each test case separately inside
# AutomationLog/attachments/TEST-XYZ
download_folder = str(Path(log_file_path) / "attachments" / test_case.replace(":", "-"))
ConfigModule.add_config_value("sectionOne", "download_folder", download_folder, temp_ini_file)
import ctypes
def terminate_thread(thread): # To kill running thread
"""Terminates a python thread from another thread.
:param thread: a threading.Thread instance
"""
if not thread.is_alive():
return
exc = ctypes.py_object(SystemExit)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(thread.ident), exc)
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
# call the function of a test step that is in its driver file
def call_driver_function_of_test_step(
sModuleInfo,
all_step_info,
StepSeq,
step_time,
current_step_name,
test_steps_data,
test_action_info,
debug_actions=None
):
try:
q = queue.Queue() # define queue
# get step driver
current_driver = all_step_info[StepSeq-1]["step_driver_type"]
# current_driver = "Built_In_Driver"
try:
current_driver = "Drivers." + current_driver
# if CommonUtil.step_module_name is None:
module_name = importlib.import_module(current_driver) # get module
# get step name
if all_step_info[StepSeq-1]["step_function"]:
step_name = all_step_info[StepSeq-1]["step_function"].strip()
else:
step_name = current_step_name
step_name = step_name.lower().replace(" ", "_")
# step_name = "sequential_actions"
try:
# importing functions from driver
functionTocall = getattr(module_name, step_name)
except Exception as e:
CommonUtil.Exception_Handler(
sys.exc_info(),
None,
"Could not find function name: %s in Driver/%s.py. Perhaps you need to add a custom driver or add an alias step to the Test Step."
% (step_name, current_driver),
)
return "zeuz_failed"
try:
simple_queue = queue.Queue()
screen_capture = "Desktop" # No need of screen capture. Need to delete this
def invoke_step(*args):
result = functionTocall(*args)
if inspect.iscoroutine(result):
return asyncio.run(result)
return result
# run in thread
if ConfigModule.get_config_value("RunDefinition", "threading") in passed_tag_list:
stepThread = threading.Thread(
target=invoke_step,
args=(
test_steps_data,
test_action_info,
simple_queue,
debug_actions,
),
) # start step thread
CommonUtil.ExecLog(sModuleInfo, "Starting Test Step Thread..", 1) # add log
# start thread
stepThread.start()
# Wait for the Thread to finish or until timeout
CommonUtil.ExecLog(
sModuleInfo,
"Waiting for Test Step Thread to finish..for (seconds) :%d"
% step_time,
1,
)
stepThread.join(float(step_time))
try:
sStepResult = simple_queue.get_nowait()
# Get the return value from the ExecuteTestStep
# fn via Queue
q.put(sStepResult)
CommonUtil.ExecLog(sModuleInfo, "Test Step Thread Ended..", 1)
except queue.Empty:
# Global.DefaultTestStepTimeout
ErrorMessage = "Test Step didn't return after %d seconds" % step_time
CommonUtil.Exception_Handler(sys.exc_info(), None, ErrorMessage)
sStepResult = "zeuz_failed"
q.put(sStepResult)
# Clean up
if stepThread.is_alive():
CommonUtil.ExecLog(sModuleInfo, "Timeout Error", 3)
# stepThread.__stop()
try:
# stepThread._Thread__stop()
terminate_thread(stepThread)
while stepThread.is_alive():
time.sleep(1)
CommonUtil.ExecLog(sModuleInfo, "Thread is still alive", 2)
except:
CommonUtil.Exception_Handler(sys.exc_info())
else:
# run sequentially
sStepResult = invoke_step(
test_steps_data,
test_action_info,
simple_queue,
debug_actions,
)
except:
CommonUtil.Exception_Handler(sys.exc_info()) # handle exceptions
sStepResult = "zeuz_failed"
# get step result
if sStepResult in passed_tag_list:
sStepResult = "PASSED"
elif sStepResult in failed_tag_list:
sStepResult = "zeuz_failed".upper()
else:
CommonUtil.ExecLog(sModuleInfo, "sStepResult not an acceptable type", 3)
CommonUtil.ExecLog(sModuleInfo, "Acceptable pass string(s): %s" % passed_tag_list, 3)
CommonUtil.ExecLog(sModuleInfo, "Acceptable fail string(s): %s" % failed_tag_list, 3)
sStepResult = "zeuz_failed"
q.put(sStepResult)
except Exception as e:
CommonUtil.Exception_Handler(sys.exc_info())
sStepResult = "zeuz_failed"
return sStepResult
except Exception:
CommonUtil.Exception_Handler(sys.exc_info())
return "zeuz_failed"
# runs all test steps of a test case
def run_all_test_steps_in_a_test_case(
testcase_info,
test_case,
sModuleInfo,
run_id,
temp_ini_file,
debug_info,
performance=False
):
try:
StepSeq = 1
CommonUtil.step_index = 0
sTestStepResultList = []
already_failed = False
Stepscount = len(testcase_info["steps"]) # no. of steps
debug_steps = ""
debug = False
cleanup_drivers_during_debug = False
debug_actions = ""
if run_id.startswith("debug"):
debug = True
debug_steps = debug_info["debug_steps"]
if "debug_step_actions" in debug_info:
debug_actions = debug_info["debug_step_actions"]
if not debug_steps:
debug_steps = []
if not debug_actions:
debug_actions = []
# performance testing
if performance:
StepSeq = 2
CommonUtil.step_index = 1
sTestStepResultList.append("PASSED")
# Creating Testcase attachment variables
attachment_path = Path(ConfigModule.get_config_value("sectionOne", "temp_run_file_path", temp_ini_file)) / "attachments"
tc_attachment_list = []
for tc_attachment in testcase_info['attachments']:
var_name = PurePosixPath(tc_attachment["path"]).name
path = str(attachment_path / tc_attachment["id"] / var_name)
tc_attachment_list.append(var_name)
shared.Set_Shared_Variables(var_name, path, attachment_var=True)
all_step_info = testcase_info["steps"]
all_step_dataset, all_action_info, step_attachment_list = [], [], []
for step_info in all_step_info:
all_Action_info = step_info["actions"]
all_action_data_set, all_action_Info = [], []
for action_info in all_Action_info:
action_dataset = action_info["step_actions"]
all_action_data_set.append(action_dataset)
Dict = {}
Dict["Action disabled"] = action_info["action_disabled"]
Dict["Action name"] = action_info["action_name"]
all_action_Info.append(Dict)
all_step_dataset.append(all_action_data_set)
all_action_info.append(all_action_Info)
step_attachments = step_info['attachments']
step_attachment_list = []
for attachment in step_attachments:
attachment_name = PurePosixPath(attachment["path"]).name
path = str(attachment_path / f"STEP-{attachment['id']}" / attachment_name)
step_attachment_list.append(attachment_name)
shared.Set_Shared_Variables(attachment_name, path, attachment_var=True)
while StepSeq <= Stepscount:
CommonUtil.custom_step_duration = ""
this_step = all_step_info[StepSeq - 1]
if debug and debug_steps:
if str(StepSeq) not in debug_steps:
StepSeq += 1
CommonUtil.step_index += 1
continue
# check if already failed
if already_failed:
if this_step["always_run"]:
CommonUtil.ExecLog(
sModuleInfo,
"Step-%s is set as 'Always run' so executing this step" % (CommonUtil.step_index + 1),
2,
)
# TODO: Revisit the todo on the right
elif "run_on_fail" in this_step and this_step["run_on_fail"]: # Todo: Remove the 1st condition when all servers are updated
CommonUtil.ExecLog(
sModuleInfo,
"Step-%s is set as 'Run on fail' and the test case has already failed so executing this step" % (CommonUtil.step_index + 1),
2,
)
else:
StepSeq += 1
CommonUtil.step_index += 1
continue
elif not already_failed and "run_on_fail" in this_step and this_step["run_on_fail"]: # Todo: Remove the 2nd condition when all servers are updated
CommonUtil.ExecLog(
sModuleInfo,
"Step-%s is set as 'Run on fail' and the test case has not failed yet so skipping this step" % (CommonUtil.step_index + 1),
2,
)
StepSeq += 1
CommonUtil.step_index += 1
continue
CommonUtil.current_step_name = current_step_name = this_step["step_name"]
CommonUtil.current_step_id = current_step_id = this_step["step_id"]
CommonUtil.current_step_sequence = current_step_sequence = this_step["step_sequence"]
shared.Set_Shared_Variables("zeuz_current_step_name", current_step_name, print_variable=False, pretty=False)
shared.Set_Shared_Variables("zeuz_current_step_sequence", current_step_sequence, print_variable=False, pretty=False)
shared.Set_Shared_Variables("zeuz_total_step_count", len(all_step_info), print_variable=False, pretty=False)
shared.Set_Shared_Variables("zeuz_current_step", this_step, print_variable=False, pretty=False)
ConfigModule.add_config_value(
"sectionOne",
"sTestStepExecLogId",
run_id + "|" + test_case + "|" + str(current_step_id) + "|" + str(current_step_sequence),
temp_ini_file,
)
CommonUtil.current_step_no = str(current_step_sequence)
_color = "yellow"
# _style = Style(color="yellow", blink=False, bold=True)
table = Table(border_style=_color, box=ASCII_DOUBLE_HEAD, expand=False)
table.add_column(
f"ID",
justify="center",
style=_color,
max_width=5,
)
table.add_column(
f"STEP #{StepSeq}",
justify="center",
style=_color,
max_width=40,
)
table.add_column(
f"Always run",
justify="center",
style=_color,
min_width=6,
max_width=6,
)
table.add_column(
f"Type",
justify="center",
style=_color,
max_width=6,
)
table.add_row(
f"{this_step['step_id']}",
f"{current_step_name}",
f"{this_step['always_run']}",
"global" if this_step['type'] == "linked" else "local",
style=_color,
)
# width_pad = CommonUtil.max_char // 2 - (max(len(current_step_name), 6) + 4) // 2
# table = Padding(table, (0, width_pad))
rich_print(table)
test_steps_data = all_step_dataset[StepSeq-1]
test_action_info = all_action_info[StepSeq-1]
CommonUtil.all_step_dataset = all_step_dataset
CommonUtil.all_action_info = all_action_info
# FIXME: If either one of run on fail or step time throws an
# exception, both values will be set to a default value. So it has
# the possibility to ignore one of the other correct values.
try:
test_case_continue = this_step["continue_on_fail"]
step_time = this_step["step_time"]
if str(step_time) != "" and step_time is not None:
step_time = int(step_time)
else:
step_time = 59
except:
test_case_continue = False
step_time = 59
# get step start time
TestStepStartTime = time.perf_counter()
sTestStepStartTime = datetime.fromtimestamp(TestStepStartTime, tz=pytz.UTC).strftime("%Y-%m-%d %H:%M:%S.%f")
WinMemBegin = CommonUtil.PhysicalAvailableMemory() # get available memory
if StepSeq in CommonUtil.disabled_step or not this_step['step_enable']:
CommonUtil.ExecLog(sModuleInfo, "STEP-%s is disabled" % StepSeq, 2)
sStepResult = "skipped"
elif CommonUtil.testcase_exit:
CommonUtil.ExecLog(sModuleInfo, "STEP-%s is skipped" % StepSeq, 2)
sStepResult = "skipped"
else:
sStepResult = call_driver_function_of_test_step(
sModuleInfo,
all_step_info,
StepSeq,
step_time,
current_step_name,
test_steps_data,
test_action_info,
debug_actions,
)
TestStepEndTime = time.perf_counter()
sTestStepEndTime = datetime.fromtimestamp(TestStepEndTime, tz=pytz.UTC).strftime("%Y-%m-%d %H:%M:%S.%f")
WinMemEnd = CommonUtil.PhysicalAvailableMemory() # get available memory
CommonUtil.step_perf.append({
"id": current_step_id,
"name": current_step_name,
"sequence": current_step_sequence,
"runtime": round(TestStepEndTime - TestStepStartTime, 5),
"time_stamp": CommonUtil.get_timestamp(),
"status": sStepResult,
})
if CommonUtil.custom_step_duration:
TestStepDuration = CommonUtil.custom_step_duration
CommonUtil.custom_step_duration = ""
else:
sec = TestStepEndTime - TestStepStartTime
hours, remainder = sec // 3600, sec % 3600
minutes, seconds = remainder // 60, remainder % 60
TestStepDuration = "%02d:%02d:%s" % (hours, minutes, round(seconds, 3))
TestStepMemConsumed = WinMemBegin - WinMemEnd # get memory consumed
# for i in step_attachment_list: shared.Remove_From_Shared_Variables(i, attachment_var=True) # Cleanup step_attachment variables
if sStepResult:
sTestStepResultList.append(sStepResult.upper())
else:
sTestStepResultList.append("zeuz_failed")
CommonUtil.ExecLog(sModuleInfo, "sStepResult : %s" % sStepResult, 1) # add log
sStepResult = "zeuz_failed"
# step dictionary after execution
after_execution_dict = {
"stepstarttime": sTestStepStartTime,
"stependtime": sTestStepEndTime,
"end_memory": WinMemEnd,
"duration": TestStepDuration,
"memory_consumed": TestStepMemConsumed,
"logid": ConfigModule.get_config_value("sectionOne", "sTestStepExecLogId", temp_ini_file)
}
if sStepResult.upper() == PASSED_TAG.upper():
# Step Passed
CommonUtil.ExecLog(sModuleInfo, "%s : Test Step Passed" % current_step_name, 1)
after_execution_dict.update({"status": PASSED_TAG})
elif sStepResult.upper() == "SKIPPED":
CommonUtil.ExecLog(sModuleInfo, "%s : Test Step Skipped" % current_step_name, 2)
after_execution_dict.update({"status": "Skipped"})
else:
CommonUtil.ExecLog(sModuleInfo, "%s%s" % (current_step_name, CommonUtil.to_dlt_from_fail_reason), 3)
after_execution_dict.update({"status": "Failed"}) # dictionary update
# check if set for continue
if not test_case_continue:
already_failed = True
elif test_case_continue and CommonUtil.step_index + 1 < len(all_step_info):
CommonUtil.ExecLog(
sModuleInfo,
"Step-%s is set as 'Continue on fail' so continuing to next step" % (CommonUtil.step_index + 1),
2
)
CommonUtil.CreateJsonReport(stepInfo=after_execution_dict)
executor = concurrent.futures.ThreadPoolExecutor()
thr = executor.submit(upload_step_report, run_id, test_case, this_step["step_sequence"], this_step["step_id"], after_execution_dict)
CommonUtil.SaveThread("step_report", thr)
executor.shutdown(wait=False)
StepSeq += 1
CommonUtil.step_index += 1
if CommonUtil.run_cancel == CANCELLED_TAG:
CommonUtil.ExecLog(sModuleInfo, "Test Run status is Cancelled. Exiting the current Test Case...%s" % test_case, 2)
CommonUtil.run_cancelled = True
break
for i in tc_attachment_list: shared.Remove_From_Shared_Variables(i, attachment_var=True) # Cleanup tc_attachment variables
CommonUtil.show_log = True
return sTestStepResultList
except:
CommonUtil.Exception_Handler(sys.exc_info())
raise Exception
# from the returned step results, it finds out the test case result
def calculate_test_case_result(sModuleInfo, TestCaseID, run_id, sTestStepResultList, testcase_info):
if CommonUtil.testcase_exit:
CommonUtil.ExecLog(sModuleInfo, f"Test Case {CommonUtil.testcase_exit}", 1)
return CommonUtil.testcase_exit
elif "BLOCKED" in sTestStepResultList:
CommonUtil.ExecLog(sModuleInfo, "Test Case Blocked", 3)
return "Blocked"
elif "CANCELLED" in sTestStepResultList or "Cancelled" in sTestStepResultList:
CommonUtil.ExecLog(sModuleInfo, "Test Case Cancelled", 3)
return "Cancelled"
elif "zeuz_failed".upper() in sTestStepResultList:
step_index = 0
for each in sTestStepResultList:
if each == "zeuz_failed".upper():
if testcase_info["steps"][step_index]["verify_point"]:
sTestCaseStatus = "Failed"
break
step_index += 1
else:
sTestCaseStatus = "Blocked"
CommonUtil.ExecLog(sModuleInfo, "Test Case " + sTestCaseStatus, 3)
return sTestCaseStatus
elif "WARNING" in sTestStepResultList:
CommonUtil.ExecLog(sModuleInfo, "Test Case Contain Warning(s)", 2)
return "Failed"
elif "NOT RUN" in sTestStepResultList:
CommonUtil.ExecLog(sModuleInfo, "Test Case Contain Not Run Steps", 2)
return "Failed"
elif all([i == "SKIPPED" for i in sTestStepResultList]):
CommonUtil.ExecLog(sModuleInfo, "Test Case Skipped", 1)
return "Skipped"
elif "PASSED" in sTestStepResultList:
CommonUtil.ExecLog(sModuleInfo, "Test Case Passed", 1)
return "Passed"
else:
CommonUtil.ExecLog(sModuleInfo, "Test Case Status Unknown", 2)
return "Unknown"
# writes the log file for a test case
def zip_and_delete_tc_folder(
run_id,
TestCaseID,
sTestCaseStatus,
temp_ini_file,
send_log_file_only_for_fail=True,
):
# if settings checked, then send log file or screenshots, otherwise don't send
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
if sTestCaseStatus not in passed_tag_list or sTestCaseStatus in passed_tag_list and not send_log_file_only_for_fail:
if ConfigModule.get_config_value("RunDefinition", "local_run") == "False":
all_steps = CommonUtil.all_logs_json[CommonUtil.runid_index]["test_cases"][CommonUtil.tc_index]["steps"]
for step in all_steps:
json_filename = Path(ConfigModule.get_config_value("sectionOne", "json_report", temp_ini_file))/(str(step["step_sequence"])+".json")
with open(json_filename, "w", encoding="utf-8") as f:
json.dump(step, f)
zip_name = run_id.replace(":", "-") + "_" + TestCaseID.replace(":", "-") + ".zip"
FL.ZipFolder(
ConfigModule.get_config_value("sectionOne", "test_case_folder", temp_ini_file),
str(Path(ConfigModule.get_config_value("sectionOne", "test_case_folder", temp_ini_file)).parent/zip_name),
)
# Delete the folder
path = ConfigModule.get_config_value("sectionOne", "test_case_folder", temp_ini_file)
CommonUtil.ExecLog(sModuleInfo, f"Deleting folder: {path}", 5)
FL.DeleteFolder(path)
def cleanup_driver_instances(): # cleans up driver(selenium, appium) instances
try: # if error happens. we don't care, main driver should not stop, pass in exception
import Framework.Built_In_Automation.Web.Selenium.BuiltInFunctions as Selenium
try:
Selenium.Tear_Down_Selenium()
except:
pass
if shared.Test_Shared_Variables("playwright_page"):
try:
from Framework.Built_In_Automation.Sequential_Actions import sequential_actions
from Framework.Built_In_Automation.Web.Playwright import BuiltInFunctions as Playwright
sequential_actions._run_action_with_timeout(Playwright.Tear_Down_Selenium, [])
except Exception:
pass
if shared.Test_Shared_Variables("appium_details"):
import Framework.Built_In_Automation.Mobile.CrossPlatform.Appium.BuiltInFunctions as Appium
driver = shared.Remove_From_Shared_Variables("appium_details")
if driver not in failed_tag_list:
Appium.teardown_appium()
except:
pass
def _normalize_auto_teardown_mode(value):
value = str(value).strip().lower()
if value in ("off", "no", "false", "disable"):
return "off"
if value in ("on_run_end", "on_run_start_and_end"):
return value
return "on"
def _auto_teardown_mode():
return _normalize_auto_teardown_mode(shared.Get_Shared_Variables("zeuz_auto_teardown", log=False))
def _auto_teardown_at_run_start():
return _auto_teardown_mode() in ("on", "on_run_start_and_end")
def _auto_teardown_after_test_case():
return _auto_teardown_mode() == "on"
def _auto_teardown_at_run_end():
return _auto_teardown_mode() in ("on_run_end", "on_run_start_and_end")
def _payload_contains_selected_test_case(run_id_info, index):
selected_test_cases = run_id_info.get("deploy_test_cases", [])
current_test_cases = [
tc.get("testcase_no")
for tc in run_id_info.get("test_cases", [])
]
if not selected_test_cases or not current_test_cases:
return True
return selected_test_cases[index] in current_test_cases
def advanced_float(text:str) -> float:
try:
return float(text)
except:
import re
nums = re.findall(r"-?\d+\.?\d*", text)
if len(nums) == 0:
raise ValueError(f"could not convert string to float: '{text}'")
num = nums[0]
num = num[:-1] if num.endswith('.') else num
return float(num)
def set_important_variables():
try:
for module in CommonUtil.common_modules[:-1]:
try:
if module not in shared.shared_variables:
exec("import " + module)
shared.shared_variables.update({module: eval(module)})
except:
continue
if "sr" not in shared.shared_variables:
shared.shared_variables.update({"sr": shared})
shared.shared_variables.update({
"clipboard_paste": pyperclip.paste,
"clipboard_set": pyperclip.copy,
"num": advanced_float,
"urlparse": urlparse,
})
shared.Set_Shared_Variables("zeuz_window_auto_switch", "on")
except:
CommonUtil.Exception_Handler(sys.exc_info())
raise Exception
def send_to_bigquery(execution_log, metrics):
# Skip sending to gcp if credentials not available in environment.
if "GCP_BIGQUERY_ACTIONS_TABLE_ID" not in os.environ:
return
from google.cloud import bigquery
client = bigquery.Client()
# Table identifiers - these should be coming from zeuz server.
actions_table_id = os.environ["GCP_BIGQUERY_ACTIONS_TABLE_ID"]
steps_table_id = os.environ["GCP_BIGQUERY_STEPS_TABLE_ID"]
browser_perf_table_id = os.environ["GCP_BIGQUERY_BROWSER_PERF_TABLE_ID"]
test_cases_table_id = os.environ["GCP_BIGQUERY_TEST_CASES_TABLE_ID"]
run_id = execution_log["run_id"]
tc_id = execution_log["test_cases"][0]["testcase_no"]
steps = metrics["node"]["steps"]
actions = metrics["node"]["actions"]
test_cases = metrics["node"]["test_cases"]
for i in range(len(test_cases)):
test_cases[i]['tc_title'] = execution_log["test_cases"][i]["title"]
try:
browser_perf = metrics["browser_performance"]["default"]
except:
browser_perf = list()
# A dict of step id to step name
step_names = {}
for step in steps:
step_names[step["id"]] = step["name"]
def send(table, rows, msg):
errors = client.insert_rows_json(table, rows)
if len(errors) == 0:
print(f"Sent {msg} metrics report to BigQuery")
else:
print(f"Encountered errors while inserting rows for {msg}: {errors}")
def send_actions_metrics():
if actions:
for action in actions:
action["run_id"] = run_id
action["tc_id"] = tc_id
action["step_name"] = step_names[action["step_id"]]
send(actions_table_id, actions, "actions")
def send_steps_metrics():
for step in steps:
step["run_id"] = run_id
step["tc_id"] = tc_id
step["step_id"] = step["id"]
del step["id"]
step["step_name"] = step["name"]
del step["name"]
step["step_sequence"] = step["sequence"]
del step["sequence"]
send(steps_table_id, steps, "step")
def send_test_case_metrics():
send(test_cases_table_id, test_cases, "test case")
def send_browser_perf_metrics():
if len(browser_perf) == 0:
return
for entry in browser_perf:
entry["run_id"] = run_id
send(browser_perf_table_id, browser_perf, "browser perf")
send_actions_metrics()
send_steps_metrics()
send_test_case_metrics()
send_browser_perf_metrics()
def check_test_skip(run_id, tc_num, skip_remaining=True) -> bool:
if run_id not in CommonUtil.skip_testcases:
return False
if skip_remaining and 'skip remaining' in CommonUtil.skip_testcases[run_id]:
return True
if tc_num in CommonUtil.skip_testcases[run_id]:
return True
ranges = [i for i in CommonUtil.skip_testcases[run_id] if type(i) == range]
if len(ranges) == 0:
return False
target = CommonUtil.tc_nums[run_id].index(tc_num)