Repository navigation
Expand file tree
/
Copy pathtest_playwright_compat.py
More file actions
2392 lines (2136 loc) · 102 KB
/
Copy pathtest_playwright_compat.py
File metadata and controls
2392 lines (2136 loc) · 102 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
import asyncio
import json
import shutil
import threading
import time
from types import SimpleNamespace
import pytest
from Framework.Built_In_Automation.Sequential_Actions.action_declarations.playwright import (
declarations,
)
from Framework.Built_In_Automation.Shared_Resources import LocateElement
from Framework.Built_In_Automation.Web.Playwright import (
BuiltInFunctions as playwright_actions,
)
from Framework.Built_In_Automation.Sequential_Actions import sequential_actions
def test_declaration_parity_and_callables():
excluded = {
"click and hold",
"validate table",
"validate table row size",
"validate table column size",
"playwright",
}
from Framework.Built_In_Automation.Sequential_Actions.action_declarations.selenium import (
declarations as selenium,
)
assert len(declarations) == 55
assert {item["name"] for item in declarations} == {
item["name"] for item in selenium
} - excluded
assert all(
callable(getattr(playwright_actions, item["function"], None))
for item in declarations
)
assert (
sum(
item["module"] == "playwright"
for item in sequential_actions.actions.values()
)
== 55
)
def test_playwright_module_loads():
assert sequential_actions.load_sa_modules("playwright") == "passed"
assert sequential_actions.playwright is playwright_actions
def test_review_routing_and_selenium_ownership(monkeypatch):
monkeypatch.setattr(playwright_actions.sr, "Test_Shared_Variables", lambda name: name == "dependency")
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda name, **_: {"Browser": "Chrome"})
from Framework.Built_In_Automation.Web.Selenium import BuiltInFunctions as selenium
values = {"zeuz_browser_driver": "playwright", "zeuz_active_browser_backend": "playwright"}
monkeypatch.setattr(sequential_actions.sr, "Get_Shared_Variables", lambda name, **_: values.get(name))
monkeypatch.setattr(sequential_actions.sr, "Set_Shared_Variables", lambda name, value, **_: values.__setitem__(name, value))
monkeypatch.setattr(sequential_actions.sr, "Shared_Variable_Export", lambda: values)
screenshots = []
monkeypatch.setattr(sequential_actions.CommonUtil, "set_screenshot_vars", lambda values: screenshots.append(values.copy()))
driver = object()
monkeypatch.setattr(selenium, "selenium_details", {"web": {"driver": driver}})
monkeypatch.setattr(selenium, "selenium_driver", None)
monkeypatch.setattr(selenium, "current_driver_id", None)
for backend in ("selenium", "playwright"):
for subfield in ("selenium action", "playwright action"):
assert sequential_actions._route_playwright_action("click", subfield, [
("browser driver", "optional parameter", backend)
]) == backend + " action"
assert selenium.Switch_Browser([("driver_id", "optional parameter", "web")]) == "passed"
assert values["zeuz_browser_backends"] == {"web": "selenium"}
assert screenshots[-1]["common_driver"] is driver
assert screenshots[-1]["zeuz_active_browser_backend"] == "selenium"
assert sequential_actions._route_playwright_action("switch browser", "selenium action", [
("driver_id", "optional parameter", "web")
]) == "selenium action"
def test_review_extension_failure_and_xpath_case(monkeypatch):
monkeypatch.setattr(playwright_actions.sr, "Test_Shared_Variables", lambda name: name == "dependency")
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda name, **_: {"Browser": "Chrome"})
from Framework.Built_In_Automation.Web.Selenium import BuiltInFunctions as selenium
monkeypatch.setattr(selenium, "ChromeExtensionDownloader", lambda **_: SimpleNamespace(
setup_chrome_extension_download=lambda **_: None))
assert selenium.parse_and_verify_datatype("addextension", repr(["a" * 32])) == []
assert LocateElement._construct_query([("XPath", "element parameter", "//button")]) == ("//button", "xpath")
def test_review_text_classifier_and_image_paste(monkeypatch):
import pyperclip
from Framework.AI import NLP
seen = []
element = SimpleNamespace(inner_text=lambda: " success \n\nnext", focus=lambda: seen.append("focus"),
evaluate=lambda script, value: seen.append(value))
monkeypatch.setattr(playwright_actions, "_element", lambda *_args, **_: element)
monkeypatch.setattr(NLP, "binary_classification", lambda message, labels, confidence: seen.append(
(message, labels, confidence)) or {"status": "passed"})
assert playwright_actions.Validate_Text([
("validate full text", "action", "unused"), ("success", "text classifier offset", "0.8")
]) == "passed"
assert seen[-1] == ("success next", ["success"], 0.8)
def failed_press(combo):
seen.append(combo)
raise RuntimeError("paste failed")
monkeypatch.setattr(playwright_actions, "get_page", lambda: SimpleNamespace(
keyboard=SimpleNamespace(press=failed_press), evaluate=lambda _: True))
monkeypatch.setattr(pyperclip, "paste", lambda: "fallback")
assert playwright_actions.Keystroke_For_Element([
("id", "element parameter", "input"), ("keystroke keys", "action", "CTRL+V"),
("paste image", "optional parameter", "true")
]) == "passed"
assert seen[-3:] == ["focus", "Meta+v", "fallback"]
def test_review_network_static_filters(monkeypatch):
logs = []
state = {"capturing_network": True, "network": [
{"url": "https://example.test/" + suffix, "status": 200, "method": "GET", "mimeType": mime}
for suffix, mime in [("a.txt", "text/plain"), ("a.webp", ""), ("a.eot", ""),
("image?id=1", "image/png"), ("font", "application/x-font-ttf"),
("api", "application/json")]
]}
monkeypatch.setattr(playwright_actions, "_state", lambda: state)
monkeypatch.setattr(playwright_actions.sr, "Set_Shared_Variables", lambda _, value: logs.extend(value))
assert playwright_actions.capture_network_log([
("capture network log", "action", "stop"), ("save", "input parameter", "logs")
]) == "passed"
assert [item["url"] for item in logs] == ["https://example.test/api"]
def test_review_clipboard_variable_and_multiple_tabs(monkeypatch, tmp_path):
image = tmp_path / "image.png"
image.write_bytes(b"image bytes")
captured = []
context = SimpleNamespace(pages=[], grant_permissions=lambda *args, **kwargs: None,
wait_for_event=lambda *args, **kwargs: None)
state = {"context": context}
class Page:
url = "https://example.test"
def __init__(self, title):
self.name = title
def title(self):
return self.name
def is_closed(self):
return False
def close(self):
context.pages.remove(self)
def evaluate(self, script, value):
captured.append(value)
pages = [Page(name) for name in ("first", "second", "third")]
context.pages = pages.copy()
monkeypatch.setattr(playwright_actions, "_state", lambda: state)
monkeypatch.setattr(playwright_actions, "get_page", lambda: pages[0])
monkeypatch.setattr(playwright_actions, "_wire_page", lambda *_: None)
monkeypatch.setattr(playwright_actions, "_set_active", lambda *_: None)
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda name: str(image))
for value in (str(image), "image_variable"):
assert playwright_actions.copy_image_into_browser([
("image variable", "input parameter", value)
]) == "passed"
assert captured[-1] == {"data": "aW1hZ2UgYnl0ZXM=", "mime": "image/png"}
assert playwright_actions.close_tab([("tabs", "optional parameter", "[0, 2]")]) == "passed"
assert context.pages == [pages[1]]
context.pages = pages.copy()
assert playwright_actions.close_tab([("tabs", "optional parameter", "['first', 'third']")]) == "passed"
assert context.pages == [pages[1]]
context.pages = pages.copy()
pages[0].name = "third backup"
assert playwright_actions.close_tab([
("*window title", "element parameter", "third"),
("window index", "element parameter", "0"),
("tabs", "optional parameter", "['third']"),
]) == "passed"
assert context.pages == pages[:2]
def test_review_electron_ports(monkeypatch):
import socket
monkeypatch.setattr(playwright_actions.sr, "Test_Shared_Variables", lambda name: name == "dependency")
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda name, **_: {"Browser": "Chrome"})
from Framework.Built_In_Automation.Web.Selenium import BuiltInFunctions as selenium
sockets, ports, closed = [], [], []
def launch(**kwargs):
port = int(next(arg.split("=", 1)[1] for arg in kwargs["options"].arguments
if arg.startswith("--remote-debugging-port=")))
sock = socket.socket()
sockets.append(sock)
sock.bind(("127.0.0.1", port))
ports.append(port)
return SimpleNamespace(implicitly_wait=lambda _: None, quit=lambda: closed.append(port))
monkeypatch.setenv("WDM_ARCHITECTURE", "x64")
monkeypatch.setattr(selenium.webdriver, "Chrome", launch)
monkeypatch.setattr(selenium, "ChromeDriverManager", lambda **_: SimpleNamespace(install=lambda: "/tmp/chromedriver"))
monkeypatch.setattr(selenium.ConfigModule, "get_config_value", lambda *_: "/tmp/chromedriver")
monkeypatch.setattr(selenium, "_publish_active_browser", lambda: None)
monkeypatch.setattr(selenium.Shared_Resources, "Set_Shared_Variables", lambda *_: None)
monkeypatch.setattr(selenium.CommonUtil, "set_screenshot_vars", lambda *_: None)
monkeypatch.setattr(selenium, "selenium_details", {})
monkeypatch.setattr(selenium, "selenium_driver", None)
monkeypatch.setattr(selenium, "current_driver_id", None)
try:
for driver_id in ("one", "two", "one"):
assert selenium.Open_Electron_App([
(selenium.platform.system().lower(), "input parameter", "/tmp/electron"),
("driverid", "optional parameter", driver_id)
]) == "passed"
assert selenium.selenium_details[driver_id]["remote-debugging-port"] == ports[-1]
assert selenium.selenium_details[driver_id]["driver"] is selenium.selenium_driver
assert ports[0] != ports[1]
assert closed == [ports[0]]
finally:
for sock in sockets:
sock.close()
def test_review_browser_action_parity(page, monkeypatch):
context = page.context.browser.new_context()
tab = context.new_page()
monkeypatch.setattr(playwright_actions, "get_page", lambda: tab)
monkeypatch.setattr(playwright_actions, "get_driver", lambda: tab)
saved = {}
monkeypatch.setattr(playwright_actions.sr, "Set_Shared_Variables", lambda name, value: saved.__setitem__(name, value) or "passed")
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda *_args, **_: 0)
try:
tab.set_content('''<input id="text" readonly><input id="check" type="checkbox" style="pointer-events:none">
<div id="root"><span class="item" value="one">keep</span><span class="item" value="two">drop</span></div>
<table><tr><th>heading</th></tr><tr><td>cell</td></tr></table>
<div style="height:2000px"></div><div id="bottom">bottom</div><div style="height:2000px"></div>
<script>window.events=[]; document.querySelector('#text').addEventListener('input', () => events.push('input'));
document.querySelector('#text').addEventListener('change', () => events.push('change'));</script>''')
text = " text ` ${literal} "
assert playwright_actions.Enter_Text_In_Text_Box([
("id", "element parameter", "text"), ("text", "action", text), ("use js", "optional parameter", "true")
]) == "passed"
assert tab.locator("#text").input_value() == text
assert tab.evaluate("events") == ["input", "change"]
assert playwright_actions.check_uncheck([
("id", "element parameter", "check"), ("check uncheck", "action", "check"), ("use js", "optional parameter", "yes")
]) == "passed"
assert tab.locator("#check").is_checked()
assert playwright_actions._return_attribute(tab.locator("#check"), "checked") == "True"
assert playwright_actions._return_attribute(tab.locator(".item").first, "tag") == "span"
assert playwright_actions._return_attribute(tab.locator(".item").first, "value") == "one"
rows = [("id", "element parameter", "root"),
("attributes", "target parameter", 'class="item", return="text", return_contains="keep"'),
("attributes", "target parameter", 'class="item", return="value"'),
("save attribute values in list", "action", "values")]
assert playwright_actions.save_attribute_values_in_list(rows) == "passed"
assert saved["values"] == [["keep", "one"], [None, "two"]]
assert playwright_actions.save_attribute_values_in_list(rows + [("paired", "optional parameter", "no")]) == "passed"
assert saved["values"] == [["keep", None], ["one", "two"]]
assert playwright_actions.save_web_elements_in_list([
("id", "element parameter", "root"),
("attributes", "target parameter", 'class="item", return_contains(text="keep"), return_does_not_contain(value="two")'),
("save web elements in list", "action", "elements")
]) == "passed"
assert [element.inner_text() for element in saved["elements"]] == ["keep"]
assert playwright_actions.Extract_Table_Data([
("tag", "element parameter", "table"), ("extract table data", "action", "table")
]) == "passed"
assert saved["table"] == [[], ["cell"]]
rows = [("id", "element parameter", "bottom"), ("scroll element to top", "action", ""),
("additional scroll", "optional parameter", "0")]
assert playwright_actions.scroll_to_element(rows) == "passed"
assert abs(tab.locator("#bottom").bounding_box()["y"]) < 1
assert playwright_actions.scroll_to_element(rows + [("align to top", "optional parameter", "false")]) == "passed"
box = tab.locator("#bottom").bounding_box()
assert abs(box["y"] + box["height"] - tab.evaluate("innerHeight")) < 1
# The synchronous click completes because the next action handles its dialog immediately.
state = {}
monkeypatch.setattr(playwright_actions, "_state", lambda: state)
monkeypatch.setattr(playwright_actions.CommonUtil, "current_action_no", "1")
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda *_args, **_: [[], [
("handle alert", "action", "send text=answer")]])
tab.on("dialog", lambda dialog: playwright_actions._on_dialog(state, dialog))
assert tab.evaluate("prompt('question')") == "answer"
assert playwright_actions.Handle_Browser_Alert([("handle alert", "action", "get text=alert")]) == "passed"
assert saved["alert"] == "question"
monkeypatch.setattr(playwright_actions, "get_page", lambda: tab)
tab.evaluate("setTimeout(() => { window.answer = prompt('delayed'); }, 100)")
assert playwright_actions.Handle_Browser_Alert([
("handle alert", "action", "accept"),
("prompt text", "input parameter", "delayed answer"),
("delayed_message", "save parameter", ""),
("wait", "optional parameter", "2"),
]) == "passed"
assert tab.evaluate("window.answer") == "delayed answer"
assert saved["delayed_message"] == "delayed"
finally:
context.close()
def test_backend_routing(monkeypatch):
values = {}
monkeypatch.setattr(
sequential_actions.sr,
"Get_Shared_Variables",
lambda name, **_: values.get(name, "zeuz_failed"),
)
assert (
sequential_actions._route_playwright_action("click", "selenium action", [])
== "selenium action"
)
assert (
sequential_actions._route_playwright_action("", "selenium conditional action", [])
== "selenium conditional action"
)
values["zeuz_browser_driver"] = "PlAyWrIgHt"
assert (
sequential_actions._route_playwright_action("click", "selenium action", [])
== "playwright action"
)
assert (
sequential_actions._route_playwright_action("", "selenium conditional action", [])
== "playwright conditional action"
)
assert (
sequential_actions._route_playwright_action("", "playwright conditional action", [])
== "playwright conditional action"
)
assert (
sequential_actions._route_playwright_action("click", "playwright action", [])
== "playwright action"
)
assert (
sequential_actions._route_playwright_action(
"open electron app", "selenium action", []
)
== "selenium action"
)
assert (
sequential_actions._route_playwright_action(
"open electron app", "playwright action", []
)
== "selenium action"
)
assert (
sequential_actions._route_playwright_action(
"accessibility test", "playwright action", []
)
== "selenium action"
)
values["zeuz_active_browser_backend"] = "selenium"
values["zeuz_browser_backends"] = {"electron": "selenium", "web": "playwright"}
assert (
sequential_actions._route_playwright_action("click", "selenium action", [])
== "selenium action"
)
assert (
sequential_actions._route_playwright_action(
"switch browser",
"selenium action",
[("driver_id", "optional parameter", "web")],
)
== "playwright action"
)
def test_routed_common_wait_receives_normalized_action_row(monkeypatch):
rows = [
("*class", "parent parameter", "navbar-expand-lg container-fluid navbar"),
("*class", "element parameter", "small-nav"),
("wait", "selenium action", "30"),
]
captured = []
values = {
"zeuz_browser_driver": "playwright",
"zeuz_prettify_limit": 500,
"action_timeout": 5,
}
monkeypatch.setattr(
sequential_actions.sr,
"Get_Shared_Variables",
lambda name, **_: values.get(name, "zeuz_failed"),
)
monkeypatch.setattr(
sequential_actions.sr, "Set_Shared_Variables", lambda *_args, **_kwargs: None
)
monkeypatch.setattr(sequential_actions.sr, "Shared_Variable_Export", lambda: {})
monkeypatch.setattr(sequential_actions, "load_sa_modules", lambda _module: None)
monkeypatch.setattr(
sequential_actions,
"playwright",
SimpleNamespace(get_driver=lambda: object()),
raising=False,
)
monkeypatch.setattr(
sequential_actions.common,
"shared_variable_to_value",
lambda data_set: data_set,
)
monkeypatch.setattr(
sequential_actions.common,
"Wait_For_Element",
lambda data_set: captured.extend(data_set) or "passed",
)
monkeypatch.setattr(
sequential_actions.ConfigModule,
"get_config_value",
lambda *_args, **_kwargs: "false",
)
monkeypatch.setattr(
sequential_actions.CommonUtil,
"TakeScreenShot",
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
sequential_actions.CommonUtil,
"set_screenshot_vars",
lambda *_args, **_kwargs: None,
)
assert sequential_actions.Action_Handler(rows, rows[-1]) == "passed"
assert ("wait", "action", "30") in captured
def test_selenium_conditional_uses_active_playwright_driver(monkeypatch):
page = object()
values = {"zeuz_browser_driver": "playwright"}
seen = []
caller_thread = threading.get_ident()
monkeypatch.setattr(
sequential_actions.sr,
"Get_Shared_Variables",
lambda name, **_: values.get(name, "zeuz_failed"),
)
monkeypatch.setattr(sequential_actions, "load_sa_modules", lambda _module: None)
monkeypatch.setattr(
sequential_actions,
"playwright",
SimpleNamespace(get_driver=lambda: page),
raising=False,
)
monkeypatch.setattr(
sequential_actions.LocateElement,
"Get_Element",
lambda _rows, driver, **_: seen.append(
(driver, threading.get_ident())
) or object(),
)
result, _skip = sequential_actions.Conditional_Action_Handler(
[[
("id", "element parameter", "button1"),
("true", "selenium conditional action", ""),
]],
0,
)
assert result == "passed"
assert seen[0][0] is page
assert seen[0][1] != caller_thread
def test_action_worker_keeps_affinity_after_timeout():
worker = sequential_actions._ActionTimeoutWorker()
thread_ids = []
def slow():
thread_ids.append(threading.get_ident())
time.sleep(0.05)
with pytest.raises(TimeoutError):
worker.run(slow, (), 0.01)
assert (
worker.run(lambda: thread_ids.append(threading.get_ident()) or "passed", (), 1)
== "passed"
)
assert len(set(thread_ids)) == 1
def test_switch_iframe_resets_then_selects_locator(monkeypatch):
frame = object()
state = {"page": object(), "frame": object(), "frame_stack": [object()]}
seen = []
monkeypatch.setattr(playwright_actions, "_state", lambda: state)
monkeypatch.setattr(
playwright_actions,
"_element",
lambda rows, **_: seen.extend(rows) or SimpleNamespace(content_frame=frame),
)
monkeypatch.setattr(
playwright_actions.sr, "Set_Shared_Variables", lambda *_args, **_kwargs: None
)
assert playwright_actions.switch_iframe([
("index", "iframe parameter", "default content"),
("id", "iframe parameter", "frame_two"),
("switch iframe", "playwright action", "switch iframe"),
]) == "passed"
assert state["frame"] is frame
assert state["frame_stack"] == [None]
assert ("id", "element parameter", "frame_two") in seen
assert not any(right == "default content" for _, _, right in seen)
def test_go_to_link_clears_previous_iframe(monkeypatch):
class Page:
url = "https://example.test/inside-frame"
def goto(self, url, **kwargs):
self.url = url
self.wait_until = kwargs["wait_until"]
page = Page()
state = {
"page": page,
"frame": object(),
"frame_stack": [object()],
"wait_until": "load",
"wired_pages": {id(page)},
}
monkeypatch.setattr(playwright_actions, "_launch", lambda _rows: state)
monkeypatch.setattr(playwright_actions, "_set_active", lambda _driver_id: None)
assert playwright_actions.Go_To_Link([
("go to link", "playwright action", "https://example.test/login"),
]) == "passed"
assert page.url == "https://example.test/login"
assert page.wait_until == "load"
assert state["frame"] is None
assert state["frame_stack"] == []
def test_go_to_link_navigates_hash_route(monkeypatch):
class Page:
url = "https://example.test/#/login"
def goto(self, url, **kwargs):
self.gotos.append(url)
self.goto_wait_until = kwargs["wait_until"]
self.url = url
def reload(self, **kwargs):
self.reload_wait_until = kwargs["wait_until"]
page = Page()
page.gotos = []
state = {
"page": page,
"frame": None,
"frame_stack": [],
"wait_until": "load",
"wired_pages": {id(page)},
}
monkeypatch.setattr(playwright_actions, "_launch", lambda _rows: state)
monkeypatch.setattr(playwright_actions, "_set_active", lambda _driver_id: None)
assert playwright_actions.Go_To_Link([
("go to link", "playwright action", page.url),
]) == "passed"
assert page.gotos == [page.url]
assert page.goto_wait_until == "load"
assert page.reload_wait_until == "load"
def test_open_new_tab_makes_new_page_active(monkeypatch):
old_page = object()
new_page = SimpleNamespace(on=lambda *_args: None)
state = {
"page": old_page,
"frame": object(),
"frame_stack": [object()],
"context": SimpleNamespace(new_page=lambda: new_page),
"wired_pages": set(),
"page_listener": True,
"capturing_network": False,
"downloads": [],
}
active_pages = []
monkeypatch.setattr(playwright_actions, "_state", lambda: state)
monkeypatch.setattr(
playwright_actions,
"_set_active",
lambda _driver_id: active_pages.append(state["page"]),
)
assert playwright_actions.open_new_tab([
("open new tab", "playwright action", "open new tab"),
]) == "passed"
assert state["page"] is new_page
assert state["frame"] is None
assert active_pages == [new_page]
def test_reused_browser_applies_element_wait(monkeypatch):
state = {"page": SimpleNamespace(title=lambda: "Existing page")}
shared = {}
monkeypatch.setattr(playwright_actions._browser_state, "playwright_details", {"default": state})
monkeypatch.setattr(playwright_actions, "_set_active", lambda _driver_id: None)
monkeypatch.setattr(
playwright_actions.sr,
"Get_Shared_Variables",
lambda name, **_kwargs: {"Browser": "Chrome"}
if name == "dependency"
else None,
)
monkeypatch.setattr(
playwright_actions.sr,
"Set_Shared_Variables",
lambda name, value, **_kwargs: shared.__setitem__(name, value),
)
assert playwright_actions._launch([
("wait time to appear element", "optional parameter", "60"),
]) is state
assert shared["element_wait"] == 60.0
@pytest.mark.parametrize("scenario", [
"delayed_index", "queued_title", "queued_index_zero", "delayed_title",
"trimmed_title", "partial_title", "negative_index", "missing_title", "missing_index",
"mixed_title_index", "mixed_title_index_legacy_flag", "mixed_index_title",
"repeated_index", "repeated_title", "partial_then_exact",
])
def test_switch_tab_keeps_requested_page_and_bridge(page, monkeypatch, scenario):
context = page.context.browser.new_context()
original = context.new_page()
original.set_content("<title>Original</title>")
bridge_calls = []
state = {
"context": context, "page": original, "downloads": [], "capturing_network": False,
"selenium_bridge": SimpleNamespace(switch_to=SimpleNamespace(window=bridge_calls.append)),
}
shared = {}
monkeypatch.setattr(playwright_actions._browser_state, "playwright_details", {"tabs": state})
monkeypatch.setattr(playwright_actions._browser_state, "current_driver_id", "tabs")
monkeypatch.setattr(playwright_actions._browser_state, "playwright_page", None)
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda name, **_: shared.get(name))
monkeypatch.setattr(playwright_actions.sr, "Set_Shared_Variables", lambda name, value, **_: shared.__setitem__(name, value))
monkeypatch.setattr(playwright_actions.sr, "Shared_Variable_Export", lambda: shared)
monkeypatch.setattr(playwright_actions.CommonUtil, "set_screenshot_vars", lambda _: None)
monkeypatch.setattr(playwright_actions, "_publish_selenium_bridge", lambda _: None)
try:
playwright_actions._wire_page(state, original)
playwright_actions._set_active("tabs")
bridge_calls.clear()
frame = object()
state["frame"], state["frame_stack"] = frame, [frame]
field, value = "tab title", "Target"
if scenario in ("delayed_index", "queued_title", "queued_index_zero"):
original.evaluate("""() => setTimeout(() => {
const popup = window.open('about:blank');
popup.document.title = 'Target';
}, 300)""")
if scenario.startswith("queued"):
# Model a Selenium/Python action: the browser runs while events queue.
time.sleep(0.7)
assert len(context.pages) == 1
if scenario == "delayed_index":
field, value = "window index", "1"
elif scenario == "queued_index_zero":
field, value = "tab index", "0"
elif scenario.startswith("missing"):
if scenario == "missing_index":
field, value = "tab index", "99"
else:
target = context.new_page()
assert state["page"] is original and state["frame"] is frame
assert state["frame_stack"] == [frame]
target.set_content("<title>Target</title>")
if scenario == "delayed_title":
target.evaluate("""() => {
document.title = 'Loading';
setTimeout(() => document.title = 'Target', 300);
}""")
elif scenario == "trimmed_title":
field, value = "window title", " Target "
elif scenario == "partial_title":
field, value = "*tab title", " ARG "
elif scenario == "negative_index":
field, value = "tab index", "-1"
rows = [(field, "input parameter", value),
("wait", "optional parameter", "0.05" if scenario.startswith("missing") else "2"),
("switch window/tab", "selenium action", "switch window or frame")]
if scenario in ("mixed_title_index", "mixed_title_index_legacy_flag"):
target.set_content("<title>SuccessKPI</title>")
if scenario == "mixed_title_index":
original.set_content("<title>SuccessKPI</title>")
rows = [("window title", "element parameter", "SuccessKPI"),
("window index", "element parameter", "0" if scenario.endswith("legacy_flag") else "1"),
("switch window/tab", "selenium action", "switch window/tab")]
if scenario.endswith("legacy_flag"):
rows.insert(0, ("playwright", "optional parameter", "true"))
elif scenario in ("mixed_index_title", "repeated_index"):
rows.insert(0, ("window index", "element parameter", "0"))
if scenario == "repeated_index":
rows[1] = ("window index", "element parameter", "1")
elif scenario == "repeated_title":
rows.insert(0, ("window title", "element parameter", "Original"))
elif scenario == "partial_then_exact":
rows[0] = ("window title", "element parameter", "get")
rows.insert(0, ("*window title", "element parameter", "Unused"))
shared["zeuz_browser_driver"] = "playwright"
routed = sequential_actions._route_playwright_action(rows[-1][0], rows[-1][1], rows)
assert sequential_actions.common.get_module_and_function(rows[-1][0], routed)[:2] == (
"playwright", "switch_window_or_tab",
)
result = playwright_actions.switch_window_or_tab(rows)
if scenario.startswith("missing"):
assert result == "zeuz_failed"
assert state["page"] is original and state["frame"] is frame
assert state["frame_stack"] == [frame]
assert shared["playwright_page"] is original
assert bridge_calls == []
return
assert result == "passed"
selected = original if scenario in ("queued_index_zero", "mixed_title_index_legacy_flag") else context.pages[-1]
assert state["page"] is selected
assert playwright_actions.get_driver() is selected
assert state["frame"] is None and state["frame_stack"] == []
assert shared["playwright_page"] is shared["common_driver"] is selected
session = context.new_cdp_session(selected)
try:
target_id = session.send("Target.getTargetInfo")["targetInfo"]["targetId"]
finally:
session.detach()
assert bridge_calls == [target_id]
# The same selection helper and bridge alignment serve tab closing/opening.
if scenario == "trimmed_title":
assert playwright_actions.close_tab([("tabs", "optional parameter", "[1]")]) == "passed"
assert playwright_actions.get_page() is original
assert shared["playwright_page"] is original
assert len(bridge_calls) == 2 and bridge_calls[-1] != target_id
assert playwright_actions.open_new_tab([("open new tab", "action", "open new tab")]) == "passed"
assert playwright_actions.get_page() is context.pages[-1]
assert len(bridge_calls) == 3
finally:
context.close()
def test_tab_wait_rejects_invalid_values(monkeypatch):
monkeypatch.setattr(playwright_actions, "_state", lambda: {"context": object()})
for value in ("-1", "nan", "inf", "invalid"):
with pytest.raises(ValueError):
playwright_actions._find_page([("timeout", "optional parameter", value)])
@pytest.mark.parametrize("closed_target", ["active", "popup", "last_page", "context", "browser"])
def test_go_to_link_recovers_closed_cached_target(page, monkeypatch, closed_target):
browser_type = page.context.browser.browser_type
browser = browser_type.launch(channel="chrome", headless=True)
context = browser.new_context()
context.add_cookies([{
"name": "login", "value": "retained", "domain": "example.test", "path": "/",
}])
original = context.new_page()
bridge_calls = []
bridge = SimpleNamespace(
switch_to=SimpleNamespace(window=bridge_calls.append),
quit=lambda: bridge_calls.append("quit"),
)
state = {
"browser": browser, "context": context, "page": original,
"wait_until": "load", "downloads": [], "capturing_network": False,
"selenium_bridge": bridge,
}
other = {"page": object()}
shared = {"dependency": {"Browser": "Chromium Headless"}}
monkeypatch.setattr(playwright_actions._browser_state, "playwright_details", {
"portal": state, "other": other,
})
monkeypatch.setattr(playwright_actions._browser_state, "current_driver_id", None)
monkeypatch.setattr(playwright_actions._browser_state, "playwright_page", None)
monkeypatch.setattr(playwright_actions._browser_state, "_playwright", SimpleNamespace(
chromium=browser_type,
))
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda name, **_: shared.get(name))
monkeypatch.setattr(playwright_actions.sr, "Set_Shared_Variables", lambda name, value, **_: shared.__setitem__(name, value))
monkeypatch.setattr(playwright_actions.sr, "Remove_From_Shared_Variables", lambda name: shared.pop(name, None))
monkeypatch.setattr(playwright_actions.sr, "Shared_Variable_Export", lambda: shared)
monkeypatch.setattr(playwright_actions.CommonUtil, "set_screenshot_vars", lambda _: None)
monkeypatch.setattr(playwright_actions, "_publish_selenium_bridge", lambda _: None)
monkeypatch.setattr(playwright_actions, "_attach_selenium_bridge", lambda *_: None)
url = "data:text/html,<title>login</title>"
try:
playwright_actions._wire_page(state, original)
target = context.new_page()
assert state["page"] is original
playwright_actions._wire_page(state, target)
assert state["page"] is target
playwright_actions._set_active("portal")
bridge_calls.clear()
if closed_target == "popup":
target.close()
elif closed_target == "last_page":
original.close()
target.close()
elif closed_target == "context":
context.close()
elif closed_target == "browser":
browser.close()
assert playwright_actions.Go_To_Link([
("driver id", "optional parameter", "portal"),
("go to link", "selenium action", url),
]) == "passed"
recovered = playwright_actions._browser_state.playwright_details["portal"]
assert not recovered["page"].is_closed()
assert recovered["page"].title() == "login"
assert recovered["page"].url == url
assert playwright_actions._browser_state.current_driver_id == "portal"
assert shared["playwright_page"] is recovered["page"]
assert shared["common_driver"] is recovered["page"]
assert playwright_actions._browser_state.playwright_details["other"] is other
if closed_target in ("active", "popup", "last_page"):
assert recovered is state
assert recovered["context"] is context
assert context.cookies()[0]["value"] == "retained"
session = context.new_cdp_session(recovered["page"])
try:
target_id = session.send("Target.getTargetInfo")["targetInfo"]["targetId"]
finally:
session.detach()
assert bridge_calls == [target_id, target_id]
if closed_target == "popup":
assert recovered["page"] is original
else:
assert recovered is not state
assert not browser.is_connected()
assert recovered["browser"].is_connected()
assert bridge_calls == ["quit"]
finally:
recovered = playwright_actions._browser_state.playwright_details.get("portal")
if recovered is not None and recovered["browser"] is not browser:
recovered["browser"].close()
browser.close()
def test_cached_browser_preserves_non_closure_errors(monkeypatch):
from playwright.sync_api import Error
context = object()
def fail_title():
raise Error("Page crashed")
state = {
"page": SimpleNamespace(title=fail_title, is_closed=lambda: False),
"context": context,
"browser": SimpleNamespace(is_connected=lambda: True, contexts=[context]),
}
monkeypatch.setattr(playwright_actions._browser_state, "playwright_details", {"default": state})
monkeypatch.setattr(playwright_actions.sr, "Get_Shared_Variables", lambda _: {"Browser": "Chrome"})
with pytest.raises(Error, match="Page crashed"):
playwright_actions._launch([])
assert playwright_actions._browser_state.playwright_details["default"] is state
def test_go_to_link_v2_retains_driver_tag(monkeypatch):
monkeypatch.setattr(
playwright_actions.sr,
"Test_Shared_Variables",
lambda name: name == "dependency",
)
monkeypatch.setattr(
playwright_actions.sr,
"Get_Shared_Variables",
lambda name, **_: {"Browser": "Chrome"} if name == "dependency" else None,
)
from Framework.Built_In_Automation.Web.Selenium import (
BuiltInFunctions as selenium_actions,
)
driver = SimpleNamespace(
set_page_load_timeout=lambda _timeout: None,
maximize_window=lambda: None,
)
monkeypatch.setattr(selenium_actions.webdriver, "Chrome", lambda **_kwargs: driver)
monkeypatch.setattr(selenium_actions, "selenium_details", {})
monkeypatch.setattr(selenium_actions, "current_driver_id", None)
monkeypatch.setattr(
selenium_actions.Shared_Resources, "Set_Shared_Variables", lambda *_args: None
)
monkeypatch.setattr(
selenium_actions.Shared_Resources, "Shared_Variable_Export", lambda: {}
)
monkeypatch.setattr(selenium_actions.CommonUtil, "ExecLog", lambda *_args: None)
monkeypatch.setattr(
selenium_actions.CommonUtil, "set_screenshot_vars", lambda *_args: None
)
assert selenium_actions.Go_To_Link_V2.__wrapped__([
("driver tag", "optional parameter", "checkout"),
]) == "passed"
assert selenium_actions.current_driver_id == "checkout"
assert selenium_actions.selenium_details["checkout"]["driver"] is driver
def test_selenium_style_page_up_key(monkeypatch):
pressed = []
monkeypatch.setattr(
playwright_actions,
"get_page",
lambda: SimpleNamespace(keyboard=SimpleNamespace(press=pressed.append)),
)
assert playwright_actions.Keystroke_For_Element([
("keystroke keys", "selenium action", "PAGE_UP"),
]) == "passed"
assert pressed == ["PageUp"]
def test_selenium_cdp_address(monkeypatch):
monkeypatch.setattr(playwright_actions, "_free_local_port", lambda: 32123)
arguments = []
assert playwright_actions._selenium_cdp_address(
"chrome", None, arguments
) == "127.0.0.1:32123"
assert "--remote-debugging-port=32123" in arguments
assert playwright_actions._selenium_cdp_address(
"microsoft edge chromium", "http://localhost:9222", []
) == "localhost:9222"
assert playwright_actions._selenium_cdp_address("firefox", None, []) is None
def test_chrome_launch_uses_chrome_for_testing(monkeypatch):
class Page:
def __init__(self, context):
self.context = context
self.url = "about:blank"
def on(self, *_args):
pass
class Context:
pages = []
def on(self, *_args):
pass
def new_page(self):
return Page(self)
class Browser:
def new_context(self, **_kwargs):
return Context()
class Chromium:
def launch(self, **kwargs):
captured["launch"] = kwargs
return Browser()
class ChromeForTesting:
def setup_chrome_for_testing(self, version, channel):
captured["version"] = version
captured["channel"] = channel
return "/tmp/chrome", "/tmp/chromedriver"
captured = {}
shared = {}
monkeypatch.setattr(playwright_actions._browser_state, "_playwright", SimpleNamespace(chromium=Chromium()))
monkeypatch.setattr(playwright_actions._browser_state, "playwright_details", {})
monkeypatch.setattr(
playwright_actions.sr,
"Get_Shared_Variables",
lambda name, **_: {"Browser": "Chrome"} if name == "dependency" else None,
)
monkeypatch.setattr(playwright_actions, "_attach_selenium_bridge", lambda *_args: None)
monkeypatch.setattr(playwright_actions, "_set_active", lambda *_args: None)
monkeypatch.setattr(
playwright_actions.sr,
"Set_Shared_Variables",
lambda name, value, **_kwargs: shared.__setitem__(name, value),
)
monkeypatch.setattr(
"Framework.Built_In_Automation.Web.Selenium.utils.ChromeForTesting",
ChromeForTesting,
)
playwright_actions._launch([
("chrome:version", "optional parameter", "beta"),
("wait time to appear element", "optional parameter", "60"),
])
assert captured["version"] is None
assert captured["channel"] == "Beta"
assert captured["launch"]["executable_path"] == "/tmp/chrome"
assert "channel" not in captured["launch"]
assert shared["element_wait"] == 60.0
def test_playwright_viewport_uses_runtime_size_or_selenium_default(monkeypatch):
values = {"window_size_x": "", "window_size_y": ""}
monkeypatch.setattr(