@testver/testver 0.2.0
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.
- package/README.md +288 -0
- package/bin/testver.js +2 -0
- package/deploy/Dockerfile +40 -0
- package/deploy/docker-compose.yml +57 -0
- package/deploy/nginx.conf +136 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +100161 -0
- package/dist/py-agent/testver_appium.py +433 -0
- package/dist/wdio-attach-service/index.cjs +193 -0
- package/dist/wdio-attach-service/package.json +11 -0
- package/dist/wdio-bootstrap/bootstrap.cjs +627 -0
- package/dist/wdio-json-reporter/index.cjs +165 -0
- package/dist/wdio-json-reporter/package.json +7 -0
- package/package.json +113 -0
- package/src/ui/static/assets/dark-logo-BddlJH8z.svg +1 -0
- package/src/ui/static/assets/index-4OALwN46.js +49 -0
- package/src/ui/static/assets/index-B717Le4X.css +7 -0
- package/src/ui/static/assets/index-D8OX9kxr.js +2075 -0
- package/src/ui/static/assets/logo-DwQCjTm_.svg +1 -0
- package/src/ui/static/dark-logo.svg +1 -0
- package/src/ui/static/favicon.svg +1 -0
- package/src/ui/static/index.html +476 -0
- package/src/ui/static/logo.svg +1 -0
|
@@ -0,0 +1,433 @@
|
|
|
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 _provider_options_block(existing):
|
|
69
|
+
"""Build the provider-specific options block (bstack:/sauce:/LT:)."""
|
|
70
|
+
provider = os.environ.get("TESTVER_PROVIDER")
|
|
71
|
+
device = os.environ.get("TESTVER_DEVICE_NAME")
|
|
72
|
+
os_ver = os.environ.get("TESTVER_PLATFORM_VERSION")
|
|
73
|
+
base = dict(existing or {})
|
|
74
|
+
base.setdefault("projectName", "Testver")
|
|
75
|
+
base.setdefault("buildName", os.environ.get("TESTVER_BUILD_NAME") or "testver-cloud-run")
|
|
76
|
+
base.setdefault("sessionName", os.environ.get("TESTVER_SESSION_NAME") or "mobile-test")
|
|
77
|
+
if provider in ("browserstack", "saucelabs"):
|
|
78
|
+
if device and "deviceName" not in base:
|
|
79
|
+
base["deviceName"] = device
|
|
80
|
+
if os_ver:
|
|
81
|
+
if provider == "browserstack" and "osVersion" not in base:
|
|
82
|
+
base["osVersion"] = os_ver
|
|
83
|
+
elif provider == "saucelabs" and "platformVersion" not in base:
|
|
84
|
+
base["platformVersion"] = os_ver
|
|
85
|
+
elif provider == "lambdatest":
|
|
86
|
+
if device and "deviceName" not in base:
|
|
87
|
+
base["deviceName"] = device
|
|
88
|
+
if os_ver and "platformVersion" not in base:
|
|
89
|
+
base["platformVersion"] = os_ver
|
|
90
|
+
return base
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _provider_options_key():
|
|
94
|
+
return {
|
|
95
|
+
"browserstack": "bstack:options",
|
|
96
|
+
"saucelabs": "sauce:options",
|
|
97
|
+
"lambdatest": "LT:Options",
|
|
98
|
+
}.get(os.environ.get("TESTVER_PROVIDER"))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _apply_caps_to_dict(caps):
|
|
102
|
+
"""Mutate a flat capabilities dict in place with Testver overrides."""
|
|
103
|
+
# Normalise any legacy unprefixed Appium keys.
|
|
104
|
+
for k in list(caps.keys()):
|
|
105
|
+
nk = _prefix_key(k)
|
|
106
|
+
if nk != k:
|
|
107
|
+
caps[nk] = caps.pop(k)
|
|
108
|
+
|
|
109
|
+
plat = os.environ.get("TESTVER_PLATFORM_NAME")
|
|
110
|
+
device = os.environ.get("TESTVER_DEVICE_NAME")
|
|
111
|
+
os_ver = os.environ.get("TESTVER_PLATFORM_VERSION")
|
|
112
|
+
app = os.environ.get("TESTVER_APP_URL")
|
|
113
|
+
|
|
114
|
+
if plat:
|
|
115
|
+
caps["platformName"] = plat
|
|
116
|
+
if device:
|
|
117
|
+
caps["appium:deviceName"] = device
|
|
118
|
+
if os_ver:
|
|
119
|
+
caps["appium:platformVersion"] = os_ver
|
|
120
|
+
if app:
|
|
121
|
+
caps["appium:app"] = app
|
|
122
|
+
# Drop app-identifier caps that may belong to a different build —
|
|
123
|
+
# cloud providers auto-detect these from the uploaded binary.
|
|
124
|
+
for stale in ("appium:appPackage", "appium:appActivity",
|
|
125
|
+
"appium:appWaitActivity", "appium:appWaitPackage",
|
|
126
|
+
"appium:bundleId", "appium:appWaitForLaunch"):
|
|
127
|
+
caps.pop(stale, None)
|
|
128
|
+
|
|
129
|
+
if not caps.get("appium:automationName"):
|
|
130
|
+
caps["appium:automationName"] = (
|
|
131
|
+
"XCUITest" if str(caps.get("platformName", "")).lower() == "ios"
|
|
132
|
+
else "UiAutomator2"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
pkey = _provider_options_key()
|
|
136
|
+
if pkey:
|
|
137
|
+
caps[pkey] = _provider_options_block(caps.get(pkey))
|
|
138
|
+
return caps
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _inject_into_options(options):
|
|
142
|
+
"""Apply overrides onto an AppiumOptions / BaseOptions instance."""
|
|
143
|
+
try:
|
|
144
|
+
existing = {}
|
|
145
|
+
try:
|
|
146
|
+
existing = dict(options.to_capabilities() or {})
|
|
147
|
+
except Exception:
|
|
148
|
+
existing = {}
|
|
149
|
+
merged = _apply_caps_to_dict(dict(existing))
|
|
150
|
+
for name, value in merged.items():
|
|
151
|
+
try:
|
|
152
|
+
options.set_capability(name, value)
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
# Caps that _apply_caps_to_dict deliberately removed (the stale
|
|
156
|
+
# app-identifier caps when an app URL is supplied) must be deleted
|
|
157
|
+
# from the options object too — set_capability only adds/overwrites.
|
|
158
|
+
dropped = set(existing.keys()) - set(merged.keys())
|
|
159
|
+
for k in dropped:
|
|
160
|
+
removed = False
|
|
161
|
+
internal = getattr(options, "_caps", None)
|
|
162
|
+
if isinstance(internal, dict):
|
|
163
|
+
for variant in (k, _prefix_key(k), k.replace("appium:", "")):
|
|
164
|
+
if internal.pop(variant, None) is not None:
|
|
165
|
+
removed = True
|
|
166
|
+
if not removed:
|
|
167
|
+
try:
|
|
168
|
+
options.set_capability(k, None)
|
|
169
|
+
except Exception:
|
|
170
|
+
pass
|
|
171
|
+
except Exception as exc: # pragma: no cover
|
|
172
|
+
_log("options injection failed: " + str(exc))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ── Hub URL / reportback ─────────────────────────────────────────────────────
|
|
176
|
+
|
|
177
|
+
def _hub_url_with_creds():
|
|
178
|
+
proto = os.environ.get("APPIUM_HUB_PROTOCOL") or "https"
|
|
179
|
+
host = os.environ.get("APPIUM_HUB_HOST")
|
|
180
|
+
if not host:
|
|
181
|
+
return None
|
|
182
|
+
default_port = "443" if proto == "https" else "80"
|
|
183
|
+
port = os.environ.get("APPIUM_HUB_PORT") or default_port
|
|
184
|
+
path = os.environ.get("APPIUM_HUB_PATH") or "/wd/hub"
|
|
185
|
+
user = os.environ.get("APPIUM_HUB_USER") or ""
|
|
186
|
+
key = os.environ.get("APPIUM_HUB_KEY") or ""
|
|
187
|
+
if _urlquote:
|
|
188
|
+
user = _urlquote(user)
|
|
189
|
+
key = _urlquote(key)
|
|
190
|
+
cred = (user + ":" + key + "@") if (user or key) else ""
|
|
191
|
+
return "{0}://{1}{2}:{3}{4}".format(proto, cred, host, port, path)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _post_json(endpoint, payload):
|
|
195
|
+
if not (_urllib_request and endpoint):
|
|
196
|
+
return
|
|
197
|
+
try:
|
|
198
|
+
data = json.dumps(payload).encode("utf-8")
|
|
199
|
+
req = _urllib_request.Request(
|
|
200
|
+
endpoint, data=data,
|
|
201
|
+
headers={"Content-Type": "application/json"}, method="POST",
|
|
202
|
+
)
|
|
203
|
+
_urllib_request.urlopen(req, timeout=3).read()
|
|
204
|
+
except Exception as exc:
|
|
205
|
+
_log("reportback POST failed (" + endpoint + "): " + str(exc))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _report_external_session(driver):
|
|
209
|
+
base = os.environ.get("TESTVER_REPORTBACK_URL")
|
|
210
|
+
client_id = os.environ.get("TESTVER_CLIENT_ID")
|
|
211
|
+
sid = getattr(driver, "session_id", None)
|
|
212
|
+
if not (base and client_id and sid):
|
|
213
|
+
return
|
|
214
|
+
hub = _hub_url_with_creds()
|
|
215
|
+
if not hub:
|
|
216
|
+
return
|
|
217
|
+
endpoint = base.rstrip("/") + "/api/mobile/session/register-external"
|
|
218
|
+
_post_json(endpoint, {
|
|
219
|
+
"clientId": client_id,
|
|
220
|
+
"sessionId": sid,
|
|
221
|
+
"hubUrl": hub,
|
|
222
|
+
"deviceName": os.environ.get("TESTVER_DEVICE_NAME"),
|
|
223
|
+
"platformName": os.environ.get("TESTVER_PLATFORM_NAME"),
|
|
224
|
+
"providerId": os.environ.get("TESTVER_PROVIDER"),
|
|
225
|
+
})
|
|
226
|
+
_log("Reported session " + str(sid)[:12] + "... for live preview")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
_unreported = {"done": False}
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _unreport_external_session():
|
|
233
|
+
if _unreported["done"]:
|
|
234
|
+
return
|
|
235
|
+
_unreported["done"] = True
|
|
236
|
+
base = os.environ.get("TESTVER_REPORTBACK_URL")
|
|
237
|
+
client_id = os.environ.get("TESTVER_CLIENT_ID")
|
|
238
|
+
if not (base and client_id):
|
|
239
|
+
return
|
|
240
|
+
endpoint = base.rstrip("/") + "/api/mobile/session/unregister-external"
|
|
241
|
+
_post_json(endpoint, {"clientId": client_id})
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# ── App reset on attach ──────────────────────────────────────────────────────
|
|
245
|
+
|
|
246
|
+
def _reset_app_on_attach(driver, caps):
|
|
247
|
+
if os.environ.get("TESTVER_SKIP_APP_RESET") == "1":
|
|
248
|
+
return
|
|
249
|
+
app_id = (
|
|
250
|
+
(caps or {}).get("appium:appPackage")
|
|
251
|
+
or (caps or {}).get("appium:bundleId")
|
|
252
|
+
or os.environ.get("TESTVER_APP_PACKAGE")
|
|
253
|
+
or os.environ.get("TESTVER_APP_BUNDLE_ID")
|
|
254
|
+
)
|
|
255
|
+
if not app_id:
|
|
256
|
+
_log("App reset on attach skipped — no appPackage/bundleId available")
|
|
257
|
+
return
|
|
258
|
+
platform = str((caps or {}).get("platformName")
|
|
259
|
+
or os.environ.get("TESTVER_PLATFORM_NAME") or "").lower()
|
|
260
|
+
is_android = platform == "android"
|
|
261
|
+
try:
|
|
262
|
+
if is_android and os.environ.get("TESTVER_SKIP_APP_CLEAR") != "1":
|
|
263
|
+
try:
|
|
264
|
+
driver.execute_script("mobile: clearApp", {"appId": app_id})
|
|
265
|
+
except Exception:
|
|
266
|
+
pass
|
|
267
|
+
try:
|
|
268
|
+
driver.execute_script("mobile: terminateApp", {"appId": app_id})
|
|
269
|
+
except Exception:
|
|
270
|
+
pass
|
|
271
|
+
driver.execute_script("mobile: activateApp", {"appId": app_id})
|
|
272
|
+
_log("App '" + app_id + "' reset to fresh launch on attached session")
|
|
273
|
+
except Exception as exc:
|
|
274
|
+
_log("App reset failed: " + str(exc))
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ── Driver patching ──────────────────────────────────────────────────────────
|
|
278
|
+
|
|
279
|
+
_patched = {"done": False}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _patch_remote(remote_cls):
|
|
283
|
+
if remote_cls is None or getattr(remote_cls, "_testver_patched", False):
|
|
284
|
+
return
|
|
285
|
+
orig_init = remote_cls.__init__
|
|
286
|
+
orig_start = getattr(remote_cls, "start_session", None)
|
|
287
|
+
orig_quit = getattr(remote_cls, "quit", None)
|
|
288
|
+
|
|
289
|
+
def new_init(self, *args, **kwargs):
|
|
290
|
+
# 1. Redirect command_executor to the Testver hub.
|
|
291
|
+
hub = os.environ.get("APPIUM_HUB_URL")
|
|
292
|
+
if hub:
|
|
293
|
+
if "command_executor" in kwargs:
|
|
294
|
+
kwargs["command_executor"] = hub
|
|
295
|
+
elif args:
|
|
296
|
+
args = (hub,) + tuple(args[1:])
|
|
297
|
+
else:
|
|
298
|
+
kwargs["command_executor"] = hub
|
|
299
|
+
# 2. Inject capabilities (AppiumOptions or desired_capabilities dict).
|
|
300
|
+
opts = kwargs.get("options")
|
|
301
|
+
if opts is None:
|
|
302
|
+
for a in args:
|
|
303
|
+
if hasattr(a, "set_capability") and hasattr(a, "to_capabilities"):
|
|
304
|
+
opts = a
|
|
305
|
+
break
|
|
306
|
+
if opts is not None:
|
|
307
|
+
_inject_into_options(opts)
|
|
308
|
+
elif isinstance(kwargs.get("desired_capabilities"), dict):
|
|
309
|
+
_apply_caps_to_dict(kwargs["desired_capabilities"])
|
|
310
|
+
|
|
311
|
+
orig_init(self, *args, **kwargs)
|
|
312
|
+
|
|
313
|
+
# 3. Live-preview reportback (best-effort).
|
|
314
|
+
try:
|
|
315
|
+
_report_external_session(self)
|
|
316
|
+
except Exception:
|
|
317
|
+
pass
|
|
318
|
+
# 4. App reset when attached to a shared session.
|
|
319
|
+
if os.environ.get("TESTVER_REUSE_SESSION_ID"):
|
|
320
|
+
try:
|
|
321
|
+
_reset_app_on_attach(self, getattr(self, "caps", None) or {})
|
|
322
|
+
except Exception:
|
|
323
|
+
pass
|
|
324
|
+
|
|
325
|
+
def new_start_session(self, *a, **k):
|
|
326
|
+
reuse = os.environ.get("TESTVER_REUSE_SESSION_ID")
|
|
327
|
+
if reuse:
|
|
328
|
+
# Attach instead of POST /session — skip booting a device.
|
|
329
|
+
self.session_id = reuse
|
|
330
|
+
caps = a[0] if a else k.get("capabilities")
|
|
331
|
+
try:
|
|
332
|
+
if isinstance(caps, dict):
|
|
333
|
+
self.caps = caps.get("alwaysMatch", caps)
|
|
334
|
+
else:
|
|
335
|
+
self.caps = {}
|
|
336
|
+
except Exception:
|
|
337
|
+
self.caps = {}
|
|
338
|
+
_log("Attached to live session " + reuse[:12] + "... (skipped device boot)")
|
|
339
|
+
return None
|
|
340
|
+
return orig_start(self, *a, **k)
|
|
341
|
+
|
|
342
|
+
def new_quit(self, *a, **k):
|
|
343
|
+
if os.environ.get("TESTVER_REUSE_SESSION_ID"):
|
|
344
|
+
_log("quit() suppressed - session is SHARED with Testver")
|
|
345
|
+
try:
|
|
346
|
+
_unreport_external_session()
|
|
347
|
+
except Exception:
|
|
348
|
+
pass
|
|
349
|
+
return None
|
|
350
|
+
try:
|
|
351
|
+
_unreport_external_session()
|
|
352
|
+
except Exception:
|
|
353
|
+
pass
|
|
354
|
+
return orig_quit(self, *a, **k) if orig_quit else None
|
|
355
|
+
|
|
356
|
+
remote_cls.__init__ = new_init
|
|
357
|
+
if orig_start is not None:
|
|
358
|
+
remote_cls.start_session = new_start_session
|
|
359
|
+
if orig_quit is not None:
|
|
360
|
+
remote_cls.quit = new_quit
|
|
361
|
+
remote_cls._testver_patched = True
|
|
362
|
+
_log("Appium Remote driver patched (provider=" +
|
|
363
|
+
str(os.environ.get("TESTVER_PROVIDER")) + ")")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _patch_module(mod):
|
|
367
|
+
if _patched["done"]:
|
|
368
|
+
return
|
|
369
|
+
remote = getattr(mod, "Remote", None) or getattr(mod, "WebDriver", None)
|
|
370
|
+
if remote is not None:
|
|
371
|
+
_patch_remote(remote)
|
|
372
|
+
_patched["done"] = True
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
# ── Post-import hook (works whether or not appium is imported yet) ────────────
|
|
376
|
+
|
|
377
|
+
def _install():
|
|
378
|
+
if not _enabled():
|
|
379
|
+
return
|
|
380
|
+
atexit.register(_unreport_external_session)
|
|
381
|
+
|
|
382
|
+
# Already imported? Patch now.
|
|
383
|
+
if "appium.webdriver" in sys.modules:
|
|
384
|
+
_patch_module(sys.modules["appium.webdriver"])
|
|
385
|
+
return
|
|
386
|
+
|
|
387
|
+
import importlib.util
|
|
388
|
+
|
|
389
|
+
class _Finder:
|
|
390
|
+
def find_spec(self, fullname, path=None, target=None):
|
|
391
|
+
if fullname != "appium.webdriver":
|
|
392
|
+
return None
|
|
393
|
+
try:
|
|
394
|
+
sys.meta_path.remove(self)
|
|
395
|
+
except ValueError:
|
|
396
|
+
return None
|
|
397
|
+
try:
|
|
398
|
+
spec = importlib.util.find_spec(fullname)
|
|
399
|
+
finally:
|
|
400
|
+
sys.meta_path.insert(0, self)
|
|
401
|
+
if spec is None or spec.loader is None:
|
|
402
|
+
return None
|
|
403
|
+
loader = spec.loader
|
|
404
|
+
orig_exec = loader.exec_module
|
|
405
|
+
finder = self
|
|
406
|
+
|
|
407
|
+
def exec_module(module):
|
|
408
|
+
orig_exec(module)
|
|
409
|
+
try:
|
|
410
|
+
_patch_module(module)
|
|
411
|
+
finally:
|
|
412
|
+
try:
|
|
413
|
+
sys.meta_path.remove(finder)
|
|
414
|
+
except ValueError:
|
|
415
|
+
pass
|
|
416
|
+
|
|
417
|
+
loader.exec_module = exec_module
|
|
418
|
+
return spec
|
|
419
|
+
|
|
420
|
+
sys.meta_path.insert(0, _Finder())
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
# Install on import (pytest loads this module via `-p testver_appium`).
|
|
424
|
+
_install()
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
# ── pytest hooks (belt-and-suspenders) ───────────────────────────────────────
|
|
428
|
+
|
|
429
|
+
def pytest_configure(config):
|
|
430
|
+
# If appium was already imported by a conftest before our hook landed,
|
|
431
|
+
# patch it now.
|
|
432
|
+
if _enabled() and "appium.webdriver" in sys.modules:
|
|
433
|
+
_patch_module(sys.modules["appium.webdriver"])
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @testver/wdio-attach-service
|
|
3
|
+
*
|
|
4
|
+
* WebdriverIO launcher service that, when `TESTVER_REUSE_SESSION_ID`
|
|
5
|
+
* is present in the environment, attaches to an existing Appium cloud
|
|
6
|
+
* session instead of letting WDIO open a fresh one. Saves ~30-60s of
|
|
7
|
+
* cloud device boot time and one provider minute per reuse.
|
|
8
|
+
*
|
|
9
|
+
* Plumbed in automatically by Testver's `wdio.testver.conf.{ts,js}`
|
|
10
|
+
* overlay (see src/mobile/cloud-bridge.ts > renderWdioOverlay). The
|
|
11
|
+
* service is only appended to the WDIO `services` array when the env
|
|
12
|
+
* var is set — so non-reuse runs are completely unaffected.
|
|
13
|
+
*
|
|
14
|
+
* How it works
|
|
15
|
+
* ─────────────
|
|
16
|
+
* WDIO's launcher calls `before` on every service before spinning up
|
|
17
|
+
* a session. We monkey-patch `global.browser`-builder by hooking into
|
|
18
|
+
* the `beforeSession` lifecycle: before WDIO POSTs `/session`, we
|
|
19
|
+
* pre-attach to the existing sessionId via `webdriverio.attach()` and
|
|
20
|
+
* stash the result on `global.browser`. WDIO sees a browser already
|
|
21
|
+
* exists and skips its own session creation.
|
|
22
|
+
*
|
|
23
|
+
* This is intentionally implemented as CommonJS (.cjs) so it can be
|
|
24
|
+
* resolved by both TS and JS projects without ESM gymnastics.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
'use strict';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Resolve `webdriverio` from the USER's project, NOT from wherever this
|
|
31
|
+
* vendored .cjs lives (e.g. E:\Testver\dist\wdio-attach-service), which
|
|
32
|
+
* has no node_modules — a bare require() there throws
|
|
33
|
+
* "Cannot find module 'webdriverio'" and the attach silently fails,
|
|
34
|
+
* forcing WDIO into a broken fresh-session fallback. The WDIO run cwd is
|
|
35
|
+
* the user's project (Testver `cd`s into it before invoking wdio), so we
|
|
36
|
+
* resolve relative to that; TESTVER_PROJECT_DIR is preferred when set.
|
|
37
|
+
*/
|
|
38
|
+
function loadWebdriverio() {
|
|
39
|
+
const Module = require('node:module');
|
|
40
|
+
const pathMod = require('node:path');
|
|
41
|
+
const bases = [];
|
|
42
|
+
if (process.env.TESTVER_PROJECT_DIR) bases.push(process.env.TESTVER_PROJECT_DIR);
|
|
43
|
+
bases.push(process.cwd());
|
|
44
|
+
for (const base of bases) {
|
|
45
|
+
try {
|
|
46
|
+
const req = Module.createRequire(pathMod.join(base, '__testver_attach_resolver__.cjs'));
|
|
47
|
+
return req('webdriverio');
|
|
48
|
+
} catch (_e) { /* try the next base */ }
|
|
49
|
+
}
|
|
50
|
+
// Last resort: resolve from this service's own location (works if the
|
|
51
|
+
// user happens to have webdriverio hoisted somewhere reachable).
|
|
52
|
+
return require('webdriverio');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* POST the live session back to Testver so the in-app live preview can
|
|
57
|
+
* render it. Mirrors the mocha `--require` bootstrap's reportback, but
|
|
58
|
+
* for the WDIO test-runner path. Fire-and-forget; a failure just means
|
|
59
|
+
* the preview stays empty — the test runs unaffected.
|
|
60
|
+
*/
|
|
61
|
+
async function reportSession(browser) {
|
|
62
|
+
const reportUrl = process.env.TESTVER_REPORTBACK_URL;
|
|
63
|
+
const clientId = process.env.TESTVER_CLIENT_ID;
|
|
64
|
+
if (!reportUrl || !clientId || !browser || !browser.sessionId) return;
|
|
65
|
+
if (typeof fetch !== 'function') return;
|
|
66
|
+
|
|
67
|
+
const proto = process.env.APPIUM_HUB_PROTOCOL || 'http';
|
|
68
|
+
const host = process.env.APPIUM_HUB_HOST || '127.0.0.1';
|
|
69
|
+
const port = process.env.APPIUM_HUB_PORT || (proto === 'https' ? '443' : '4723');
|
|
70
|
+
const rawPath = process.env.APPIUM_HUB_PATH || '/';
|
|
71
|
+
const user = encodeURIComponent(process.env.APPIUM_HUB_USER || '');
|
|
72
|
+
const key = encodeURIComponent(process.env.APPIUM_HUB_KEY || '');
|
|
73
|
+
const hubUrl = `${proto}://${user}:${key}@${host}:${port}${rawPath}`;
|
|
74
|
+
|
|
75
|
+
const caps = browser.capabilities || {};
|
|
76
|
+
const body = JSON.stringify({
|
|
77
|
+
clientId,
|
|
78
|
+
sessionId: browser.sessionId,
|
|
79
|
+
hubUrl,
|
|
80
|
+
deviceName: caps['appium:deviceName'] || process.env.TESTVER_DEVICE_NAME,
|
|
81
|
+
platformName: caps.platformName || process.env.TESTVER_PLATFORM_NAME,
|
|
82
|
+
providerId: process.env.TESTVER_PROVIDER,
|
|
83
|
+
});
|
|
84
|
+
try {
|
|
85
|
+
await fetch(reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external', {
|
|
86
|
+
method: 'POST',
|
|
87
|
+
headers: { 'Content-Type': 'application/json' },
|
|
88
|
+
body,
|
|
89
|
+
});
|
|
90
|
+
// eslint-disable-next-line no-console
|
|
91
|
+
console.log(`[testver-attach] Reported sessionId ${String(browser.sessionId).slice(0, 12)}… to Testver for live preview`);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
// eslint-disable-next-line no-console
|
|
94
|
+
console.log(`[testver-attach] Reportback failed (live preview may be empty): ${err && err.message}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function unreportSession() {
|
|
99
|
+
const reportUrl = process.env.TESTVER_REPORTBACK_URL;
|
|
100
|
+
const clientId = process.env.TESTVER_CLIENT_ID;
|
|
101
|
+
if (!reportUrl || !clientId || typeof fetch !== 'function') return;
|
|
102
|
+
try {
|
|
103
|
+
await fetch(reportUrl.replace(/\/$/, '') + '/api/mobile/session/unregister-external', {
|
|
104
|
+
method: 'POST',
|
|
105
|
+
headers: { 'Content-Type': 'application/json' },
|
|
106
|
+
body: JSON.stringify({ clientId }),
|
|
107
|
+
});
|
|
108
|
+
} catch { /* best-effort */ }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
class TestverAttachService {
|
|
112
|
+
constructor(serviceOptions = {}, capabilities = {}, config = {}) {
|
|
113
|
+
this.serviceOptions = serviceOptions;
|
|
114
|
+
this.capabilities = capabilities;
|
|
115
|
+
this.config = config;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* `onPrepare` runs once per WDIO launch, BEFORE any worker session.
|
|
120
|
+
* We don't attach here — attach happens per-worker in `beforeSession`.
|
|
121
|
+
* But we log clearly so users see reuse is engaged.
|
|
122
|
+
*/
|
|
123
|
+
onPrepare() {
|
|
124
|
+
const sid = process.env.TESTVER_REUSE_SESSION_ID;
|
|
125
|
+
if (!sid) return;
|
|
126
|
+
// eslint-disable-next-line no-console
|
|
127
|
+
console.log(`[testver-attach] Reuse engaged — will attach to sessionId=${sid.slice(0, 12)}…`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* `beforeSession` runs once per worker, BEFORE WDIO creates a session.
|
|
132
|
+
* We pre-create `global.browser` via webdriverio.attach() — when WDIO
|
|
133
|
+
* sees a browser already on globalThis, it skips its own POST /session.
|
|
134
|
+
*
|
|
135
|
+
* Returns a promise so WDIO awaits the attach before running tests.
|
|
136
|
+
*/
|
|
137
|
+
async beforeSession(_config, _capabilities) {
|
|
138
|
+
const sid = process.env.TESTVER_REUSE_SESSION_ID;
|
|
139
|
+
if (!sid) return; // No reuse — let WDIO open a fresh session.
|
|
140
|
+
|
|
141
|
+
const wdio = loadWebdriverio();
|
|
142
|
+
const attachOpts = {
|
|
143
|
+
sessionId: sid,
|
|
144
|
+
hostname: process.env.APPIUM_HUB_HOST,
|
|
145
|
+
port: Number(process.env.APPIUM_HUB_PORT || '443'),
|
|
146
|
+
protocol: process.env.APPIUM_HUB_PROTOCOL || 'https',
|
|
147
|
+
path: process.env.APPIUM_HUB_PATH || '/wd/hub',
|
|
148
|
+
user: process.env.APPIUM_HUB_USER,
|
|
149
|
+
key: process.env.APPIUM_HUB_KEY,
|
|
150
|
+
// Cap object on attach is informational — WDIO uses it to populate
|
|
151
|
+
// browser.capabilities for test code that reads it.
|
|
152
|
+
capabilities: {
|
|
153
|
+
platformName: process.env.TESTVER_PLATFORM_NAME || 'Android',
|
|
154
|
+
'appium:deviceName': process.env.TESTVER_DEVICE_NAME,
|
|
155
|
+
'appium:platformVersion': process.env.TESTVER_PLATFORM_VERSION,
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
try {
|
|
159
|
+
const browser = await wdio.attach(attachOpts);
|
|
160
|
+
// Stash on globalThis so WDIO's worker process picks it up.
|
|
161
|
+
// WDIO's launcher checks `globalThis.browser` before creating a
|
|
162
|
+
// new session; if present, it adopts it.
|
|
163
|
+
globalThis.browser = browser;
|
|
164
|
+
// eslint-disable-next-line no-console
|
|
165
|
+
console.log(`[testver-attach] Attached successfully to session ${sid.slice(0, 12)}…`);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
// eslint-disable-next-line no-console
|
|
168
|
+
console.warn(`[testver-attach] Attach failed (${err && err.message}); falling back to fresh session.`);
|
|
169
|
+
// Don't throw — let WDIO open a fresh session. Reuse is an
|
|
170
|
+
// optimisation, not a hard requirement.
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* `before` runs per-worker AFTER the session exists (whether WDIO
|
|
176
|
+
* created it fresh OR we attached above) and hands us the live
|
|
177
|
+
* `browser`. This is where we report the session back to Testver so
|
|
178
|
+
* the in-app live preview renders it — covering BOTH the fresh-session
|
|
179
|
+
* and reuse cases on the WDIO test-runner path.
|
|
180
|
+
*/
|
|
181
|
+
async before(_capabilities, _specs, browser) {
|
|
182
|
+
const b = browser || globalThis.browser;
|
|
183
|
+
try { await reportSession(b); } catch { /* best-effort */ }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Tell Testver the session is over so the preview stops polling. */
|
|
187
|
+
async after() {
|
|
188
|
+
try { await unreportSession(); } catch { /* best-effort */ }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
module.exports = TestverAttachService;
|
|
193
|
+
module.exports.default = TestverAttachService;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@testver/wdio-attach-service",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "WDIO service that attaches to an existing Appium cloud session when TESTVER_REUSE_SESSION_ID is set, instead of creating a fresh one. Used by Testver's mobile cloud-bridge for session reuse from recording → first run.",
|
|
6
|
+
"main": "index.cjs",
|
|
7
|
+
"type": "commonjs",
|
|
8
|
+
"peerDependencies": {
|
|
9
|
+
"webdriverio": ">=8.0.0"
|
|
10
|
+
}
|
|
11
|
+
}
|