@testver/testver 1.2.2 → 1.2.3

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.
@@ -65,8 +65,29 @@ def _prefix_key(key):
65
65
  return "appium:" + key
66
66
 
67
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
+
68
81
  def _provider_options_block(existing):
69
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
70
91
  provider = os.environ.get("TESTVER_PROVIDER")
71
92
  device = os.environ.get("TESTVER_DEVICE_NAME")
72
93
  os_ver = os.environ.get("TESTVER_PLATFORM_VERSION")
@@ -106,6 +127,9 @@ def _provider_options_block(existing):
106
127
 
107
128
 
108
129
  def _provider_options_key():
130
+ vendor = _vendor_from_testver()
131
+ if vendor:
132
+ return vendor.get("key")
109
133
  return {
110
134
  "browserstack": "bstack:options",
111
135
  "saucelabs": "sauce:options",
@@ -132,7 +156,22 @@ def _apply_caps_to_dict(caps):
132
156
  caps["appium:deviceName"] = device
133
157
  if os_ver:
134
158
  caps["appium:platformVersion"] = os_ver
159
+ # The device: a local one by its serial / udid (Appium picks the device
160
+ # by appium:udid, never by deviceName); on a vendor's cloud a local
161
+ # udid / AVD means nothing.
162
+ udid = os.environ.get("TESTVER_DEVICE_UDID")
163
+ if os.environ.get("TESTVER_PROVIDER") == "local-appium":
164
+ if udid:
165
+ caps["appium:udid"] = udid
166
+ caps.pop("appium:avd", None)
167
+ else:
168
+ caps.pop("appium:udid", None)
169
+ caps.pop("appium:avd", None)
135
170
  if app:
171
+ # the project's own package / bundle id, for the reset on a reused
172
+ # session (it is dropped from the caps just below)
173
+ _project_app_id["value"] = (caps.get("appium:appPackage") or caps.get("appium:bundleId")
174
+ or _project_app_id["value"])
136
175
  caps["appium:app"] = app
137
176
  # Drop app-identifier caps that may belong to a different build —
138
177
  # cloud providers auto-detect these from the uploaded binary.
@@ -170,7 +209,9 @@ def _inject_into_options(options):
170
209
  # Caps that _apply_caps_to_dict deliberately removed (the stale
171
210
  # app-identifier caps when an app URL is supplied) must be deleted
172
211
  # from the options object too — set_capability only adds/overwrites.
173
- dropped = set(existing.keys()) - set(merged.keys())
212
+ # (by the namespaced name: a legacy `automationName` the client lists
213
+ # unprefixed lives on as `appium:automationName` — it isn't dropped)
214
+ dropped = {k for k in existing.keys() if _prefix_key(k) not in merged}
174
215
  for k in dropped:
175
216
  removed = False
176
217
  internal = getattr(options, "_caps", None)
@@ -237,6 +278,8 @@ def _report_external_session(driver):
237
278
  "deviceName": os.environ.get("TESTVER_DEVICE_NAME"),
238
279
  "platformName": os.environ.get("TESTVER_PLATFORM_NAME"),
239
280
  "providerId": os.environ.get("TESTVER_PROVIDER"),
281
+ # the run that opened it (several runs of one tab side by side)
282
+ "runId": os.environ.get("TESTVER_RUN_ID"),
240
283
  })
241
284
  _log("Reported session " + str(sid)[:12] + "... for live preview")
242
285
 
@@ -258,12 +301,16 @@ def _unreport_external_session():
258
301
 
259
302
  # ── App reset on attach ──────────────────────────────────────────────────────
260
303
 
304
+ _project_app_id = {"value": None}
305
+
306
+
261
307
  def _reset_app_on_attach(driver, caps):
262
308
  if os.environ.get("TESTVER_SKIP_APP_RESET") == "1":
263
309
  return
264
310
  app_id = (
265
311
  (caps or {}).get("appium:appPackage")
266
312
  or (caps or {}).get("appium:bundleId")
313
+ or _project_app_id["value"]
267
314
  or os.environ.get("TESTVER_APP_PACKAGE")
268
315
  or os.environ.get("TESTVER_APP_BUNDLE_ID")
269
316
  )
