Repository navigation
Expand file tree
/
Copy pathtest_selenium_adapter.py
More file actions
1677 lines (1452 loc) · 53.7 KB
/
Copy pathtest_selenium_adapter.py
File metadata and controls
1677 lines (1452 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import copy
import hashlib
import http.server
import io
import json
import pathlib
import signal
import socket
import subprocess
import sys
import textwrap
import threading
import time
import pytest
from runner.scripts.adapters import selenium_adapter
def make_executable(root: pathlib.Path) -> pathlib.Path:
executable = root / "build_artifacts" / "chromedriver" / "bin" / "chromedriver"
executable.parent.mkdir(parents=True, exist_ok=True)
executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
executable.chmod(0o755)
return executable.resolve()
def make_http_chromedriver(
root: pathlib.Path,
*,
ready: bool = True,
reject_session: bool = False,
ignore_sigterm: bool = False,
) -> tuple[pathlib.Path, pathlib.Path, pathlib.Path]:
executable = root / "fake_chromedriver"
state_path = root / "fake_chromedriver_state.json"
request_path = root / "fake_chromedriver_requests.log"
executable.write_text(
textwrap.dedent(
f"""\
#!{sys.executable}
import http.server
import json
import pathlib
import signal
import sys
READY = {ready!r}
REJECT_SESSION = {reject_session!r}
IGNORE_SIGTERM = {ignore_sigterm!r}
STATE_PATH = pathlib.Path({str(state_path)!r})
REQUEST_PATH = pathlib.Path({str(request_path)!r})
port = int(next(arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--port=")))
if IGNORE_SIGTERM:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
class Handler(http.server.BaseHTTPRequestHandler):
def send_json(self, status, body):
payload = json.dumps(body).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
if self.path == "/status":
self.send_json(200, {{"value": {{"ready": READY, "message": "fake"}}}})
else:
self.send_json(404, {{"value": {{"error": "unknown command"}}}})
def do_POST(self):
REQUEST_PATH.open("a", encoding="utf-8").write(f"POST {{self.path}}\\n")
if self.path != "/session":
self.send_json(404, {{"value": {{"error": "unknown command"}}}})
elif REJECT_SESSION:
self.send_json(500, {{"value": {{
"error": "session not created",
"message": "fake session rejection",
"stacktrace": "",
}}}})
else:
self.send_json(200, {{"value": {{
"sessionId": "fake-session",
"capabilities": {{
"browserName": "chrome",
"browserVersion": "Fake/1.0",
}},
}}}})
def do_DELETE(self):
REQUEST_PATH.open("a", encoding="utf-8").write(f"DELETE {{self.path}}\\n")
self.send_json(200, {{"value": None}})
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", port), Handler)
server.daemon_threads = True
STATE_PATH.write_text(json.dumps({{
"pid": __import__("os").getpid(),
"port": port,
"argv": sys.argv[1:],
}}), encoding="utf-8")
server.serve_forever()
"""
),
encoding="utf-8",
)
executable.chmod(0o755)
return executable.resolve(), state_path, request_path
def port_is_open(port: int) -> bool:
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.1):
return True
except OSError:
return False
def wait_for_process_absent(pid: int, timeout_s: float = 2.0) -> None:
stat_path = pathlib.Path(f"/proc/{pid}/stat")
deadline = time.monotonic() + timeout_s
while stat_path.exists() and time.monotonic() < deadline:
time.sleep(0.02)
assert not stat_path.exists(), f"process {pid} was not reaped"
def assertion(
mechanism: str,
actual_path: str,
expected_ref: str | None,
condition: str,
*,
expected_literal: str | None = None,
) -> dict:
row = {
"mechanism": mechanism,
"actual_path": actual_path,
"operator": "equals",
"condition": condition,
}
if expected_ref is not None:
row["expected_ref"] = expected_ref
else:
row["expected_literal"] = expected_literal
return row
def binding_payload(
engine: str,
route_id: str,
root: pathlib.Path,
) -> dict:
route = copy.deepcopy(selenium_adapter.ROUTE_CONTRACTS[route_id])
route["route_id"] = route_id
route["identity"] = {
"http_assertions": [
assertion("http_json_version", "Browser|Product", "expect_product", "always"),
assertion("http_json_version", "User-Agent", "expect_ua", "expected_nonempty"),
assertion("http_json_version", "webSocketDebuggerUrl", "browser_ws", "when_present"),
],
"live_transport_assertions": (
[
assertion(
"webdriver_capabilities",
"capabilities.browserName",
"expect_browser_name",
"always",
),
assertion(
"webdriver_capabilities",
"capabilities.browserVersion",
"expect_product_live",
"always",
),
]
if route_id == "native_webdriver"
else [
assertion(
"selenium_cdp_extension",
"execute_cdp_cmd.Browser.getVersion.product",
"expect_product_live",
"always",
)
]
),
}
bridges = []
if route_id == "chromedriver_cdp":
executable = make_executable(root)
bridges = [
{
"ref_id": "bridge.chromedriver",
"key": "chromedriver",
"metadata": {
"version": "150.0.0.0",
"binary_path": "build_artifacts/chromedriver/bin/chromedriver",
"sha256_12": hashlib.sha256(executable.read_bytes()).hexdigest()[:12],
},
"executable": str(executable),
}
]
return {
"binding_id": f"{engine}__selenium",
"browser_id": engine,
"driver_id": "selenium",
"route": route,
"pins": {
"browser": {"ref_id": f"browser.{engine}", "key": engine},
"driver": {
"ref_id": "driver.selenium",
"key": "selenium",
"metadata": {"version": "4.46.0", "pip_package": "selenium"},
},
"bridges": bridges,
},
"fallback_allowed": False,
}
def adapter_payload(
engine: str,
route_id: str,
root: pathlib.Path,
*,
transport_policy: str | None = "engine_native",
) -> dict:
return {
"protocol": "abb_scenario_adapter/1",
"driver_kind": "webdriver_selenium",
"driver_key": "selenium",
"engine": engine,
"binding": binding_payload(engine, route_id, root),
"browser_ws": "ws://127.0.0.1:9333/devtools/browser/abc",
"cdp_port": 9333,
"expect_product": "Moli/0.1.0",
"expect_ua": "MoliUA/1.0",
"expect_product_live": "MoliLive/0.1",
"expect_browser_name": "moli",
"transport_policy": transport_policy,
"task_url": "http://127.0.0.1:18080/l1/core",
"steps": [],
"checks": [{"kind": "saved_truthy", "name": "answer"}],
"connect_timeout_ms": 15_000,
"task_timeout_ms": 30_000,
"artifact_dir": str(root / "artifacts"),
}
class HangingSessionHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.server.request_count += 1
time.sleep(2)
try:
self.send_response(500)
self.end_headers()
except (BrokenPipeError, ConnectionResetError):
pass
def log_message(self, *args):
pass
@pytest.fixture
def hanging_session_server():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), HangingSessionHandler)
server.daemon_threads = True
server.request_count = 0
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
host, port = server.server_address
yield f"http://{host}:{port}", server
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_native_webdriver_options_use_binding_browser_name_without_chrome_capabilities():
capabilities = selenium_adapter.native_webdriver_options(
"moli",
connect_timeout_ms=15_000,
).to_capabilities()
assert capabilities["browserName"] == "moli"
assert capabilities["timeouts"] == {
"pageLoad": 15_000,
"script": 20_000,
}
assert "goog:chromeOptions" not in capabilities
def test_native_session_creation_honors_connect_timeout(hanging_session_server):
server_url, server = hanging_session_server
started = time.monotonic()
with pytest.raises(Exception):
selenium_adapter.start_native_webdriver(
server_url,
"moli",
100,
)
assert time.monotonic() - started < 0.8
assert server.request_count == 1
def test_session_request_tracker_marks_only_after_request_construction():
commands: list[str] = []
requests: list[tuple] = []
class Connection:
def request(self, *args, **kwargs):
requests.append((args, kwargs))
return {"value": None}
class Executor:
def __init__(self):
self._conn = Connection()
def execute(self, command, params):
json.dumps(params)
commands.append(command)
if command == "newSession":
return self._conn.request("POST", "/session")
return {"value": None}
executor = Executor()
original_connection = executor._conn
tracker = selenium_adapter.SessionRequestTracker(executor)
tracker.execute("status", {})
assert tracker.request_started is False
with pytest.raises(TypeError):
tracker.execute("newSession", {"not_json": {object()}})
assert tracker.request_started is False
tracker.execute("newSession", {})
assert tracker.request_started is True
assert commands == ["status", "newSession"]
assert len(requests) == 1
tracker.restore()
assert executor._conn is original_connection
def test_session_request_tracker_marks_transport_error_and_restores_boundary():
class Connection:
def request(self, *args, **kwargs):
raise ConnectionError("request reached transport")
class Executor:
def __init__(self):
self._conn = Connection()
def execute(self, command, params):
return self._conn.request("POST", "/session")
executor = Executor()
original_connection = executor._conn
tracker = selenium_adapter.SessionRequestTracker(executor)
with pytest.raises(ConnectionError, match="reached transport"):
tracker.execute("newSession", {})
assert tracker.request_started is True
tracker.restore()
assert executor._conn is original_connection
def test_session_request_tracker_rejects_missing_transport_boundary():
with pytest.raises(
selenium_adapter.SeleniumClientConfigurationError,
match="does not expose its HTTP request boundary",
):
selenium_adapter.SessionRequestTracker(object())
def test_repository_bridge_uses_http_status_and_closes_port_idempotently(tmp_path):
executable, state_path, request_path = make_http_chromedriver(tmp_path)
port = selenium_adapter.free_port()
bridge = selenium_adapter.ChromeDriverBridge(executable, port)
process = None
try:
bridge.start_until(time.monotonic() + 2)
process = bridge.process
assert process is not None
state = json.loads(state_path.read_text(encoding="utf-8"))
assert state["pid"] == process.pid
assert state["port"] == port
assert state["argv"] == ["--enable-chrome-logs", f"--port={port}"]
assert port_is_open(port)
assert not request_path.exists()
bridge.stop()
bridge.stop()
assert process.poll() is not None
wait_for_process_absent(process.pid)
assert not port_is_open(port)
finally:
if process is not None and process.poll() is None:
process.kill()
process.wait(timeout=1)
def test_repository_bridge_rejects_tcp_only_not_ready_service(tmp_path):
executable, state_path, request_path = make_http_chromedriver(
tmp_path,
ready=False,
)
port = selenium_adapter.free_port()
bridge = selenium_adapter.ChromeDriverBridge(executable, port)
started = time.monotonic()
with pytest.raises(
selenium_adapter.SeleniumClientConfigurationError,
match="HTTP service did not become ready",
):
bridge.start_until(time.monotonic() + 1.0)
assert time.monotonic() - started < 1.5
state = json.loads(state_path.read_text(encoding="utf-8"))
wait_for_process_absent(state["pid"])
assert not port_is_open(port)
assert not request_path.exists()
def test_repository_bridge_escalates_sigterm_and_reaps_before_deadline(tmp_path):
executable, state_path, _ = make_http_chromedriver(
tmp_path,
ignore_sigterm=True,
)
port = selenium_adapter.free_port()
bridge = selenium_adapter.ChromeDriverBridge(executable, port)
process = None
try:
bridge.start_until(time.monotonic() + 2)
process = bridge.process
assert process is not None
assert json.loads(state_path.read_text(encoding="utf-8"))["pid"] == process.pid
assert port_is_open(port)
started = time.monotonic()
deadline = started + 0.5
bridge.stop(deadline=deadline)
elapsed = time.monotonic() - started
bridge.stop(deadline=deadline)
assert elapsed <= 0.7
assert bridge.process is None
assert process.returncode == -signal.SIGKILL
wait_for_process_absent(process.pid)
assert not port_is_open(port)
finally:
if process is not None and process.poll() is None:
process.kill()
process.wait(timeout=1)
def test_repository_bridge_cleanup_interrupt_preserves_interrupt_and_reaps(
tmp_path,
monkeypatch,
):
executable, _, _ = make_http_chromedriver(
tmp_path,
ignore_sigterm=True,
)
port = selenium_adapter.free_port()
bridge = selenium_adapter.ChromeDriverBridge(executable, port)
process = None
try:
bridge.start_until(time.monotonic() + 2)
process = bridge.process
assert process is not None
real_wait = process.wait
interruption = KeyboardInterrupt()
calls = 0
def interrupting_wait(*args, **kwargs):
nonlocal calls
calls += 1
if calls == 1:
raise interruption
return real_wait(*args, **kwargs)
monkeypatch.setattr(process, "wait", interrupting_wait)
with pytest.raises(KeyboardInterrupt) as raised:
bridge.stop(deadline=time.monotonic() + 0.5)
assert raised.value is interruption
assert bridge.process is None
assert process.returncode == -signal.SIGKILL
wait_for_process_absent(process.pid)
assert not port_is_open(port)
finally:
if process is not None and process.poll() is None:
process.kill()
real_wait = getattr(process, "wait")
real_wait(timeout=1)
def test_repository_bridge_early_exit_is_local_configuration_error(tmp_path):
executable = make_executable(tmp_path)
bridge = selenium_adapter.ChromeDriverBridge(
executable,
selenium_adapter.free_port(),
)
with pytest.raises(
selenium_adapter.SeleniumClientConfigurationError,
match="exited before HTTP readiness with code 0",
):
bridge.start_until(time.monotonic() + 1)
bridge.stop()
def test_real_new_session_success_uses_owned_bridge(tmp_path):
executable, state_path, request_path = make_http_chromedriver(tmp_path)
driver = bridge = process = None
try:
driver, bridge = selenium_adapter.start_chromedriver_webdriver(
executable,
"127.0.0.1:9333",
2000,
)
process = bridge.process
assert process is not None
assert driver.session_id == "fake-session"
assert "POST /session" in request_path.read_text(encoding="utf-8")
assert json.loads(state_path.read_text(encoding="utf-8"))["pid"] == process.pid
driver.quit()
driver = None
bridge.stop()
bridge.stop()
wait_for_process_absent(process.pid)
assert not port_is_open(bridge.port)
finally:
if driver is not None:
try:
driver.quit()
except Exception:
pass
if bridge is not None:
bridge.stop()
if process is not None and process.poll() is None:
process.kill()
process.wait(timeout=1)
def test_real_post_new_session_failure_is_compatibility_exception_and_reaps_bridge(
tmp_path,
):
executable, state_path, request_path = make_http_chromedriver(
tmp_path,
reject_session=True,
)
with pytest.raises(Exception, match="fake session rejection") as raised:
selenium_adapter.start_chromedriver_webdriver(
executable,
"127.0.0.1:9333",
1000,
)
assert not isinstance(
raised.value,
selenium_adapter.SeleniumClientConfigurationError,
)
state = json.loads(state_path.read_text(encoding="utf-8"))
assert "POST /session" in request_path.read_text(encoding="utf-8")
wait_for_process_absent(state["pid"])
assert not port_is_open(state["port"])
def test_repository_bridge_keyboard_interrupt_reaps_real_process(
tmp_path,
monkeypatch,
):
executable, _, _ = make_http_chromedriver(tmp_path, ready=False)
bridge = selenium_adapter.ChromeDriverBridge(
executable,
selenium_adapter.free_port(),
)
processes: list[subprocess.Popen] = []
real_popen = selenium_adapter.subprocess.Popen
def capturing_popen(*args, **kwargs):
process = real_popen(*args, **kwargs)
processes.append(process)
return process
monkeypatch.setattr(selenium_adapter.subprocess, "Popen", capturing_popen)
monkeypatch.setattr(
selenium_adapter,
"chromedriver_status_ready",
lambda *args: (_ for _ in ()).throw(KeyboardInterrupt()),
)
with pytest.raises(KeyboardInterrupt):
bridge.start_until(time.monotonic() + 1)
assert len(processes) == 1
wait_for_process_absent(processes[0].pid)
def test_real_bridge_startup_failure_is_structured_script_error(
tmp_path,
monkeypatch,
):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("chrome", "chromedriver_cdp", tmp_path)
emitted: list[dict] = []
monkeypatch.setattr(
selenium_adapter.sys,
"stdin",
io.StringIO(json.dumps(payload)),
)
monkeypatch.setattr(selenium_adapter, "emit", emitted.append)
monkeypatch.setattr(
selenium_adapter,
"http_json",
lambda *args: {
"Browser": payload["expect_product"],
"User-Agent": payload["expect_ua"],
"webSocketDebuggerUrl": payload["browser_ws"],
},
)
selenium_adapter.main()
result = emitted[0]
assert result["ok"] is False
assert result["error"]["class"] == "script_error"
assert "exited before HTTP readiness with code 0" in result["error"]["message"]
assert "checks" not in result["observations"]
def test_real_post_new_session_failure_is_main_compatibility_evidence(
tmp_path,
monkeypatch,
):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("chrome", "chromedriver_cdp", tmp_path)
fake_executable, state_path, request_path = make_http_chromedriver(
tmp_path,
reject_session=True,
)
pinned_executable = pathlib.Path(
payload["binding"]["pins"]["bridges"][0]["executable"]
)
pinned_executable.write_bytes(fake_executable.read_bytes())
pinned_executable.chmod(0o755)
payload["binding"]["pins"]["bridges"][0]["metadata"]["sha256_12"] = (
hashlib.sha256(pinned_executable.read_bytes()).hexdigest()[:12]
)
emitted: list[dict] = []
monkeypatch.setattr(
selenium_adapter.sys,
"stdin",
io.StringIO(json.dumps(payload)),
)
monkeypatch.setattr(selenium_adapter, "emit", emitted.append)
monkeypatch.setattr(
selenium_adapter,
"http_json",
lambda *args: {
"Browser": payload["expect_product"],
"User-Agent": payload["expect_ua"],
"webSocketDebuggerUrl": payload["browser_ws"],
},
)
selenium_adapter.main()
result = emitted[0]
assert result["ok"] is True
assert result["observations"]["failure_class"] == "cdp_semantic"
assert "fake session rejection" in result["observations"]["connect_error"]
assert result["observations"]["checks"][0]["name"] == "driver_connect"
assert result["observations"]["checks"][0]["status"] == "fail"
assert "POST /session" in request_path.read_text(encoding="utf-8")
state = json.loads(state_path.read_text(encoding="utf-8"))
wait_for_process_absent(state["pid"])
assert not port_is_open(state["port"])
def test_bridge_session_creation_honors_timeout_and_stops_bridge(
tmp_path,
monkeypatch,
hanging_session_server,
):
server_url, server = hanging_session_server
executable = make_executable(tmp_path)
stop_calls: list[bool] = []
class FakeBridge:
def __init__(self, path, port):
self.path = path
self.port = port
self.service_url = server_url
def start_until(self, deadline, *, cleanup_deadline=None):
pass
def stop(self, *, deadline=None):
stop_calls.append(True)
monkeypatch.setattr(
selenium_adapter,
"ChromeDriverBridge",
FakeBridge,
)
started = time.monotonic()
with pytest.raises(Exception):
selenium_adapter.start_chromedriver_webdriver(
executable,
"127.0.0.1:9333",
300,
)
assert time.monotonic() - started < 1.0
assert server.request_count == 1
assert stop_calls == [True]
def test_bridge_http_readiness_shares_connect_deadline_and_stops_once(
tmp_path,
monkeypatch,
):
executable = make_executable(tmp_path)
stop_calls: list[bool] = []
starts: list[str] = []
class NeverReadyBridge:
def __init__(self, path, port):
self.path = path
self.port = port
self.service_url = f"http://127.0.0.1:{port}"
self.stopped = False
def start_until(self, deadline, *, cleanup_deadline=None):
starts.append(str(self.path))
while time.monotonic() < deadline:
time.sleep(0.005)
self.stop(deadline=cleanup_deadline)
raise selenium_adapter.SeleniumClientConfigurationError(
"ChromeDriver HTTP service did not become ready before connect timeout"
)
def stop(self, *, deadline=None):
if not self.stopped:
self.stopped = True
stop_calls.append(True)
monkeypatch.setattr(
selenium_adapter,
"ChromeDriverBridge",
NeverReadyBridge,
)
monkeypatch.setattr(
"selenium.webdriver.Remote",
lambda **kwargs: pytest.fail("session POST must not start before service readiness"),
)
started = time.monotonic()
with pytest.raises(
selenium_adapter.SeleniumClientConfigurationError,
match="did not become ready",
):
selenium_adapter.start_chromedriver_webdriver(
executable,
"127.0.0.1:9333",
100,
)
assert time.monotonic() - started < 0.35
assert starts == [str(executable)]
assert stop_calls == [True]
def test_normalized_route_overrides_engine_and_legacy_transport_policy(tmp_path, monkeypatch):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
calls: list[tuple] = []
monkeypatch.setattr(
selenium_adapter,
"start_native_webdriver",
lambda endpoint, browser_name, timeout: calls.append(
("native", endpoint, browser_name, timeout)
)
or "native-driver",
)
monkeypatch.setattr(
selenium_adapter,
"start_chromedriver_webdriver",
lambda executable, endpoint, timeout, cleanup_deadline: calls.append(
("bridge", executable, endpoint, timeout, cleanup_deadline)
)
or ("bridge-driver", "service"),
)
# Chrome follows a synthetic native binding; no engine-name inference.
chrome_native = adapter_payload(
"chrome",
"native_webdriver",
tmp_path,
transport_policy="chromedriver_cdp",
)
native_binding = selenium_adapter.validate_runtime_binding(chrome_native)
assert selenium_adapter.connect_webdriver(chrome_native, native_binding, 1234) == (
"native-driver",
None,
)
# Moli follows a synthetic bridge binding even though legacy metadata says native.
moli_bridge = adapter_payload(
"moli",
"chromedriver_cdp",
tmp_path,
transport_policy="engine_native",
)
bridge_binding = selenium_adapter.validate_runtime_binding(moli_bridge)
assert selenium_adapter.connect_webdriver(moli_bridge, bridge_binding, 4321) == (
"bridge-driver",
"service",
)
assert [row[0] for row in calls] == ["native", "bridge"]
assert calls[-1][-1] is None
def test_native_route_never_resolves_or_checks_chromedriver(tmp_path, monkeypatch):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("moli", "native_webdriver", tmp_path)
monkeypatch.setattr(
selenium_adapter,
"_bridge_executable",
lambda binding: pytest.fail("native route must not inspect ChromeDriver"),
)
monkeypatch.setattr(
selenium_adapter,
"start_native_webdriver",
lambda *args: "native-driver",
)
binding = selenium_adapter.validate_runtime_binding(payload)
assert selenium_adapter.connect_webdriver(payload, binding, 15000) == (
"native-driver",
None,
)
@pytest.mark.parametrize(
("mutation", "message"),
[
(lambda payload: payload.pop("binding"), "payload.binding must be an object"),
(
lambda payload: payload["binding"].update(browser_id="chrome"),
"does not match payload.engine",
),
(
lambda payload: payload["binding"].update(driver_id="playwright"),
"must be `selenium`",
),
(
lambda payload: payload["binding"]["route"].update(route_id="mystery"),
"unknown Selenium route",
),
(
lambda payload: payload["binding"]["route"].pop("ordered_hops"),
"ordered_hops must be a non-empty list",
),
(
lambda payload: payload["binding"].update(fallback_allowed=True),
"fallback_allowed must be false",
),
],
)
def test_invalid_binding_is_rejected_without_fallback(
tmp_path,
monkeypatch,
mutation,
message,
):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("moli", "native_webdriver", tmp_path)
mutation(payload)
with pytest.raises(selenium_adapter.BindingPayloadError, match=message):
selenium_adapter.validate_runtime_binding(payload)
def test_semantically_mutated_route_is_rejected_before_driver_construction(
tmp_path,
monkeypatch,
):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("moli", "native_webdriver", tmp_path)
payload["binding"]["route"]["provider"] = "chromedriver"
monkeypatch.setattr(
selenium_adapter,
"start_native_webdriver",
lambda *args: pytest.fail("invalid binding must fail before construction"),
)
with pytest.raises(
selenium_adapter.BindingPayloadError,
match="provider does not match",
):
selenium_adapter.validate_runtime_binding(payload)
def test_missing_binding_fails_before_http_or_driver_construction(
tmp_path,
monkeypatch,
):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("moli", "native_webdriver", tmp_path)
payload.pop("binding")
emitted: list[dict] = []
monkeypatch.setattr(selenium_adapter.sys, "stdin", io.StringIO(json.dumps(payload)))
monkeypatch.setattr(selenium_adapter, "emit", emitted.append)
monkeypatch.setattr(
selenium_adapter,
"http_json",
lambda *args: pytest.fail("invalid binding must fail before HTTP"),
)
monkeypatch.setattr(
selenium_adapter,
"connect_webdriver",
lambda *args: pytest.fail("invalid binding must fail before driver construction"),
)
selenium_adapter.main()
assert emitted[0]["ok"] is False
assert emitted[0]["error"]["class"] == "script_error"
assert "payload.binding" in emitted[0]["error"]["message"]
def test_connect_failure_is_compatibility_evidence_not_skip_or_script_error(
tmp_path,
monkeypatch,
):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("moli", "native_webdriver", tmp_path)
emitted: list[dict] = []
monkeypatch.setattr(selenium_adapter.sys, "stdin", io.StringIO(json.dumps(payload)))
monkeypatch.setattr(selenium_adapter, "emit", emitted.append)
monkeypatch.setattr(
selenium_adapter,
"http_json",
lambda *args: {
"Browser": payload["expect_product"],
"User-Agent": payload["expect_ua"],
"webSocketDebuggerUrl": payload["browser_ws"],
},
)
monkeypatch.setattr(
selenium_adapter,
"connect_webdriver",
lambda *args: (_ for _ in ()).throw(RuntimeError("session rejected")),
)
selenium_adapter.main()
result = emitted[0]
assert result["ok"] is True
assert result["observations"]["connect_error"] == "session rejected"
assert result["observations"]["binding"]["binding_id"] == "moli__selenium"
assert result["observations"]["binding"]["route_id"] == "native_webdriver"
assert result["observations"]["checks"][0]["name"] == "driver_connect"
assert result["observations"]["checks"][0]["status"] == "fail"
assert "skip" not in result
def test_missing_client_import_is_script_error_not_compatibility(
tmp_path,
monkeypatch,
):
monkeypatch.setattr(selenium_adapter, "BENCH_ROOT", tmp_path)
payload = adapter_payload("moli", "native_webdriver", tmp_path)
emitted: list[dict] = []
monkeypatch.setattr(
selenium_adapter.sys,
"stdin",
io.StringIO(json.dumps(payload)),
)
monkeypatch.setattr(selenium_adapter, "emit", emitted.append)
monkeypatch.setattr(
selenium_adapter,
"http_json",
lambda *args: {
"Browser": payload["expect_product"],
"User-Agent": payload["expect_ua"],
"webSocketDebuggerUrl": payload["browser_ws"],
},
)
monkeypatch.setattr(
selenium_adapter,
"connect_webdriver",