@testver/testver 1.2.4 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,535 +1,553 @@
1
- """
2
- Testver Appium agent for pytest + Appium-Python-Client.
3
-
4
- Loaded automatically by Testver via:
5
- PYTHONPATH += <this dir>
6
- PYTEST_ADDOPTS += -p testver_appium
7
-
8
- It monkey-patches the Appium Python client's ``Remote`` driver so an
9
- UNMODIFIED test project transparently:
10
-
11
- 1. Redirects the driver's command_executor to the Testver-provided
12
- Appium hub (cloud or local) and injects device / app / platform /
13
- provider capabilities from the TESTVER_* env vars.
14
- 2. Reports the live cloud session id back to Testver so the Runner's
15
- live-preview panel can stream screenshots (register-external).
16
- 3. Attaches to an existing session when TESTVER_REUSE_SESSION_ID is
17
- set (skips booting a fresh device), suppresses the test's quit()
18
- so it doesn't kill the shared session, and resets the app to a
19
- fresh launch.
20
-
21
- This is the Python port of src/mobile/wdio-bootstrap/bootstrap.cjs.
22
-
23
- No-op when the TESTVER_* env vars aren't present, so importing this
24
- module in a non-Testver run changes nothing.
25
- """
26
-
27
- import os
28
- import sys
29
- import json
30
- import atexit
31
-
32
- try: # stdlib only — never add a runtime dependency to the user's project
33
- from urllib import request as _urllib_request
34
- from urllib.parse import quote as _urlquote
35
- except Exception: # pragma: no cover
36
- _urllib_request = None
37
- _urlquote = None
38
-
39
-
40
- def _enabled():
41
- return bool(os.environ.get("TESTVER_PROVIDER") or os.environ.get("APPIUM_HUB_HOST"))
42
-
43
-
44
- def _log(msg):
45
- try:
46
- sys.stderr.write("[testver-appium] " + str(msg) + "\n")
47
- sys.stderr.flush()
48
- except Exception:
49
- pass
50
-
51
-
52
- # ── W3C capability handling ──────────────────────────────────────────────────
53
-
54
- _W3C_STANDARD = {
55
- "browserName", "browserVersion", "platformName", "acceptInsecureCerts",
56
- "pageLoadStrategy", "proxy", "setWindowRect", "timeouts",
57
- "strictFileInteractability", "unhandledPromptBehavior", "webSocketUrl",
58
- }
59
-
60
-
61
- def _prefix_key(key):
62
- """Namespace a legacy Appium cap under ``appium:`` for W3C servers."""
63
- if ":" in key or key in _W3C_STANDARD:
64
- return key
65
- return "appium:" + key
66
-
67
-
68
- def _vendor_from_testver():
69
- """The vendor block Testver built for this run (each vendor's own field
70
- names, the tunnel, the picked device) — TESTVER_VENDOR_OPTIONS."""
71
- raw = os.environ.get("TESTVER_VENDOR_OPTIONS")
72
- if not raw:
73
- return None
74
- try:
75
- block = json.loads(raw)
76
- return block if isinstance(block, dict) and block.get("key") else None
77
- except Exception:
78
- return None
79
-
80
-
81
- def _provider_options_block(existing):
82
- """Build the provider-specific options block (bstack:/sauce:/LT:)."""
83
- vendor = _vendor_from_testver()
84
- if vendor:
85
- # names / tunnel: the project's own values win; the device picked in
86
- # the Runner wins over the project's
87
- merged = dict(vendor.get("options") or {})
88
- merged.update(existing or {})
89
- merged.update(vendor.get("overrides") or {})
90
- return merged
91
- provider = os.environ.get("TESTVER_PROVIDER")
92
- device = os.environ.get("TESTVER_DEVICE_NAME")
93
- os_ver = os.environ.get("TESTVER_PLATFORM_VERSION")
94
- base = dict(existing or {})
95
- base.setdefault("projectName", "Testver")
96
- # Same resolution chain as runCloudBuildName in api-runner — Testver's
97
- # session poller / artifact fetcher search the provider dashboard by
98
- # that name, so the capabilities must carry the SAME one (typed name
99
- # -> provider env default -> static literal as last resort).
100
- # Provider-KEYED (not a flat or-chain): this runs in the child process
101
- # with the user's full environment, so a stale machine-level var from
102
- # a different provider must never leak in.
103
- _build_var = {
104
- "browserstack": "BROWSERSTACK_BUILD_NAME",
105
- "saucelabs": "SAUCE_BUILD_NAME",
106
- "lambdatest": "LT_BUILD_NAME",
107
- }.get(provider or "")
108
- base.setdefault("buildName",
109
- os.environ.get("TESTVER_BUILD_NAME")
110
- or (os.environ.get(_build_var) if _build_var else None)
111
- or "testver-cloud-run")
112
- base.setdefault("sessionName", os.environ.get("TESTVER_SESSION_NAME") or "mobile-test")
113
- if provider in ("browserstack", "saucelabs"):
114
- if device and "deviceName" not in base:
115
- base["deviceName"] = device
116
- if os_ver:
117
- if provider == "browserstack" and "osVersion" not in base:
118
- base["osVersion"] = os_ver
119
- elif provider == "saucelabs" and "platformVersion" not in base:
120
- base["platformVersion"] = os_ver
121
- elif provider == "lambdatest":
122
- if device and "deviceName" not in base:
123
- base["deviceName"] = device
124
- if os_ver and "platformVersion" not in base:
125
- base["platformVersion"] = os_ver
126
- return base
127
-
128
-
129
- def _provider_options_key():
130
- vendor = _vendor_from_testver()
131
- if vendor:
132
- return vendor.get("key")
133
- return {
134
- "browserstack": "bstack:options",
135
- "saucelabs": "sauce:options",
136
- "lambdatest": "lt:options",
137
- }.get(os.environ.get("TESTVER_PROVIDER"))
138
-
139
-
140
- def _env_json(name):
141
- try:
142
- value = json.loads(os.environ.get(name) or "{}")
143
- return value if isinstance(value, dict) else {}
144
- except ValueError:
145
- return {}
146
-
147
-
148
- def _apply_local_caps(caps):
149
- """Local Devices (Settings → Local Devices): capabilities the project
150
- doesn't set itself (TESTVER_LOCAL_CAPS_DEFAULTS — WebDriverAgent port and
151
- signing), then Testver's own over the project's (TESTVER_LOCAL_CAPS —
152
- app launch mode)."""
153
- for k, v in _env_json("TESTVER_LOCAL_CAPS_DEFAULTS").items():
154
- bare = k[len("appium:"):] if k.startswith("appium:") else k
155
- if k not in caps and bare not in caps:
156
- caps[k] = v
157
- for k, v in _env_json("TESTVER_LOCAL_CAPS").items():
158
- bare = k[len("appium:"):] if k.startswith("appium:") else k
159
- caps.pop(bare, None)
160
- caps[k] = v
161
-
162
-
163
- def _apply_caps_to_dict(caps):
164
- """Mutate a flat capabilities dict in place with Testver overrides."""
165
- # Normalise any legacy unprefixed Appium keys.
166
- for k in list(caps.keys()):
167
- nk = _prefix_key(k)
168
- if nk != k:
169
- caps[nk] = caps.pop(k)
170
-
171
- plat = os.environ.get("TESTVER_PLATFORM_NAME")
172
- device = os.environ.get("TESTVER_DEVICE_NAME")
173
- os_ver = os.environ.get("TESTVER_PLATFORM_VERSION")
174
- app = os.environ.get("TESTVER_APP_URL")
175
-
176
- if plat:
177
- caps["platformName"] = plat
178
- if device:
179
- caps["appium:deviceName"] = device
180
- if os_ver:
181
- caps["appium:platformVersion"] = os_ver
182
- # The device: a local one by its serial / udid (Appium picks the device
183
- # by appium:udid, never by deviceName); on a vendor's cloud a local
184
- # udid / AVD means nothing.
185
- udid = os.environ.get("TESTVER_DEVICE_UDID")
186
- if os.environ.get("TESTVER_PROVIDER") == "local-appium":
187
- if udid:
188
- caps["appium:udid"] = udid
189
- caps.pop("appium:avd", None)
190
- _apply_local_caps(caps)
191
- else:
192
- caps.pop("appium:udid", None)
193
- caps.pop("appium:avd", None)
194
- if app:
195
- # the project's own package / bundle id, for the reset on a reused
196
- # session (it is dropped from the caps just below)
197
- _project_app_id["value"] = (caps.get("appium:appPackage") or caps.get("appium:bundleId")
198
- or _project_app_id["value"])
199
- caps["appium:app"] = app
200
- # Drop app-identifier caps that may belong to a different build —
201
- # cloud providers auto-detect these from the uploaded binary.
202
- for stale in ("appium:appPackage", "appium:appActivity",
203
- "appium:appWaitActivity", "appium:appWaitPackage",
204
- "appium:bundleId", "appium:appWaitForLaunch"):
205
- caps.pop(stale, None)
206
-
207
- if not caps.get("appium:automationName"):
208
- caps["appium:automationName"] = (
209
- "XCUITest" if str(caps.get("platformName", "")).lower() == "ios"
210
- else "UiAutomator2"
211
- )
212
-
213
- pkey = _provider_options_key()
214
- if pkey:
215
- # the project's own spelling of the block (`LT:Options` / `lt:options`)
216
- if pkey not in caps:
217
- pkey = next((k for k in caps if isinstance(k, str) and k.lower() == pkey.lower()), pkey)
218
- caps[pkey] = _provider_options_block(caps.get(pkey))
219
- return caps
220
-
221
-
222
- def _inject_into_options(options):
223
- """Apply overrides onto an AppiumOptions / BaseOptions instance."""
224
- try:
225
- existing = {}
226
- try:
227
- existing = dict(options.to_capabilities() or {})
228
- except Exception:
229
- existing = {}
230
- merged = _apply_caps_to_dict(dict(existing))
231
- for name, value in merged.items():
232
- try:
233
- options.set_capability(name, value)
234
- except Exception:
235
- pass
236
- # Caps that _apply_caps_to_dict deliberately removed (the stale
237
- # app-identifier caps when an app URL is supplied) must be deleted
238
- # from the options object too — set_capability only adds/overwrites.
239
- # (by the namespaced name: a legacy `automationName` the client lists
240
- # unprefixed lives on as `appium:automationName` — it isn't dropped)
241
- dropped = {k for k in existing.keys() if _prefix_key(k) not in merged}
242
- for k in dropped:
243
- removed = False
244
- internal = getattr(options, "_caps", None)
245
- if isinstance(internal, dict):
246
- for variant in (k, _prefix_key(k), k.replace("appium:", "")):
247
- if internal.pop(variant, None) is not None:
248
- removed = True
249
- if not removed:
250
- try:
251
- options.set_capability(k, None)
252
- except Exception:
253
- pass
254
- except Exception as exc: # pragma: no cover
255
- _log("options injection failed: " + str(exc))
256
-
257
-
258
- # ── Hub URL / reportback ─────────────────────────────────────────────────────
259
-
260
- def _hub_url_with_creds():
261
- proto = os.environ.get("APPIUM_HUB_PROTOCOL") or "https"
262
- host = os.environ.get("APPIUM_HUB_HOST")
263
- if not host:
264
- return None
265
- default_port = "443" if proto == "https" else "80"
266
- port = os.environ.get("APPIUM_HUB_PORT") or default_port
267
- path = os.environ.get("APPIUM_HUB_PATH") or "/wd/hub"
268
- user = os.environ.get("APPIUM_HUB_USER") or ""
269
- key = os.environ.get("APPIUM_HUB_KEY") or ""
270
- if _urlquote:
271
- user = _urlquote(user)
272
- key = _urlquote(key)
273
- cred = (user + ":" + key + "@") if (user or key) else ""
274
- return "{0}://{1}{2}:{3}{4}".format(proto, cred, host, port, path)
275
-
276
-
277
- def _post_json(endpoint, payload):
278
- if not (_urllib_request and endpoint):
279
- return
280
- try:
281
- data = json.dumps(payload).encode("utf-8")
282
- req = _urllib_request.Request(
283
- endpoint, data=data,
284
- headers={"Content-Type": "application/json"}, method="POST",
285
- )
286
- _urllib_request.urlopen(req, timeout=3).read()
287
- except Exception as exc:
288
- _log("reportback POST failed (" + endpoint + "): " + str(exc))
289
-
290
-
291
- def _report_external_session(driver):
292
- base = os.environ.get("TESTVER_REPORTBACK_URL")
293
- client_id = os.environ.get("TESTVER_CLIENT_ID")
294
- sid = getattr(driver, "session_id", None)
295
- if not (base and client_id and sid):
296
- return
297
- hub = _hub_url_with_creds()
298
- if not hub:
299
- return
300
- endpoint = base.rstrip("/") + "/api/mobile/session/register-external"
301
- _post_json(endpoint, {
302
- "clientId": client_id,
303
- "sessionId": sid,
304
- "hubUrl": hub,
305
- "deviceName": os.environ.get("TESTVER_DEVICE_NAME"),
306
- "platformName": os.environ.get("TESTVER_PLATFORM_NAME"),
307
- "providerId": os.environ.get("TESTVER_PROVIDER"),
308
- # the run that opened it (several runs of one tab side by side)
309
- "runId": os.environ.get("TESTVER_RUN_ID"),
310
- })
311
- _log("Reported session " + str(sid)[:12] + "... for live preview")
312
-
313
-
314
- _unreported = {"done": False}
315
-
316
-
317
- def _unreport_external_session():
318
- if _unreported["done"]:
319
- return
320
- _unreported["done"] = True
321
- base = os.environ.get("TESTVER_REPORTBACK_URL")
322
- client_id = os.environ.get("TESTVER_CLIENT_ID")
323
- if not (base and client_id):
324
- return
325
- endpoint = base.rstrip("/") + "/api/mobile/session/unregister-external"
326
- _post_json(endpoint, {"clientId": client_id})
327
-
328
-
329
- # ── App reset on attach ──────────────────────────────────────────────────────
330
-
331
- _project_app_id = {"value": None}
332
-
333
-
334
- def _reset_app_on_attach(driver, caps):
335
- if os.environ.get("TESTVER_SKIP_APP_RESET") == "1":
336
- return
337
- app_id = (
338
- (caps or {}).get("appium:appPackage")
339
- or (caps or {}).get("appium:bundleId")
340
- or _project_app_id["value"]
341
- or os.environ.get("TESTVER_APP_PACKAGE")
342
- or os.environ.get("TESTVER_APP_BUNDLE_ID")
343
- )
344
- if not app_id:
345
- _log("App reset on attach skipped — no appPackage/bundleId available")
346
- return
347
- platform = str((caps or {}).get("platformName")
348
- or os.environ.get("TESTVER_PLATFORM_NAME") or "").lower()
349
- is_android = platform == "android"
350
- try:
351
- if is_android and os.environ.get("TESTVER_SKIP_APP_CLEAR") != "1":
352
- try:
353
- driver.execute_script("mobile: clearApp", {"appId": app_id})
354
- except Exception:
355
- pass
356
- try:
357
- driver.execute_script("mobile: terminateApp", {"appId": app_id})
358
- except Exception:
359
- pass
360
- driver.execute_script("mobile: activateApp", {"appId": app_id})
361
- _log("App '" + app_id + "' reset to fresh launch on attached session")
362
- except Exception as exc:
363
- _log("App reset failed: " + str(exc))
364
-
365
-
366
- # ── Driver patching ──────────────────────────────────────────────────────────
367
-
368
- _patched = {"done": False}
369
-
370
-
371
- def _patch_remote(remote_cls):
372
- if remote_cls is None or getattr(remote_cls, "_testver_patched", False):
373
- return
374
- orig_init = remote_cls.__init__
375
- orig_start = getattr(remote_cls, "start_session", None)
376
- orig_quit = getattr(remote_cls, "quit", None)
377
-
378
- def new_init(self, *args, **kwargs):
379
- # 1. Redirect command_executor to the Testver hub.
380
- hub = os.environ.get("APPIUM_HUB_URL")
381
- if hub:
382
- if "command_executor" in kwargs:
383
- kwargs["command_executor"] = hub
384
- elif args:
385
- args = (hub,) + tuple(args[1:])
386
- else:
387
- kwargs["command_executor"] = hub
388
- # Appium-Python-Client 5+ (and AppiumLibrary 3+) pass a
389
- # client_config whose server address wins over command_executor.
390
- cc = kwargs.get("client_config")
391
- if cc is not None and hasattr(cc, "remote_server_addr"):
392
- try:
393
- cc.remote_server_addr = hub
394
- user = os.environ.get("APPIUM_HUB_USER") or ""
395
- key = os.environ.get("APPIUM_HUB_KEY") or ""
396
- if user and hasattr(cc, "username"):
397
- cc.username = user
398
- cc.password = key
399
- except Exception as exc: # pragma: no cover
400
- _log("could not redirect client_config: %s" % exc)
401
- # 2. Inject capabilities (AppiumOptions or desired_capabilities dict).
402
- opts = kwargs.get("options")
403
- if opts is None:
404
- for a in args:
405
- if hasattr(a, "set_capability") and hasattr(a, "to_capabilities"):
406
- opts = a
407
- break
408
- if opts is not None:
409
- _inject_into_options(opts)
410
- elif isinstance(kwargs.get("desired_capabilities"), dict):
411
- _apply_caps_to_dict(kwargs["desired_capabilities"])
412
-
413
- orig_init(self, *args, **kwargs)
414
-
415
- # 3. Live-preview reportback (best-effort).
416
- try:
417
- _report_external_session(self)
418
- except Exception:
419
- pass
420
- # 4. App reset when attached to a shared session.
421
- if os.environ.get("TESTVER_REUSE_SESSION_ID"):
422
- try:
423
- _reset_app_on_attach(self, getattr(self, "caps", None) or {})
424
- except Exception:
425
- pass
426
-
427
- def new_start_session(self, *a, **k):
428
- reuse = os.environ.get("TESTVER_REUSE_SESSION_ID")
429
- if reuse:
430
- # Attach instead of POST /session — skip booting a device.
431
- self.session_id = reuse
432
- caps = a[0] if a else k.get("capabilities")
433
- try:
434
- if isinstance(caps, dict):
435
- self.caps = caps.get("alwaysMatch", caps)
436
- else:
437
- self.caps = {}
438
- except Exception:
439
- self.caps = {}
440
- _log("Attached to live session " + reuse[:12] + "... (skipped device boot)")
441
- return None
442
- return orig_start(self, *a, **k)
443
-
444
- def new_quit(self, *a, **k):
445
- if os.environ.get("TESTVER_REUSE_SESSION_ID"):
446
- _log("quit() suppressed - session is SHARED with Testver")
447
- try:
448
- _unreport_external_session()
449
- except Exception:
450
- pass
451
- return None
452
- try:
453
- _unreport_external_session()
454
- except Exception:
455
- pass
456
- return orig_quit(self, *a, **k) if orig_quit else None
457
-
458
- remote_cls.__init__ = new_init
459
- if orig_start is not None:
460
- remote_cls.start_session = new_start_session
461
- if orig_quit is not None:
462
- remote_cls.quit = new_quit
463
- remote_cls._testver_patched = True
464
- _log("Appium Remote driver patched (provider=" +
465
- str(os.environ.get("TESTVER_PROVIDER")) + ")")
466
-
467
-
468
- def _patch_module(mod):
469
- if _patched["done"]:
470
- return
471
- remote = getattr(mod, "Remote", None) or getattr(mod, "WebDriver", None)
472
- if remote is not None:
473
- _patch_remote(remote)
474
- _patched["done"] = True
475
-
476
-
477
- # ── Post-import hook (works whether or not appium is imported yet) ────────────
478
-
479
- def _install():
480
- if not _enabled():
481
- return
482
- atexit.register(_unreport_external_session)
483
-
484
- # Already imported? Patch now.
485
- if "appium.webdriver" in sys.modules:
486
- _patch_module(sys.modules["appium.webdriver"])
487
- return
488
-
489
- import importlib.util
490
-
491
- class _Finder:
492
- def find_spec(self, fullname, path=None, target=None):
493
- if fullname != "appium.webdriver":
494
- return None
495
- try:
496
- sys.meta_path.remove(self)
497
- except ValueError:
498
- return None
499
- try:
500
- spec = importlib.util.find_spec(fullname)
501
- finally:
502
- sys.meta_path.insert(0, self)
503
- if spec is None or spec.loader is None:
504
- return None
505
- loader = spec.loader
506
- orig_exec = loader.exec_module
507
- finder = self
508
-
509
- def exec_module(module):
510
- orig_exec(module)
511
- try:
512
- _patch_module(module)
513
- finally:
514
- try:
515
- sys.meta_path.remove(finder)
516
- except ValueError:
517
- pass
518
-
519
- loader.exec_module = exec_module
520
- return spec
521
-
522
- sys.meta_path.insert(0, _Finder())
523
-
524
-
525
- # Install on import (pytest loads this module via `-p testver_appium`).
526
- _install()
527
-
528
-
529
- # ── pytest hooks (belt-and-suspenders) ───────────────────────────────────────
530
-
531
- def pytest_configure(config):
532
- # If appium was already imported by a conftest before our hook landed,
533
- # patch it now.
534
- if _enabled() and "appium.webdriver" in sys.modules:
535
- _patch_module(sys.modules["appium.webdriver"])
1
+ """
2
+ Testver Appium agent for pytest + Appium-Python-Client.
3
+
4
+ Loaded automatically by Testver via:
5
+ PYTHONPATH += <this dir>
6
+ PYTEST_ADDOPTS += -p testver_appium
7
+
8
+ It monkey-patches the Appium Python client's ``Remote`` driver so an
9
+ UNMODIFIED test project transparently:
10
+
11
+ 1. Redirects the driver's command_executor to the Testver-provided
12
+ Appium hub (cloud or local) and injects device / app / platform /
13
+ provider capabilities from the TESTVER_* env vars.
14
+ 2. Reports the live cloud session id back to Testver so the Runner's
15
+ live-preview panel can stream screenshots (register-external).
16
+ 3. Attaches to an existing session when TESTVER_REUSE_SESSION_ID is
17
+ set (skips booting a fresh device), suppresses the test's quit()
18
+ so it doesn't kill the shared session, and resets the app to a
19
+ fresh launch.
20
+
21
+ This is the Python port of src/mobile/wdio-bootstrap/bootstrap.cjs.
22
+
23
+ No-op when the TESTVER_* env vars aren't present, so importing this
24
+ module in a non-Testver run changes nothing.
25
+ """
26
+
27
+ import os
28
+ import sys
29
+ import json
30
+ import atexit
31
+
32
+ try: # stdlib only — never add a runtime dependency to the user's project
33
+ from urllib import request as _urllib_request
34
+ from urllib.parse import quote as _urlquote
35
+ except Exception: # pragma: no cover
36
+ _urllib_request = None
37
+ _urlquote = None
38
+
39
+
40
+ def _enabled():
41
+ return bool(os.environ.get("TESTVER_PROVIDER") or os.environ.get("APPIUM_HUB_HOST"))
42
+
43
+
44
+ def _log(msg):
45
+ try:
46
+ sys.stderr.write("[testver-appium] " + str(msg) + "\n")
47
+ sys.stderr.flush()
48
+ except Exception:
49
+ pass
50
+
51
+
52
+ # ── W3C capability handling ──────────────────────────────────────────────────
53
+
54
+ _W3C_STANDARD = {
55
+ "browserName", "browserVersion", "platformName", "acceptInsecureCerts",
56
+ "pageLoadStrategy", "proxy", "setWindowRect", "timeouts",
57
+ "strictFileInteractability", "unhandledPromptBehavior", "webSocketUrl",
58
+ }
59
+
60
+
61
+ def _prefix_key(key):
62
+ """Namespace a legacy Appium cap under ``appium:`` for W3C servers."""
63
+ if ":" in key or key in _W3C_STANDARD:
64
+ return key
65
+ return "appium:" + key
66
+
67
+
68
+ def _vendor_from_testver():
69
+ """The vendor block Testver built for this run (each vendor's own field
70
+ names, the tunnel, the picked device) — TESTVER_VENDOR_OPTIONS."""
71
+ raw = os.environ.get("TESTVER_VENDOR_OPTIONS")
72
+ if not raw:
73
+ return None
74
+ try:
75
+ block = json.loads(raw)
76
+ return block if isinstance(block, dict) and block.get("key") else None
77
+ except Exception:
78
+ return None
79
+
80
+
81
+ def _provider_options_block(existing):
82
+ """Build the provider-specific options block (bstack:/sauce:/LT:)."""
83
+ vendor = _vendor_from_testver()
84
+ if vendor:
85
+ # names / tunnel: the project's own values win; the device picked in
86
+ # the Runner wins over the project's
87
+ merged = dict(vendor.get("options") or {})
88
+ merged.update(existing or {})
89
+ merged.update(vendor.get("overrides") or {})
90
+ return merged
91
+ provider = os.environ.get("TESTVER_PROVIDER")
92
+ device = os.environ.get("TESTVER_DEVICE_NAME")
93
+ os_ver = os.environ.get("TESTVER_PLATFORM_VERSION")
94
+ base = dict(existing or {})
95
+ base.setdefault("projectName", "Testver")
96
+ # Same resolution chain as runCloudBuildName in api-runner — Testver's
97
+ # session poller / artifact fetcher search the provider dashboard by
98
+ # that name, so the capabilities must carry the SAME one (typed name
99
+ # -> provider env default -> static literal as last resort).
100
+ # Provider-KEYED (not a flat or-chain): this runs in the child process
101
+ # with the user's full environment, so a stale machine-level var from
102
+ # a different provider must never leak in.
103
+ _build_var = {
104
+ "browserstack": "BROWSERSTACK_BUILD_NAME",
105
+ "saucelabs": "SAUCE_BUILD_NAME",
106
+ "lambdatest": "LT_BUILD_NAME",
107
+ }.get(provider or "")
108
+ base.setdefault("buildName",
109
+ os.environ.get("TESTVER_BUILD_NAME")
110
+ or (os.environ.get(_build_var) if _build_var else None)
111
+ or "testver-cloud-run")
112
+ base.setdefault("sessionName", os.environ.get("TESTVER_SESSION_NAME") or "mobile-test")
113
+ if provider in ("browserstack", "saucelabs"):
114
+ if device and "deviceName" not in base:
115
+ base["deviceName"] = device
116
+ if os_ver:
117
+ if provider == "browserstack" and "osVersion" not in base:
118
+ base["osVersion"] = os_ver
119
+ elif provider == "saucelabs" and "platformVersion" not in base:
120
+ base["platformVersion"] = os_ver
121
+ elif provider == "lambdatest":
122
+ if device and "deviceName" not in base:
123
+ base["deviceName"] = device
124
+ if os_ver and "platformVersion" not in base:
125
+ base["platformVersion"] = os_ver
126
+ return base
127
+
128
+
129
+ def _provider_options_key():
130
+ vendor = _vendor_from_testver()
131
+ if vendor:
132
+ return vendor.get("key")
133
+ return {
134
+ "browserstack": "bstack:options",
135
+ "saucelabs": "sauce:options",
136
+ "lambdatest": "lt:options",
137
+ }.get(os.environ.get("TESTVER_PROVIDER"))
138
+
139
+
140
+ def _env_json(name):
141
+ try:
142
+ value = json.loads(os.environ.get(name) or "{}")
143
+ return value if isinstance(value, dict) else {}
144
+ except ValueError:
145
+ return {}
146
+
147
+
148
+ def _apply_local_caps(caps):
149
+ """Local Devices (Settings → Local Devices): capabilities the project
150
+ doesn't set itself (TESTVER_LOCAL_CAPS_DEFAULTS — WebDriverAgent port and
151
+ signing), then Testver's own over the project's (TESTVER_LOCAL_CAPS —
152
+ app launch mode)."""
153
+ for k, v in _env_json("TESTVER_LOCAL_CAPS_DEFAULTS").items():
154
+ bare = k[len("appium:"):] if k.startswith("appium:") else k
155
+ if k not in caps and bare not in caps:
156
+ caps[k] = v
157
+ for k, v in _env_json("TESTVER_LOCAL_CAPS").items():
158
+ bare = k[len("appium:"):] if k.startswith("appium:") else k
159
+ caps.pop(bare, None)
160
+ caps[k] = v
161
+
162
+
163
+ def _apply_caps_to_dict(caps):
164
+ """Mutate a flat capabilities dict in place with Testver overrides."""
165
+ # Normalise any legacy unprefixed Appium keys.
166
+ for k in list(caps.keys()):
167
+ nk = _prefix_key(k)
168
+ if nk != k:
169
+ caps[nk] = caps.pop(k)
170
+
171
+ plat = os.environ.get("TESTVER_PLATFORM_NAME")
172
+ device = os.environ.get("TESTVER_DEVICE_NAME")
173
+ os_ver = os.environ.get("TESTVER_PLATFORM_VERSION")
174
+ app = os.environ.get("TESTVER_APP_URL")
175
+
176
+ if plat:
177
+ caps["platformName"] = plat
178
+ if device:
179
+ caps["appium:deviceName"] = device
180
+ if os_ver:
181
+ caps["appium:platformVersion"] = os_ver
182
+ # The device: a local one by its serial / udid (Appium picks the device
183
+ # by appium:udid, never by deviceName); on a vendor's cloud a local
184
+ # udid / AVD means nothing.
185
+ udid = os.environ.get("TESTVER_DEVICE_UDID")
186
+ if os.environ.get("TESTVER_PROVIDER") == "local-appium":
187
+ if udid:
188
+ caps["appium:udid"] = udid
189
+ caps.pop("appium:avd", None)
190
+ _apply_local_caps(caps)
191
+ else:
192
+ caps.pop("appium:udid", None)
193
+ caps.pop("appium:avd", None)
194
+ if app:
195
+ # the project's own package / bundle id, for the reset on a reused
196
+ # session (it is dropped from the caps just below)
197
+ _project_app_id["value"] = (caps.get("appium:appPackage") or caps.get("appium:bundleId")
198
+ or _project_app_id["value"])
199
+ caps["appium:app"] = app
200
+ # Drop app-identifier caps that may belong to a different build —
201
+ # cloud providers auto-detect these from the uploaded binary.
202
+ for stale in ("appium:appPackage", "appium:appActivity",
203
+ "appium:appWaitActivity", "appium:appWaitPackage",
204
+ "appium:bundleId", "appium:appWaitForLaunch"):
205
+ caps.pop(stale, None)
206
+
207
+ if not caps.get("appium:automationName"):
208
+ caps["appium:automationName"] = (
209
+ "XCUITest" if str(caps.get("platformName", "")).lower() == "ios"
210
+ else "UiAutomator2"
211
+ )
212
+
213
+ pkey = _provider_options_key()
214
+ if pkey:
215
+ # the project's own spelling of the block (`LT:Options` / `lt:options`)
216
+ if pkey not in caps:
217
+ pkey = next((k for k in caps if isinstance(k, str) and k.lower() == pkey.lower()), pkey)
218
+ caps[pkey] = _provider_options_block(caps.get(pkey))
219
+ return caps
220
+
221
+
222
+ def _inject_into_options(options):
223
+ """Apply overrides onto an AppiumOptions / BaseOptions instance."""
224
+ try:
225
+ existing = {}
226
+ try:
227
+ existing = dict(options.to_capabilities() or {})
228
+ except Exception:
229
+ existing = {}
230
+ merged = _apply_caps_to_dict(dict(existing))
231
+ for name, value in merged.items():
232
+ try:
233
+ options.set_capability(name, value)
234
+ except Exception:
235
+ pass
236
+ # Caps that _apply_caps_to_dict deliberately removed (the stale
237
+ # app-identifier caps when an app URL is supplied) must be deleted
238
+ # from the options object too — set_capability only adds/overwrites.
239
+ # (by the namespaced name: a legacy `automationName` the client lists
240
+ # unprefixed lives on as `appium:automationName` — it isn't dropped)
241
+ dropped = {k for k in existing.keys() if _prefix_key(k) not in merged}
242
+ for k in dropped:
243
+ removed = False
244
+ internal = getattr(options, "_caps", None)
245
+ if isinstance(internal, dict):
246
+ for variant in (k, _prefix_key(k), k.replace("appium:", "")):
247
+ if internal.pop(variant, None) is not None:
248
+ removed = True
249
+ if not removed:
250
+ try:
251
+ options.set_capability(k, None)
252
+ except Exception:
253
+ pass
254
+ except Exception as exc: # pragma: no cover
255
+ _log("options injection failed: " + str(exc))
256
+
257
+
258
+ # ── Hub URL / reportback ─────────────────────────────────────────────────────
259
+
260
+ def _hub_url_with_creds():
261
+ proto = os.environ.get("APPIUM_HUB_PROTOCOL") or "https"
262
+ host = os.environ.get("APPIUM_HUB_HOST")
263
+ if not host:
264
+ return None
265
+ default_port = "443" if proto == "https" else "80"
266
+ port = os.environ.get("APPIUM_HUB_PORT") or default_port
267
+ path = os.environ.get("APPIUM_HUB_PATH") or "/wd/hub"
268
+ user = os.environ.get("APPIUM_HUB_USER") or ""
269
+ key = os.environ.get("APPIUM_HUB_KEY") or ""
270
+ if _urlquote:
271
+ user = _urlquote(user)
272
+ key = _urlquote(key)
273
+ cred = (user + ":" + key + "@") if (user or key) else ""
274
+ return "{0}://{1}{2}:{3}{4}".format(proto, cred, host, port, path)
275
+
276
+
277
+ def _post_json(endpoint, payload):
278
+ if not (_urllib_request and endpoint):
279
+ return
280
+ try:
281
+ data = json.dumps(payload).encode("utf-8")
282
+ req = _urllib_request.Request(
283
+ endpoint, data=data,
284
+ headers={"Content-Type": "application/json"}, method="POST",
285
+ )
286
+ _urllib_request.urlopen(req, timeout=3).read()
287
+ except Exception as exc:
288
+ _log("reportback POST failed (" + endpoint + "): " + str(exc))
289
+
290
+
291
+ def _report_device_session(driver):
292
+ """A local device run: tell Testver which Appium session this test
293
+ opened, so Auto-Heal can read the device screen and Stop can end the
294
+ session (Appium 3 does not list its sessions to other programs). Only
295
+ the session id goes; the run's one-time token proves it is this run."""
296
+ url = os.environ.get("TESTVER_SESSION_REPORT_URL")
297
+ token = os.environ.get("TESTVER_SESSION_REPORT_TOKEN")
298
+ run_id = os.environ.get("TESTVER_RUN_ID")
299
+ sid = getattr(driver, "session_id", None)
300
+ if not (url and token and run_id and sid):
301
+ return
302
+ _post_json(url, {"runId": run_id, "token": token, "sessionId": str(sid)})
303
+
304
+
305
+ def _report_external_session(driver):
306
+ base = os.environ.get("TESTVER_REPORTBACK_URL")
307
+ client_id = os.environ.get("TESTVER_CLIENT_ID")
308
+ sid = getattr(driver, "session_id", None)
309
+ if not (base and client_id and sid):
310
+ return
311
+ hub = _hub_url_with_creds()
312
+ if not hub:
313
+ return
314
+ endpoint = base.rstrip("/") + "/api/mobile/session/register-external"
315
+ _post_json(endpoint, {
316
+ "clientId": client_id,
317
+ "sessionId": sid,
318
+ "hubUrl": hub,
319
+ "deviceName": os.environ.get("TESTVER_DEVICE_NAME"),
320
+ "platformName": os.environ.get("TESTVER_PLATFORM_NAME"),
321
+ "providerId": os.environ.get("TESTVER_PROVIDER"),
322
+ # the run that opened it (several runs of one tab side by side)
323
+ "runId": os.environ.get("TESTVER_RUN_ID"),
324
+ })
325
+ _log("Reported session " + str(sid)[:12] + "... for live preview")
326
+
327
+
328
+ _unreported = {"done": False}
329
+
330
+
331
+ def _unreport_external_session():
332
+ if _unreported["done"]:
333
+ return
334
+ _unreported["done"] = True
335
+ base = os.environ.get("TESTVER_REPORTBACK_URL")
336
+ client_id = os.environ.get("TESTVER_CLIENT_ID")
337
+ if not (base and client_id):
338
+ return
339
+ endpoint = base.rstrip("/") + "/api/mobile/session/unregister-external"
340
+ _post_json(endpoint, {"clientId": client_id})
341
+
342
+
343
+ # ── App reset on attach ──────────────────────────────────────────────────────
344
+
345
+ _project_app_id = {"value": None}
346
+
347
+
348
+ def _reset_app_on_attach(driver, caps):
349
+ if os.environ.get("TESTVER_SKIP_APP_RESET") == "1":
350
+ return
351
+ app_id = (
352
+ (caps or {}).get("appium:appPackage")
353
+ or (caps or {}).get("appium:bundleId")
354
+ or _project_app_id["value"]
355
+ or os.environ.get("TESTVER_APP_PACKAGE")
356
+ or os.environ.get("TESTVER_APP_BUNDLE_ID")
357
+ )
358
+ if not app_id:
359
+ _log("App reset on attach skipped — no appPackage/bundleId available")
360
+ return
361
+ platform = str((caps or {}).get("platformName")
362
+ or os.environ.get("TESTVER_PLATFORM_NAME") or "").lower()
363
+ is_android = platform == "android"
364
+ try:
365
+ if is_android and os.environ.get("TESTVER_SKIP_APP_CLEAR") != "1":
366
+ try:
367
+ driver.execute_script("mobile: clearApp", {"appId": app_id})
368
+ except Exception:
369
+ pass
370
+ try:
371
+ driver.execute_script("mobile: terminateApp", {"appId": app_id})
372
+ except Exception:
373
+ pass
374
+ driver.execute_script("mobile: activateApp", {"appId": app_id})
375
+ _log("App '" + app_id + "' reset to fresh launch on attached session")
376
+ except Exception as exc:
377
+ _log("App reset failed: " + str(exc))
378
+
379
+
380
+ # ── Driver patching ──────────────────────────────────────────────────────────
381
+
382
+ _patched = {"done": False}
383
+
384
+
385
+ def _patch_remote(remote_cls):
386
+ if remote_cls is None or getattr(remote_cls, "_testver_patched", False):
387
+ return
388
+ orig_init = remote_cls.__init__
389
+ orig_start = getattr(remote_cls, "start_session", None)
390
+ orig_quit = getattr(remote_cls, "quit", None)
391
+
392
+ def new_init(self, *args, **kwargs):
393
+ # 1. Redirect command_executor to the Testver hub.
394
+ hub = os.environ.get("APPIUM_HUB_URL")
395
+ if hub:
396
+ if "command_executor" in kwargs:
397
+ kwargs["command_executor"] = hub
398
+ elif args:
399
+ args = (hub,) + tuple(args[1:])
400
+ else:
401
+ kwargs["command_executor"] = hub
402
+ # Appium-Python-Client 5+ (and AppiumLibrary 3+) pass a
403
+ # client_config whose server address wins over command_executor.
404
+ cc = kwargs.get("client_config")
405
+ if cc is not None and hasattr(cc, "remote_server_addr"):
406
+ try:
407
+ cc.remote_server_addr = hub
408
+ user = os.environ.get("APPIUM_HUB_USER") or ""
409
+ key = os.environ.get("APPIUM_HUB_KEY") or ""
410
+ if user and hasattr(cc, "username"):
411
+ cc.username = user
412
+ cc.password = key
413
+ except Exception as exc: # pragma: no cover
414
+ _log("could not redirect client_config: %s" % exc)
415
+ # 2. Inject capabilities (AppiumOptions or desired_capabilities dict).
416
+ opts = kwargs.get("options")
417
+ if opts is None:
418
+ for a in args:
419
+ if hasattr(a, "set_capability") and hasattr(a, "to_capabilities"):
420
+ opts = a
421
+ break
422
+ if opts is not None:
423
+ _inject_into_options(opts)
424
+ elif isinstance(kwargs.get("desired_capabilities"), dict):
425
+ _apply_caps_to_dict(kwargs["desired_capabilities"])
426
+
427
+ orig_init(self, *args, **kwargs)
428
+
429
+ # 3. Live-preview reportback (best-effort).
430
+ try:
431
+ _report_external_session(self)
432
+ except Exception:
433
+ pass
434
+ try:
435
+ _report_device_session(self)
436
+ except Exception:
437
+ pass
438
+ # 4. App reset when attached to a shared session.
439
+ if os.environ.get("TESTVER_REUSE_SESSION_ID"):
440
+ try:
441
+ _reset_app_on_attach(self, getattr(self, "caps", None) or {})
442
+ except Exception:
443
+ pass
444
+
445
+ def new_start_session(self, *a, **k):
446
+ reuse = os.environ.get("TESTVER_REUSE_SESSION_ID")
447
+ if reuse:
448
+ # Attach instead of POST /session — skip booting a device.
449
+ self.session_id = reuse
450
+ caps = a[0] if a else k.get("capabilities")
451
+ try:
452
+ if isinstance(caps, dict):
453
+ self.caps = caps.get("alwaysMatch", caps)
454
+ else:
455
+ self.caps = {}
456
+ except Exception:
457
+ self.caps = {}
458
+ _log("Attached to live session " + reuse[:12] + "... (skipped device boot)")
459
+ return None
460
+ return orig_start(self, *a, **k)
461
+
462
+ def new_quit(self, *a, **k):
463
+ if os.environ.get("TESTVER_REUSE_SESSION_ID"):
464
+ _log("quit() suppressed - session is SHARED with Testver")
465
+ try:
466
+ _unreport_external_session()
467
+ except Exception:
468
+ pass
469
+ return None
470
+ try:
471
+ _unreport_external_session()
472
+ except Exception:
473
+ pass
474
+ return orig_quit(self, *a, **k) if orig_quit else None
475
+
476
+ remote_cls.__init__ = new_init
477
+ if orig_start is not None:
478
+ remote_cls.start_session = new_start_session
479
+ if orig_quit is not None:
480
+ remote_cls.quit = new_quit
481
+ remote_cls._testver_patched = True
482
+ _log("Appium Remote driver patched (provider=" +
483
+ str(os.environ.get("TESTVER_PROVIDER")) + ")")
484
+
485
+
486
+ def _patch_module(mod):
487
+ if _patched["done"]:
488
+ return
489
+ remote = getattr(mod, "Remote", None) or getattr(mod, "WebDriver", None)
490
+ if remote is not None:
491
+ _patch_remote(remote)
492
+ _patched["done"] = True
493
+
494
+
495
+ # ── Post-import hook (works whether or not appium is imported yet) ────────────
496
+
497
+ def _install():
498
+ if not _enabled():
499
+ return
500
+ atexit.register(_unreport_external_session)
501
+
502
+ # Already imported? Patch now.
503
+ if "appium.webdriver" in sys.modules:
504
+ _patch_module(sys.modules["appium.webdriver"])
505
+ return
506
+
507
+ import importlib.util
508
+
509
+ class _Finder:
510
+ def find_spec(self, fullname, path=None, target=None):
511
+ if fullname != "appium.webdriver":
512
+ return None
513
+ try:
514
+ sys.meta_path.remove(self)
515
+ except ValueError:
516
+ return None
517
+ try:
518
+ spec = importlib.util.find_spec(fullname)
519
+ finally:
520
+ sys.meta_path.insert(0, self)
521
+ if spec is None or spec.loader is None:
522
+ return None
523
+ loader = spec.loader
524
+ orig_exec = loader.exec_module
525
+ finder = self
526
+
527
+ def exec_module(module):
528
+ orig_exec(module)
529
+ try:
530
+ _patch_module(module)
531
+ finally:
532
+ try:
533
+ sys.meta_path.remove(finder)
534
+ except ValueError:
535
+ pass
536
+
537
+ loader.exec_module = exec_module
538
+ return spec
539
+
540
+ sys.meta_path.insert(0, _Finder())
541
+
542
+
543
+ # Install on import (pytest loads this module via `-p testver_appium`).
544
+ _install()
545
+
546
+
547
+ # ── pytest hooks (belt-and-suspenders) ───────────────────────────────────────
548
+
549
+ def pytest_configure(config):
550
+ # If appium was already imported by a conftest before our hook landed,
551
+ # patch it now.
552
+ if _enabled() and "appium.webdriver" in sys.modules:
553
+ _patch_module(sys.modules["appium.webdriver"])