@@ -311,6 +358,19 @@ def _patch_remote(remote_cls):
311
358
  args = (hub,) + tuple(args[1:])
312
359
  else:
313
360
  kwargs["command_executor"] = hub
361
+ # Appium-Python-Client 5+ (and AppiumLibrary 3+) pass a
362
+ # client_config whose server address wins over command_executor.
363
+ cc = kwargs.get("client_config")
364
+ if cc is not None and hasattr(cc, "remote_server_addr"):
365
+ try:
366
+ cc.remote_server_addr = hub
367
+ user = os.environ.get("APPIUM_HUB_USER") or ""
368
+ key = os.environ.get("APPIUM_HUB_KEY") or ""
369
+ if user and hasattr(cc, "username"):
370
+ cc.username = user
371
+ cc.password = key
372
+ except Exception as exc: # pragma: no cover
373
+ _log("could not redirect client_config: %s" % exc)
314
374
  # 2. Inject capabilities (AppiumOptions or desired_capabilities dict).
315
375
  opts = kwargs.get("options")
316
376
  if opts is None:
@@ -0,0 +1,110 @@
1
+ """
2
+ Testver listener for Robot Framework.
3
+
4
+ Loaded automatically by Testver — nothing to add to a suite:
5
+ PYTHONPATH += <this dir>
6
+ ROBOT_OPTIONS += --listener testver_robot
7
+
8
+ What it does, only when Testver asks for it through the environment:
9
+
10
+ * Web cloud / Testver Grid runs (TESTVER_ROBOT_REMOTE=1): SeleniumLibrary's
11
+ ``Open Browser`` opens the browser on the hub in SELENIUM_REMOTE_URL
12
+ instead of on this machine. A ``remote_url`` the suite passes itself
13
+ is kept.
14
+ * Mobile runs (TESTVER_PROVIDER / APPIUM_HUB_HOST set): loads the
15
+ ``testver_appium`` agent, which points the Appium Python client that
16
+ AppiumLibrary uses at the chosen device / hub and adds the device and
17
+ app capabilities.
18
+
19
+ In any other run it does nothing.
20
+ """
21
+
22
+ import os
23
+ import sys
24
+
25
+ ROBOT_LISTENER_API_VERSION = 3
26
+
27
+ _state = {"selenium": False}
28
+
29
+
30
+ def _log(msg):
31
+ try:
32
+ sys.stderr.write("[testver-robot] " + str(msg) + "\n")
33
+ sys.stderr.flush()
34
+ except Exception:
35
+ pass
36
+
37
+
38
+ def _remote_url():
39
+ if os.environ.get("TESTVER_ROBOT_REMOTE") != "1":
40
+ return None
41
+ return os.environ.get("SELENIUM_REMOTE_URL") or None
42
+
43
+
44
+ def _no_remote(value):
45
+ # Open Browser's default is remote_url=False (a bool); "False"/"None"
46
+ # strings come from suites passing ${FALSE}-style values as text.
47
+ if not value:
48
+ return True
49
+ return isinstance(value, str) and value.strip().upper() in ("FALSE", "NONE")
50
+
51
+
52
+ def _patch_selenium_library():
53
+ """Make WebDriverCreator.create_driver use the hub when no remote_url is given."""
54
+ if _state["selenium"] or _remote_url() is None:
55
+ return
56
+ try:
57
+ from SeleniumLibrary.keywords import webdrivertools # type: ignore
58
+ except Exception:
59
+ return
60
+ creator = getattr(webdrivertools, "WebDriverCreator", None)
61
+ original = getattr(creator, "create_driver", None) if creator else None
62
+ if original is None or getattr(original, "_testver", False):
63
+ _state["selenium"] = True
64
+ return
65
+
66
+ def create_driver(self, *args, **kwargs):
67
+ hub = _remote_url()
68
+ if hub:
69
+ # create_driver(browser, desired_capabilities, remote_url, ...)
70
+ if "remote_url" in kwargs:
71
+ if _no_remote(kwargs.get("remote_url")):
72
+ kwargs["remote_url"] = hub
73
+ elif len(args) >= 3:
74
+ if _no_remote(args[2]):
75
+ args = args[:2] + (hub,) + args[3:]
76
+ else:
77
+ kwargs["remote_url"] = hub
78
+ return original(self, *args, **kwargs)
79
+
80
+ create_driver._testver = True # type: ignore[attr-defined]
81
+ creator.create_driver = create_driver
82
+ _state["selenium"] = True
83
+ _log("SeleniumLibrary browsers open on the Testver-selected hub")
84
+
85
+
86
+ def _load_appium_agent():
87
+ if os.environ.get("TESTVER_PROVIDER") or os.environ.get("APPIUM_HUB_HOST"):
88
+ try:
89
+ import testver_appium # noqa: F401 (installs itself on import)
90
+ except Exception as exc: # pragma: no cover
91
+ _log("Appium agent not loaded: %s" % exc)
92
+
93
+
94
+ _load_appium_agent()
95
+ _patch_selenium_library()
96
+
97
+
98
+ # ── listener hooks: libraries are imported as suites start ───────────────────
99
+
100
+ def start_suite(data, result):
101
+ _patch_selenium_library()
102
+
103
+
104
+ def start_test(data, result):
105
+ _patch_selenium_library()
106
+
107
+
108
+ def start_keyword(data, result):
109
+ if not _state["selenium"] and _remote_url() is not None:
110
+ _patch_selenium_library()
@@ -80,6 +80,8 @@ async function reportSession(browser) {
80
80
  deviceName: caps['appium:deviceName'] || process.env.TESTVER_DEVICE_NAME,
81
81
  platformName: caps.platformName || process.env.TESTVER_PLATFORM_NAME,
82
82
  providerId: process.env.TESTVER_PROVIDER,
83
+ // the run that opened it (several runs of one tab side by side)
84
+ runId: process.env.TESTVER_RUN_ID,
83
85
  });
84
86
  try {
85
87
  await fetch(reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external', {
@@ -129,14 +131,29 @@ class TestverAttachService {
129
131
 
130
132
  /**
131
133
  * `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.
134
+ * WDIO's runner (v7–v9) ATTACHES instead of opening a session when the
135
+ * worker's config carries a `sessionId` — so the reused session and the
136
+ * hub it lives on go onto that config. (A browser left on globalThis was
137
+ * never read: WDIO opened a fresh session on the same device, restarting
138
+ * UiAutomator2 under the AI Assistant's live session.)
136
139
  */
137
- async beforeSession(_config, _capabilities) {
140
+ async beforeSession(config, _capabilities) {
138
141
  const sid = process.env.TESTVER_REUSE_SESSION_ID;
139
142
  if (!sid) return; // No reuse — let WDIO open a fresh session.
143
+ if (config && typeof config === 'object') {
144
+ Object.assign(config, {
145
+ sessionId: sid,
146
+ hostname: process.env.APPIUM_HUB_HOST || config.hostname,
147
+ port: Number(process.env.APPIUM_HUB_PORT || config.port || 443),
148
+ protocol: process.env.APPIUM_HUB_PROTOCOL || config.protocol || 'https',
149
+ path: process.env.APPIUM_HUB_PATH || config.path || '/wd/hub',
150
+ user: process.env.APPIUM_HUB_USER || config.user,
151
+ key: process.env.APPIUM_HUB_KEY || config.key,
152
+ });
153
+ // eslint-disable-next-line no-console
154
+ console.log(`[testver-attach] Attaching to session ${sid.slice(0, 12)}…`);
155
+ return;
156
+ }
140
157
 
141
158
  const wdio = loadWebdriverio();
142
159
  const attachOpts = {
@@ -180,6 +197,11 @@ class TestverAttachService {
180
197
  */
181
198
  async before(_capabilities, _specs, browser) {
182
199
  const b = browser || globalThis.browser;
200
+ // A reused session belongs to the AI Assistant: WDIO's end-of-run
201
+ // deleteSession (and the test's own) must leave it open.
202
+ if (process.env.TESTVER_REUSE_SESSION_ID && b && typeof b.overwriteCommand === 'function') {
203
+ try { b.overwriteCommand('deleteSession', async () => undefined); } catch { /* best-effort */ }
204
+ }
183
205
  try { await reportSession(b); } catch { /* best-effort */ }
184
206
  }
185
207
 
@@ -137,6 +137,18 @@ function applyTestverOverrides(opts) {
137
137
  if (process.env.TESTVER_PLATFORM_NAME) caps.platformName = process.env.TESTVER_PLATFORM_NAME;
138
138
  if (process.env.TESTVER_DEVICE_NAME) caps['appium:deviceName'] = process.env.TESTVER_DEVICE_NAME;
139
139
  if (process.env.TESTVER_PLATFORM_VERSION) caps['appium:platformVersion'] = process.env.TESTVER_PLATFORM_VERSION;
140
+ // The device: a local one by its serial / udid (Appium picks the device by
141
+ // appium:udid, never by deviceName); on a vendor's cloud a local udid / AVD
142
+ // means nothing.
143
+ if (process.env.TESTVER_PROVIDER === 'local-appium') {
144
+ if (process.env.TESTVER_DEVICE_UDID) {
145
+ caps['appium:udid'] = process.env.TESTVER_DEVICE_UDID;
146
+ delete caps['appium:avd'];
147
+ }
148
+ } else {
149
+ delete caps['appium:udid'];
150
+ delete caps['appium:avd'];
151
+ }
140
152
  if (process.env.TESTVER_APP_URL) {
141
153
  caps['appium:app'] = process.env.TESTVER_APP_URL;
142
154
  // The user's test code may hard-code app-identifier caps that
@@ -147,6 +159,9 @@ function applyTestverOverrides(opts) {
147
159
  // makes the run robust against mismatches like:
148
160
  // [BROWSERSTACK_INVALID_APP_ACTIVITY] Activity name "..." used
149
161
  // to start the app doesn't exist. Supported values: "c".
162
+ // (the project's package / bundle id is kept aside for the app reset
163
+ // on a reused session)
164
+ projectAppId = caps['appium:appPackage'] || caps['appium:bundleId'] || projectAppId;
150
165
  delete caps['appium:appPackage'];
151
166
  delete caps['appium:appActivity'];
152
167
  delete caps['appium:appWaitActivity'];
@@ -181,37 +196,22 @@ function applyTestverOverrides(opts) {
181
196
  // 1. Testver env var (explicit selection by UI / Runner)
182
197
  // 2. User-provided `appium:deviceName` from their caps
183
198
  // 3. Anything the user already put in `bstack:options.deviceName`
184
- const provider = process.env.TESTVER_PROVIDER;
185
- const deviceFromEnv = process.env.TESTVER_DEVICE_NAME;
186
- const osVerFromEnv = process.env.TESTVER_PLATFORM_VERSION;
187
- const deviceFromUser = caps['appium:deviceName'];
188
- const osVerFromUser = caps['appium:platformVersion'];
189
- const providerOpts = {
190
- projectName: 'Testver',
191
- buildName: process.env.TESTVER_BUILD_NAME || 'testver-cloud-run',
192
- sessionName: process.env.TESTVER_SESSION_NAME || 'mobile-test',
193
- };
194
- const resolvedDevice = deviceFromEnv || deviceFromUser;
195
- const resolvedOsVer = osVerFromEnv || osVerFromUser;
196
-
197
- if (provider === 'browserstack') {
198
- const existing = caps['bstack:options'] || {};
199
- caps['bstack:options'] = Object.assign({}, existing, providerOpts);
200
- // BrowserStack uses `deviceName` + `osVersion` keys.
201
- if (resolvedDevice && !existing.deviceName) caps['bstack:options'].deviceName = resolvedDevice;
202
- if (resolvedOsVer && !existing.osVersion) caps['bstack:options'].osVersion = resolvedOsVer;
203
- } else if (provider === 'saucelabs') {
204
- const existing = caps['sauce:options'] || {};
205
- caps['sauce:options'] = Object.assign({}, existing, providerOpts);
206
- // Sauce Labs uses `deviceName` (or `appium:deviceName` at top level — both honoured).
207
- if (resolvedDevice && !existing.deviceName) caps['sauce:options'].deviceName = resolvedDevice;
208
- if (resolvedOsVer && !existing.platformVersion) caps['sauce:options'].platformVersion = resolvedOsVer;
209
- } else if (provider === 'lambdatest') {
210
- const existing = caps['LT:Options'] || {};
211
- caps['LT:Options'] = Object.assign({}, existing, providerOpts);
212
- // LambdaTest uses `deviceName` + `platformVersion`.
213
- if (resolvedDevice && !existing.deviceName) caps['LT:Options'].deviceName = resolvedDevice;
214
- if (resolvedOsVer && !existing.platformVersion) caps['LT:Options'].platformVersion = resolvedOsVer;
199
+ // The vendor block Testver built for this run (TESTVER_VENDOR_OPTIONS):
200
+ // each vendor's own field names, the tunnel, the picked device. Names and
201
+ // tunnel: the project's own values win; the picked device wins over the
202
+ // project's. Without it (an older run plan) the device and OS version are
203
+ // still mirrored into the vendor's block.
204
+ let vendor = null;
205
+ try { vendor = process.env.TESTVER_VENDOR_OPTIONS ? JSON.parse(process.env.TESTVER_VENDOR_OPTIONS) : null; } catch (e) { vendor = null; }
206
+ if (vendor && vendor.key) {
207
+ caps[vendor.key] = Object.assign({}, vendor.options || {}, caps[vendor.key] || {}, vendor.overrides || {});
208
+ } else {
209
+ const key = { browserstack: 'bstack:options', saucelabs: 'sauce:options', lambdatest: 'LT:Options' }[process.env.TESTVER_PROVIDER || ''];
210
+ const device = process.env.TESTVER_DEVICE_NAME || caps['appium:deviceName'];
211
+ if (key && device) {
212
+ const existing = caps[key] || {};
213
+ caps[key] = Object.assign({}, existing, existing.deviceName ? {} : { deviceName: device });
214
+ }
215
215
  }
216
216
  return opts;
217
217
  }
@@ -267,6 +267,9 @@ function applyTestverOverrides(opts) {
267
267
  *
268
268
  * Disable: set TESTVER_SKIP_APP_RESET=1 in the run env.
269
269
  */
270
+ /** The project's own app package / bundle id, before an uploaded app replaced it in the caps. */
271
+ let projectAppId;
272
+
270
273
  async function resetAppOnAttach(browser, caps) {
271
274
  // Idempotency guard — if the browser already went through a reset
272
275
  // (e.g. wdio.remote() delegated to wdio.attach() which is also
@@ -281,6 +284,7 @@ async function resetAppOnAttach(browser, caps) {
281
284
  return;
282
285
  }
283
286
  const appId = (caps && (caps['appium:appPackage'] || caps['appium:bundleId']))
287
+ || projectAppId
284
288
  || process.env.TESTVER_APP_PACKAGE
285
289
  || process.env.TESTVER_APP_BUNDLE_ID;
286
290
  if (!appId) {
@@ -445,6 +449,8 @@ function reportExternalSession(browser, patched) {
445
449
  deviceName: patched.capabilities && patched.capabilities['appium:deviceName'],
446
450
  platformName: patched.capabilities && patched.capabilities.platformName,
447
451
  providerId: process.env.TESTVER_PROVIDER,
452
+ // the run that opened it (several runs of one tab side by side)
453
+ runId: process.env.TESTVER_RUN_ID,
448
454
  });
449
455
  const endpoint = reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external';
450
456
  // Node 18+ has global fetch — we target Node 20 in the parent app.