Debian Codegraph @

testing/web-platform/tests/tools/wpt/browser.py

raw
1 # mypy: allow-untyped-defs
2 import configparser
3 import json
4 import os
5 import platform
6 import re
7 import shutil
8 import stat
9 import subprocess
10 import tempfile
11 from abc import ABCMeta, abstractmethod
12 from datetime import datetime, timedelta, timezone
13 from shutil import which
14 from typing import Any, Dict, Optional, Tuple
15 from urllib.parse import urlsplit, quote
16
17 import html5lib
18 import requests
19 from packaging.specifiers import SpecifierSet
20
21 from .utils import (
22 call,
23 get,
24 get_download_to_descriptor,
25 rmtree,
26 sha256sum,
27 untar,
28 unzip,
29 )
30 from .wpt import venv_dir
31
32 uname = platform.uname()
33
34 # The root URL for Chrome for Testing API endpoints.
35 CHROME_FOR_TESTING_ROOT_URL = "https://googlechromelabs.github.io/chrome-for-testing/"
36 # File name containing a matching ChromeDriver download URL for a specific Chrome download.
37 CHROMEDRIVER_SAVED_DOWNLOAD_FILE = "matching_chromedriver_url.txt"
38
39 # the rootUrl for the firefox-ci deployment of Taskcluster
40 FIREFOX_CI_ROOT_URL = 'https://firefox-ci-tc.services.mozilla.com'
41
42
43 def _get_fileversion(binary, logger=None):
44 command = "(Get-Item -ErrorAction Stop '%s').VersionInfo.FileVersion" % binary.replace("'", "''")
45 try:
46 return call("powershell.exe", command).strip()
47 except (subprocess.CalledProcessError, OSError):
48 if logger is not None:
49 logger.warning("Failed to call %s in PowerShell" % command)
50 return None
51
52
53 def get_ext(filename):
54 """Get the extension from a filename with special handling for .tar.foo"""
55 name, ext = os.path.splitext(filename)
56 if name.endswith(".tar"):
57 ext = ".tar%s" % ext
58 return ext
59
60
61 def get_download_filename(resp, default=None):
62 """Get the filename from a requests.Response, or default"""
63 filename = None
64
65 content_disposition = resp.headers.get("content-disposition")
66 if content_disposition:
67 filenames = re.findall("filename=(.+)", content_disposition)
68 if filenames:
69 filename = filenames[0]
70
71 if not filename:
72 filename = urlsplit(resp.url).path.rsplit("/", 1)[1]
73
74 return filename or default
75
76
77 def get_taskcluster_artifact(index, path):
78 TC_INDEX_BASE = FIREFOX_CI_ROOT_URL + "/api/index/v1/"
79
80 resp = get(TC_INDEX_BASE + "task/%s/artifacts/%s" % (index, path))
81 resp.raise_for_status()
82
83 return resp
84
85
86 def get_file_github(repo: str, ref: str, path: str) -> bytes:
87 data: bytes = get(f"https://raw.githubusercontent.com/{repo}/{ref}/{path}").content # type: ignore
88 return data
89
90
91 class Browser:
92 __metaclass__ = ABCMeta
93
94 def __init__(self, logger):
95 self.logger = logger
96
97 def _get_browser_download_dir(self, dest, channel):
98 if dest is None:
99 return self._get_browser_binary_dir(dest, channel)
100
101 return dest
102
103 def _get_browser_binary_dir(self, dest, channel):
104 if dest is None:
105 # os.getcwd() doesn't include the venv path
106 dest = os.path.join(os.getcwd(), venv_dir())
107
108 dest = os.path.join(dest, "browsers", channel)
109
110 if not os.path.exists(dest):
111 os.makedirs(dest)
112
113 return dest
114
115 def download_from_url(
116 self, url, dest=None, channel=None, rename=None, default_name="download"
117 ):
118 """Download a URL into a dest/channel
119 :param url: The URL to download
120 :param dest: Directory in which to put the dowloaded
121 :param channel: Browser channel to append to the dest
122 :param rename: Optional name for the download; the original extension
123 is preserved
124 :param default_name: The default name for the download if none is
125 provided and none can be found from the network
126 :return: The path to the downloaded package/installer
127 """
128 self.logger.info("Downloading from %s" % url)
129
130 dest = self._get_browser_download_dir(dest, channel)
131
132 resp = get(url)
133 filename = get_download_filename(resp, default_name)
134 if rename:
135 filename = "%s%s" % (rename, get_ext(filename))
136
137 output_path = os.path.join(dest, filename)
138
139 with open(output_path, "wb") as f:
140 for chunk in resp.iter_content(chunk_size=64 * 1024):
141 f.write(chunk)
142
143 return output_path
144
145 @abstractmethod
146 def download(self, dest=None, channel=None, rename=None):
147 """Download a package or installer for the browser
148 :param dest: Directory in which to put the dowloaded package
149 :param channel: Browser channel to download
150 :param rename: Optional name for the downloaded package; the original
151 extension is preserved.
152 :return: The path to the downloaded package/installer
153 """
154 return NotImplemented
155
156 @abstractmethod
157 def install(self, dest=None, channel=None):
158 """Download and install the browser.
159
160 This method usually calls download().
161
162 :param dest: Directory in which to install the browser
163 :param channel: Browser channel to install
164 :return: The path to the installed browser
165 """
166 return NotImplemented
167
168 @abstractmethod
169 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
170 """Download and install the WebDriver implementation for this browser.
171
172 :param dest: Directory in which to install the WebDriver
173 :param channel: Browser channel to install
174 :param browser_binary: The path to the browser binary
175 :return: The path to the installed WebDriver
176 """
177 return NotImplemented
178
179 @abstractmethod
180 def find_binary(self, venv_path=None, channel=None):
181 """Find the binary of the browser.
182
183 If the WebDriver for the browser is able to find the binary itself, this
184 method doesn't need to be implemented, in which case NotImplementedError
185 is suggested to be raised to prevent accidental use.
186 """
187 return NotImplemented
188
189 @abstractmethod
190 def find_webdriver(self, venv_path=None, channel=None):
191 """Find the binary of the WebDriver."""
192 return NotImplemented
193
194 @abstractmethod
195 def version(self, binary=None, webdriver_binary=None):
196 """Retrieve the release version of the installed browser."""
197 return NotImplemented
198
199 @abstractmethod
200 def requirements(self):
201 """Name of the browser-specific wptrunner requirements file"""
202 return NotImplemented
203
204
205 class Firefox(Browser):
206 """Firefox-specific interface.
207
208 Includes installation, webdriver installation, and wptrunner setup methods.
209 """
210
211 product = "firefox"
212 binary = "browsers/firefox/firefox"
213 requirements = "requirements_firefox.txt"
214
215 platform = {
216 "Linux": "linux",
217 "Windows": "win",
218 "Darwin": "macos"
219 }.get(uname[0])
220
221 application_name = {
222 "stable": "Firefox.app",
223 "beta": "Firefox.app",
224 "nightly": "Firefox Nightly.app"
225 }
226
227 def platform_string_geckodriver(self):
228 if self.platform is None:
229 raise ValueError("Unable to construct a valid Geckodriver package name for current platform")
230
231 if self.platform in ("linux", "win"):
232 bits = "64" if uname[4] == "x86_64" else "32"
233 elif self.platform == "macos" and uname.machine == "arm64":
234 bits = "-aarch64"
235 else:
236 bits = ""
237
238 return "%s%s" % (self.platform, bits)
239
240 def download(self, dest=None, channel="nightly", rename=None):
241 product = {
242 "nightly": "firefox-nightly-latest-ssl",
243 "beta": "firefox-beta-latest-ssl",
244 "stable": "firefox-latest-ssl"
245 }
246
247 os_builds = {
248 ("linux", "x86"): "linux",
249 ("linux", "x86_64"): "linux64",
250 ("win", "x86"): "win",
251 ("win", "AMD64"): "win64",
252 ("macos", "x86_64"): "osx",
253 ("macos", "arm64"): "osx",
254 }
255 os_key = (self.platform, uname[4])
256
257 dest = self._get_browser_download_dir(dest, channel)
258
259 if channel not in product:
260 raise ValueError("Unrecognised release channel: %s" % channel)
261
262 if os_key not in os_builds:
263 raise ValueError("Unsupported platform: %s %s" % os_key)
264
265 url = "https://download.mozilla.org/?product=%s&os=%s&lang=en-US" % (product[channel],
266 os_builds[os_key])
267 self.logger.info("Downloading Firefox from %s" % url)
268 resp = get(url)
269
270 filename = get_download_filename(resp, "firefox.tar.bz2")
271
272 if rename:
273 filename = "%s%s" % (rename, get_ext(filename))
274
275 installer_path = os.path.join(dest, filename)
276
277 with open(installer_path, "wb") as f:
278 f.write(resp.content)
279
280 return installer_path
281
282 def install(self, dest=None, channel="nightly"):
283 """Install Firefox."""
284 import mozinstall
285
286 dest = self._get_browser_binary_dir(dest, channel)
287
288 filename = os.path.basename(dest)
289
290 installer_path = self.download(dest, channel)
291
292 try:
293 mozinstall.install(installer_path, dest)
294 except mozinstall.mozinstall.InstallError:
295 if self.platform == "macos" and os.path.exists(os.path.join(dest, self.application_name.get(channel, "Firefox Nightly.app"))):
296 # mozinstall will fail if nightly is already installed in the venv because
297 # mac installation uses shutil.copy_tree
298 mozinstall.uninstall(os.path.join(dest, self.application_name.get(channel, "Firefox Nightly.app")))
299 mozinstall.install(filename, dest)
300 else:
301 raise
302
303 os.remove(installer_path)
304 return self.find_binary_path(dest)
305
306 def find_binary_path(self, path=None, channel="nightly"):
307 """Looks for the firefox binary in the virtual environment"""
308
309 if path is None:
310 path = self._get_browser_binary_dir(None, channel)
311
312 binary = None
313
314 if self.platform == "linux":
315 binary = which("firefox", path=os.path.join(path, "firefox"))
316 elif self.platform == "win":
317 import mozinstall
318 try:
319 binary = mozinstall.get_binary(path, "firefox")
320 except mozinstall.InvalidBinary:
321 # ignore the case where we fail to get a binary
322 pass
323 elif self.platform == "macos":
324 binary = which("firefox",
325 path=os.path.join(path,
326 self.application_name.get(channel, "Firefox Nightly.app"),
327 "Contents", "MacOS"))
328
329 return binary
330
331 def find_binary(self, venv_path=None, channel="nightly"):
332
333 path = self._get_browser_binary_dir(venv_path, channel)
334 binary = self.find_binary_path(path, channel)
335
336 if not binary and self.platform == "win":
337 winpaths = [os.path.expandvars("$SYSTEMDRIVE\\Program Files\\Mozilla Firefox"),
338 os.path.expandvars("$SYSTEMDRIVE\\Program Files (x86)\\Mozilla Firefox")]
339 for winpath in winpaths:
340 binary = self.find_binary_path(winpath, channel)
341 if binary is not None:
342 break
343
344 if not binary and self.platform == "macos":
345 macpaths = ["/Applications/Firefox Nightly.app/Contents/MacOS",
346 os.path.expanduser("~/Applications/Firefox Nightly.app/Contents/MacOS"),
347 "/Applications/Firefox Developer Edition.app/Contents/MacOS",
348 os.path.expanduser("~/Applications/Firefox Developer Edition.app/Contents/MacOS"),
349 "/Applications/Firefox.app/Contents/MacOS",
350 os.path.expanduser("~/Applications/Firefox.app/Contents/MacOS")]
351 return which("firefox", path=os.pathsep.join(macpaths))
352
353 if binary is None:
354 return which("firefox")
355
356 return binary
357
358 def find_certutil(self):
359 path = which("certutil")
360 if path is None:
361 return None
362 if os.path.splitdrive(os.path.normcase(path))[1].split(os.path.sep) == ["", "windows", "system32", "certutil.exe"]:
363 return None
364 return path
365
366 def find_webdriver(self, venv_path=None, channel=None):
367 return which("geckodriver")
368
369 def extract_version_number(self, version_string: str) -> Tuple[Optional[str], str]:
370 version_parser = re.compile(r"^(\d+)\.(\d+)(?:\.(\d+))?((a|b)\d+)?")
371 m = version_parser.match(version_string)
372 if not m:
373 return None, "nightly"
374 major, minor, patch, pre, channel_id = m.groups()
375 version = f"{major}.{minor}"
376 if patch is not None:
377 version += f".{patch}"
378 if pre is not None:
379 version += pre
380 channel = {"a": "nightly", "b": "beta"}.get(channel_id, "stable")
381 return version, channel
382
383 def get_version_and_channel(self, binary: str) -> Tuple[Optional[str], str, Optional[str]]:
384 application_ini_path = os.path.join(os.path.dirname(binary), "application.ini")
385 if os.path.exists(application_ini_path):
386 try:
387 return self.get_version_and_channel_application_ini(application_ini_path)
388 except ValueError as e:
389 self.logger.info(f"Reading application ini file failed: {e}")
390 # Fall back to calling the binary
391 version_string: str = call(binary, "--version").strip() # type: ignore
392 version_re = re.compile(r"Mozilla Firefox (.*)")
393 m = version_re.match(version_string)
394 if not m:
395 return None, "nightly", None
396 version, channel = self.extract_version_number(m.group(1))
397 return version, channel, None
398
399 def get_version_and_channel_application_ini(self, path: str) -> Tuple[Optional[str], str, Optional[str]]:
400 """Try to read application version from an ini file
401
402 This doesn't work in all cases e.g. local builds don't have
403 all the information, or builds where the binary path is a shell
404 script or similar."""
405 config = configparser.ConfigParser()
406 paths = config.read(path)
407 if path not in paths:
408 raise ValueError("Failed to read config file")
409
410 version = config.get("App", "Version", fallback=None)
411 if version is None:
412 raise ValueError("Failed to find Version key")
413 version, channel = self.extract_version_number(version)
414
415 rev = None
416 if channel == "nightly":
417 source_repo = config.get("App", "SourceRepository", fallback=None)
418 commit = config.get("App", "SourceStamp", fallback=None)
419 if source_repo is not None and commit is not None:
420 if source_repo.startswith("https://hg.mozilla.org"):
421 try:
422 commit_data: Dict[str, Any] = get(
423 f"https://hg-edge.mozilla.org/integration/autoland/json-rev/{commit}"
424 ).json() # type: ignore
425 rev = commit_data.get("git_commit")
426 except Exception:
427 pass
428 else:
429 rev = commit
430
431 return version, channel, rev
432
433 def get_git_ref(self, version: str, channel: str, rev: Optional[str]) -> str:
434 if rev is not None:
435 return rev
436
437 if channel == "stable":
438 return "FIREFOX_%s_RELEASE" % version.replace(".", "_")
439
440 if channel == "beta":
441 ref_prefix = "FIREFOX_%s" % version.replace(".", "_")
442 tags = []
443 build_re = re.compile(fr"{ref_prefix}_BUILD(\d)+")
444 for tag_data in get(
445 f"https://api.github.com/repos/mozilla-firefox/firefox/git/matching-refs/tags/{ref_prefix}"
446 ).json(): # type: ignore
447 tag = tag_data["ref"].rsplit("/", 1)[1]
448 if tag.endswith("_RELEASE"):
449 tags = [(0, tag)]
450 break
451 m = build_re.match(tag)
452 if m:
453 tags.append((int(m.group(1)), tag))
454 tags.sort()
455 if not tags:
456 raise ValueError(f"No tag found for {version} beta")
457 return f"{tags[-1][1]}"
458
459 return "main"
460
461 def get_profile_github(self, version: str, channel: str, dest: str, rev: Optional[str]) -> None:
462 """Read the testing/profiles data from firefox source on GitHub"""
463
464 # There are several possible approaches here, none of which are great:
465 # 1. Shallow, sparse, clone of the repo with no history and just the testing/profiles
466 # directory. This is too slow to be usable.
467 # 2. Use the Github repository contents API to read all the files under that directory.
468 # This requires auth to not run into rate limits.
469 # 3. Gitub tree API has basically the same problems
470 # 4. Download a full archive of the relevant commit from Github and extract only the
471 # required directory. This is also too slow to be useful.
472 #
473 # In the end we use githubusercontent.com, which has the problem that it doesn't allow
474 # directory listings. So we have to hardcode in all the files we need. In particular
475 # for each profile we are currently just downloading the user.js file and ignoring the
476 # extensions/ directory, which is currently unused.
477 ref = self.get_git_ref(version, channel, rev)
478 file_data = {}
479 profiles_bytes = get_file_github("mozilla-firefox/firefox", ref, "testing/profiles/profiles.json")
480 profiles = json.loads(profiles_bytes)
481 file_data["profiles.json"] = profiles_bytes
482 for subdir in profiles["web-platform-tests"]:
483 rel_path = os.path.join(subdir, "user.js")
484 file_data[rel_path] = get_file_github("mozilla-firefox/firefox",
485 ref,
486 f"testing/profiles/{subdir}/user.js")
487
488 for path, data in file_data.items():
489 dest_path = os.path.join(dest, path)
490 os.makedirs(os.path.dirname(dest_path), exist_ok=True)
491 with open(dest_path, "wb") as f:
492 f.write(data)
493
494 def install_prefs(self, binary, dest=None, channel=None):
495 if binary and not binary.endswith(".apk"):
496 version, channel_, rev = self.get_version_and_channel(binary)
497 if channel is not None and channel != channel_:
498 # Beta doesn't always seem to have the b in the version string, so allow the
499 # manually supplied value to override the one from the binary
500 self.logger.warning("Supplied channel doesn't match binary, using supplied channel")
501 elif channel is None:
502 channel = channel_
503 else:
504 rev = None
505 version = None
506
507 if dest is None:
508 dest = os.curdir
509
510 dest = os.path.join(dest, "profiles", rev if rev is not None else channel)
511 if version:
512 dest = os.path.join(dest, version)
513 have_cache = False
514 if os.path.exists(dest) and os.path.exists(os.path.join(dest, "profiles.json")):
515 if channel != "nightly":
516 have_cache = True
517 else:
518 now = datetime.now()
519 have_cache = (datetime.fromtimestamp(os.stat(dest).st_mtime) >
520 now - timedelta(days=1))
521
522 # If we don't have a recent download, grab and extract the latest one
523 if not have_cache:
524 if os.path.exists(dest):
525 rmtree(dest)
526 os.makedirs(dest)
527
528 self.get_profile_github(version, channel, dest, rev)
529 self.logger.info(f"Test prefs downloaded to {dest}")
530 else:
531 self.logger.info(f"Using cached test prefs from {dest}")
532
533 return dest
534
535 def _latest_geckodriver_version(self):
536 """Get and return latest version number for geckodriver."""
537 # This is used rather than an API call to avoid rate limits
538 tags = call("git", "ls-remote", "--tags", "--refs",
539 "https://github.com/mozilla/geckodriver.git")
540 release_re = re.compile(r".*refs/tags/v(\d+)\.(\d+)\.(\d+)")
541 latest_release = (0, 0, 0)
542 for item in tags.split("\n"):
543 m = release_re.match(item)
544 if m:
545 version = tuple(int(item) for item in m.groups())
546 if version > latest_release:
547 latest_release = version
548 assert latest_release != (0, 0, 0)
549 return "v%s.%s.%s" % tuple(str(item) for item in latest_release)
550
551 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
552 """Install latest Geckodriver."""
553 if dest is None:
554 dest = os.getcwd()
555
556 path = None
557 if channel == "nightly":
558 path = self.install_geckodriver_nightly(dest)
559 if path is None:
560 self.logger.warning("Nightly webdriver not found; falling back to release")
561
562 if path is None:
563 version = self._latest_geckodriver_version()
564 format = "zip" if uname[0] == "Windows" else "tar.gz"
565 self.logger.debug("Latest geckodriver release %s" % version)
566 url = ("https://github.com/mozilla/geckodriver/releases/download/%s/geckodriver-%s-%s.%s" %
567 (version, version, self.platform_string_geckodriver(), format))
568 if format == "zip":
569 unzip(get(url).raw, dest=dest)
570 else:
571 untar(get(url).raw, dest=dest)
572 path = which("geckodriver", path=dest)
573
574 assert path is not None
575 self.logger.info("Installed %s" %
576 subprocess.check_output([path, "--version"]).splitlines()[0])
577 return path
578
579 def install_geckodriver_nightly(self, dest):
580 self.logger.info("Attempting to install webdriver from nightly")
581
582 platform_bits = ("64" if uname[4] == "x86_64" else
583 ("32" if self.platform == "win" else ""))
584 tc_platform = "%s%s" % (self.platform, platform_bits)
585
586 archive_ext = ".zip" if uname[0] == "Windows" else ".tar.gz"
587 archive_name = "public/build/geckodriver%s" % archive_ext
588
589 try:
590 resp = get_taskcluster_artifact(
591 "gecko.v2.mozilla-central.latest.geckodriver.%s" % tc_platform,
592 archive_name)
593 except Exception:
594 self.logger.info("Geckodriver download failed")
595 return
596
597 if archive_ext == ".zip":
598 unzip(resp.raw, dest)
599 else:
600 untar(resp.raw, dest)
601
602 exe_ext = ".exe" if uname[0] == "Windows" else ""
603 path = os.path.join(dest, "geckodriver%s" % exe_ext)
604
605 self.logger.info("Extracted geckodriver to %s" % path)
606
607 return path
608
609 def version(self, binary=None, webdriver_binary=None):
610 """Retrieve the release version of the installed browser."""
611 version_string = call(binary, "--version").strip()
612 m = re.match(r"Mozilla Firefox (.*)", version_string)
613 if not m:
614 return None
615 return m.group(1)
616
617
618 class FirefoxAndroid(Browser):
619 """Android-specific Firefox interface."""
620
621 product = "firefox_android"
622 requirements = "requirements_firefox.txt"
623
624 def __init__(self, logger):
625 super().__init__(logger)
626 self.apk_path = None
627 self._fx_browser = Firefox(self.logger)
628
629 def download(self, dest=None, channel=None, rename=None):
630 if dest is None:
631 dest = os.pwd
632
633 resp = get_taskcluster_artifact(
634 "gecko.v2.mozilla-central.shippable.latest.mobile.android-x86_64-opt",
635 "public/build/geckoview-test_runner.apk")
636
637 filename = "geckoview-test_runner.apk"
638 if rename:
639 filename = "%s%s" % (rename, get_ext(filename)[1])
640 self.apk_path = os.path.join(dest, filename)
641
642 with open(self.apk_path, "wb") as f:
643 f.write(resp.content)
644
645 return self.apk_path
646
647 def install(self, dest=None, channel=None):
648 return self.download(dest, channel)
649
650 def install_prefs(self, binary, dest=None, channel=None):
651 return self._fx_browser.install_prefs(binary, dest, channel)
652
653 def find_binary(self, venv_path=None, channel=None):
654 return self.apk_path
655
656 def find_webdriver(self, venv_path=None, channel=None):
657 return self._fx_browser.find_webdriver(venv_path, channel)
658
659 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
660 return self._fx_browser.install_webdriver(dest, channel, None)
661
662 def version(self, binary=None, webdriver_binary=None):
663 return None
664
665
666 class ChromeChromiumBase(Browser):
667 """
668 Chrome/Chromium base Browser class for shared functionality between Chrome and Chromium
669
670 For a detailed description on the installation and detection of these browser components,
671 see https://web-platform-tests.org/running-tests/chrome-chromium-installation-detection.html
672 """
673
674 requirements: Optional[str] = "requirements_chromium.txt"
675 platform = {
676 "Linux": "Linux",
677 "Windows": "Win",
678 "Darwin": "Mac",
679 }.get(uname[0])
680
681 def _build_snapshots_url(self, revision, filename):
682 return ("https://storage.googleapis.com/chromium-browser-snapshots/"
683 f"{self._chromium_platform_string}/{revision}/{filename}")
684
685 def _get_latest_chromium_revision(self):
686 """Returns latest Chromium revision available for download."""
687 # This is only used if the user explicitly passes "latest" for the revision flag.
688 # The pinned revision is used by default to avoid unexpected failures as versions update.
689 revision_url = ("https://storage.googleapis.com/chromium-browser-snapshots/"
690 f"{self._chromium_platform_string}/LAST_CHANGE")
691 return get(revision_url).text.strip()
692
693 def _get_pinned_chromium_revision(self):
694 """Returns the pinned Chromium revision number."""
695 return get("https://storage.googleapis.com/wpt-versions/pinned_chromium_revision").text.strip()
696
697 def _get_chromium_revision(self, filename=None, version=None):
698 """Retrieve a valid Chromium revision to download a browser component."""
699
700 # If a specific version is passed as an argument, we will use it.
701 if version is not None:
702 # Detect a revision number based on the version passed.
703 revision = self._get_base_revision_from_version(version)
704 if revision is not None:
705 # File name is needed to test if request is valid.
706 url = self._build_snapshots_url(revision, filename)
707 try:
708 # Check the status without downloading the content (this is a streaming request).
709 get(url)
710 return revision
711 except requests.RequestException:
712 self.logger.warning("404: Unsuccessful attempt to download file "
713 f"based on version. {url}")
714 # If no URL was used in a previous install
715 # and no version was passed, use the pinned Chromium revision.
716 revision = self._get_pinned_chromium_revision()
717
718 # If the url is successfully used to download/install, it will be used again
719 # if another component is also installed during this run (browser/webdriver).
720 return revision
721
722 def _get_base_revision_from_version(self, version):
723 """Get a Chromium revision number that is associated with a given version."""
724 # This is not the single revision associated with the version,
725 # but instead is where it branched from. Chromium revisions are just counting
726 # commits on the master branch, there are no Chromium revisions for branches.
727
728 version = self._remove_version_suffix(version)
729
730 # Try to find the Chromium build with the same revision.
731 try:
732 omaha = get(f"https://omahaproxy.appspot.com/deps.json?version={version}").json()
733 detected_revision = omaha['chromium_base_position']
734 return detected_revision
735 except requests.RequestException:
736 self.logger.debug("Unsuccessful attempt to detect revision based on version")
737 return None
738
739 def _remove_existing_chromedriver_binary(self, path):
740 """Remove an existing ChromeDriver for this product if it exists
741 in the virtual environment.
742 """
743 # There may be an existing chromedriver binary from a previous install.
744 # To provide a clean install experience, remove the old binary - this
745 # avoids tricky issues like unzipping over a read-only file.
746 existing_chromedriver_path = which("chromedriver", path=path)
747 if existing_chromedriver_path:
748 self.logger.info(f"Removing existing ChromeDriver binary: {existing_chromedriver_path}")
749 os.chmod(existing_chromedriver_path, stat.S_IWUSR)
750 os.remove(existing_chromedriver_path)
751
752 def _remove_version_suffix(self, version):
753 """Removes channel suffixes from Chrome/Chromium version string (e.g. " dev")."""
754 return version.split(' ')[0]
755
756 @property
757 def _chromedriver_platform_string(self):
758 """Returns a string that represents the suffix of the ChromeDriver
759 file name when downloaded from Chromium Snapshots.
760 """
761 if self.platform == "Linux":
762 bits = "64" if uname[4] == "x86_64" else "32"
763 elif self.platform == "Mac":
764 bits = "64"
765 elif self.platform == "Win":
766 bits = "32"
767 return f"{self.platform.lower()}{bits}"
768
769 @property
770 def _chromium_platform_string(self):
771 """Returns a string that is used for the platform directory in Chromium Snapshots"""
772 if (self.platform == "Linux" or self.platform == "Win") and uname[4] == "x86_64":
773 return f"{self.platform}_x64"
774 if self.platform == "Mac" and uname.machine == "arm64":
775 return "Mac_Arm"
776 return self.platform
777
778 def find_webdriver(self, venv_path=None, channel=None, browser_binary=None):
779 if venv_path:
780 venv_path = os.path.join(venv_path, self.product)
781 return which("chromedriver", path=venv_path)
782
783 def install_mojojs(self, dest, browser_binary):
784 """Install MojoJS web framework."""
785 # MojoJS is platform agnostic, but the version number must be an
786 # exact match of the Chrome/Chromium version to be compatible.
787 chrome_version = self.version(binary=browser_binary)
788 if not chrome_version:
789 return None
790 chrome_version = self._remove_version_suffix(chrome_version)
791
792 try:
793 # MojoJS version url must match the browser binary version exactly.
794 url = ("https://storage.googleapis.com/chrome-for-testing-public/"
795 f"{chrome_version}/mojojs.zip")
796 # Check the status without downloading the content (this is a streaming request).
797 get(url)
798 except requests.RequestException:
799 # If a valid matching version cannot be found in the CfT archive,
800 # download from Chromium snapshots bucket. However,
801 # MojoJS is only bundled with Linux from Chromium snapshots.
802 if self.platform == "Linux":
803 filename = "mojojs.zip"
804 revision = self._get_chromium_revision(filename, chrome_version)
805 url = self._build_snapshots_url(revision, filename)
806 else:
807 self.logger.error("A valid MojoJS version cannot be found "
808 f"for browser binary version {chrome_version}.")
809 return None
810
811 extracted = os.path.join(dest, "mojojs", "gen")
812 last_url_file = os.path.join(extracted, "DOWNLOADED_FROM")
813 if os.path.exists(last_url_file):
814 with open(last_url_file, "rt") as f:
815 last_url = f.read().strip()
816 if last_url == url:
817 self.logger.info("Mojo bindings already up to date")
818 return extracted
819 rmtree(extracted)
820
821 try:
822 self.logger.info(f"Downloading Mojo bindings from {url}")
823 unzip(get(url).raw, dest)
824 with open(last_url_file, "wt") as f:
825 f.write(url)
826 return extracted
827 except Exception as e:
828 self.logger.error(f"Cannot enable MojoJS: {e}")
829 return None
830
831 def install_webdriver_by_version(self, version, dest, revision=None):
832 dest = os.path.join(dest, self.product)
833 self._remove_existing_chromedriver_binary(dest)
834 # _get_webdriver_url is implemented differently for Chrome and Chromium because
835 # they download their respective versions of ChromeDriver from different sources.
836 url = self._get_webdriver_url(version, revision)
837 self.logger.info(f"Downloading ChromeDriver from {url}")
838 unzip(get(url).raw, dest)
839
840 # The two sources of ChromeDriver have different zip structures:
841 # * Chromium archives the binary inside a chromedriver_* directory;
842 # * Chrome archives the binary directly.
843 # We want to make sure the binary always ends up directly in bin/.
844 chromedriver_dir = os.path.join(dest,
845 f"chromedriver_{self._chromedriver_platform_string}")
846 chromedriver_path = which("chromedriver", path=chromedriver_dir)
847 if chromedriver_path is not None:
848 shutil.move(chromedriver_path, dest)
849 rmtree(chromedriver_dir)
850
851 chromedriver_path = which("chromedriver", path=dest)
852 assert chromedriver_path is not None
853 return chromedriver_path
854
855 def version(self, binary=None, webdriver_binary=None):
856 if not binary:
857 self.logger.warning("No browser binary provided.")
858 return None
859
860 if uname[0] == "Windows":
861 return _get_fileversion(binary, self.logger)
862
863 try:
864 version_string = call(binary, "--version").strip()
865 except (subprocess.CalledProcessError, OSError) as e:
866 self.logger.warning(f"Failed to call {binary}: {e}")
867 return None
868 m = re.match(r"(?:Google Chrome|Chromium) (.*)", version_string)
869 if not m:
870 self.logger.warning(f"Failed to extract version from: {version_string}")
871 return None
872 return m.group(1)
873
874 def webdriver_version(self, webdriver_binary):
875 if webdriver_binary is None:
876 self.logger.warning("No valid webdriver supplied to detect version.")
877 return None
878
879 try:
880 version_string = call(webdriver_binary, "--version").strip()
881 except (subprocess.CalledProcessError, OSError) as e:
882 self.logger.warning(f"Failed to call {webdriver_binary}: {e}")
883 return None
884 m = re.match(r"ChromeDriver ([0-9][0-9.]*)", version_string)
885 if not m:
886 self.logger.warning(f"Failed to extract version from: {version_string}")
887 return None
888 return m.group(1)
889
890
891 class Chromium(ChromeChromiumBase):
892 """Chromium-specific interface.
893
894 Includes browser binary installation and detection.
895 Webdriver installation and wptrunner setup shared in base class with Chrome
896
897 For a detailed description on the installation and detection of these browser components,
898 see https://web-platform-tests.org/running-tests/chrome-chromium-installation-detection.html
899 """
900 product = "chromium"
901
902 @property
903 def _chromium_package_name(self):
904 return f"chrome-{self.platform.lower()}"
905
906 def _get_existing_browser_revision(self, venv_path, channel):
907 revision = None
908 try:
909 # A file referencing the revision number is saved with the binary.
910 # Check if this revision number exists and use it if it does.
911 path = os.path.join(self._get_browser_binary_dir(None, channel), "revision")
912 with open(path) as f:
913 revision = f.read().strip()
914 except FileNotFoundError:
915 # If there is no information about the revision downloaded,
916 # use the pinned revision.
917 revision = self._get_pinned_chromium_revision()
918 return revision
919
920 def _find_binary_in_directory(self, directory):
921 """Search for Chromium browser binary in a given directory."""
922 if uname[0] == "Darwin":
923 return which("Chromium", path=os.path.join(directory,
924 self._chromium_package_name,
925 "Chromium.app",
926 "Contents",
927 "MacOS"))
928 # which will add .exe on Windows automatically.
929 return which("chrome", path=os.path.join(directory, self._chromium_package_name))
930
931 def _get_webdriver_url(self, version, revision=None):
932 """Get Chromium Snapshots url to download Chromium ChromeDriver."""
933 filename = f"chromedriver_{self._chromedriver_platform_string}.zip"
934
935 # Make sure we use the same revision in an invocation.
936 # If we have a url that was last used successfully during this run,
937 # that url takes priority over trying to form another.
938 if hasattr(self, "last_revision_used") and self.last_revision_used is not None:
939 return self._build_snapshots_url(self.last_revision_used, filename)
940 if revision is None:
941 revision = self._get_chromium_revision(filename, version)
942 elif revision == "latest":
943 revision = self._get_latest_chromium_revision()
944 elif revision == "pinned":
945 revision = self._get_pinned_chromium_revision()
946
947 return self._build_snapshots_url(revision, filename)
948
949 def download(self, dest=None, channel=None, rename=None, version=None, revision=None):
950 dest = self._get_browser_download_dir(dest, channel)
951
952 filename = f"{self._chromium_package_name}.zip"
953
954 if revision is None:
955 revision = self._get_chromium_revision(filename, version)
956 elif revision == "latest":
957 revision = self._get_latest_chromium_revision()
958 elif revision == "pinned":
959 revision = self._get_pinned_chromium_revision()
960
961 url = self._build_snapshots_url(revision, filename)
962 self.logger.info(f"Downloading Chromium from {url}")
963 resp = get(url)
964 installer_path = os.path.join(dest, filename)
965 with open(installer_path, "wb") as f:
966 f.write(resp.content)
967
968 # Revision successfully used. Keep this revision if another component install is needed.
969 self.last_revision_used = revision
970 with open(os.path.join(dest, "revision"), "w") as f:
971 f.write(revision)
972 return installer_path
973
974 def find_binary(self, venv_path=None, channel=None):
975 return self._find_binary_in_directory(self._get_browser_binary_dir(venv_path, channel))
976
977 def install(self, dest=None, channel=None, version=None, revision=None):
978 dest = self._get_browser_binary_dir(dest, channel)
979 installer_path = self.download(dest, channel, version=version, revision=revision)
980 with open(installer_path, "rb") as f:
981 unzip(f, dest)
982 os.remove(installer_path)
983 return self._find_binary_in_directory(dest)
984
985 def install_webdriver(self, dest=None, channel=None, browser_binary=None, revision=None):
986 if dest is None:
987 dest = os.pwd
988
989 if revision is None:
990 # If a revision was not given, we will need to detect the browser version.
991 # The ChromeDriver that is installed will match this version.
992 revision = self._get_existing_browser_revision(dest, channel)
993
994 chromedriver_path = self.install_webdriver_by_version(None, dest, revision)
995
996 return chromedriver_path
997
998 def webdriver_supports_browser(self, webdriver_binary, browser_binary, browser_channel=None):
999 """Check that the browser binary and ChromeDriver versions are a valid match."""
1000 browser_version = self.version(browser_binary)
1001 chromedriver_version = self.webdriver_version(webdriver_binary)
1002
1003 if not chromedriver_version:
1004 self.logger.warning("Unable to get version for ChromeDriver "
1005 f"{webdriver_binary}, rejecting it")
1006 return False
1007
1008 if not browser_version:
1009 # If we can't get the browser version,
1010 # we just have to assume the ChromeDriver is good.
1011 return True
1012
1013 # Because Chromium and its ChromeDriver should be pulled from the
1014 # same revision number, their version numbers should match exactly.
1015 if browser_version == chromedriver_version:
1016 self.logger.debug("Browser and ChromeDriver versions match.")
1017 return True
1018 self.logger.warning(f"ChromeDriver version {chromedriver_version} does not match "
1019 f"Chromium version {browser_version}.")
1020 return False
1021
1022
1023 class DownloadNotFoundError(Exception):
1024 """Raised when a download is not found for browser/webdriver installation."""
1025 pass
1026
1027
1028 class Chrome(ChromeChromiumBase):
1029 """Chrome-specific interface.
1030
1031 Includes browser binary installation and detection.
1032 Webdriver installation and wptrunner setup shared in base class with Chromium.
1033
1034 For a detailed description on the installation and detection of these browser components,
1035 see https://web-platform-tests.org/running-tests/chrome-chromium-installation-detection.html
1036 """
1037
1038 product = "chrome"
1039
1040 @property
1041 def _chrome_platform_string(self):
1042 """A string that represents the platform-based suffix
1043 of the Chrome for Testing downloads.
1044 """
1045 if self.platform in ("Linux", "Win"):
1046 bits = "64" if uname.machine == "x86_64" else "32"
1047 elif self.platform == "Mac":
1048 bits = "-arm64" if uname.machine == "arm64" else "-x64"
1049 else:
1050 bits = ""
1051 return f"{self.platform.lower()}{bits}"
1052
1053 @property
1054 def _chrome_package_name(self):
1055 return f"chrome-{self._chrome_platform_string}"
1056
1057 def _get_build_version(self, version):
1058 """Convert a Chrome/ChromeDriver version into MAJOR.MINOR.BUILD format."""
1059 version_parts = version.split(".")
1060 if len(version_parts) < 3:
1061 self.logger.info(f"Version {version} could not be formatted for build matching.")
1062 return None
1063 return ".".join(version_parts[0:3])
1064
1065 def _get_webdriver_url(self, version, channel):
1066 """Get a ChromeDriver URL to download a version of ChromeDriver that matches
1067 the browser binary version.
1068
1069 Raises: ValueError if the given version string could not be formatted.
1070
1071 Returns: A ChromeDriver download URL that matches the given Chrome version.
1072 """
1073 # Remove version suffix if it exists.
1074 if version:
1075 version = self._remove_version_suffix(version)
1076
1077 formatted_version = self._get_build_version(version)
1078 if formatted_version is None:
1079 raise ValueError(f"Unknown version format: {version}")
1080 major_version = version.split(".")[0]
1081
1082 # Chrome for Testing only has ChromeDriver downloads available for Chrome 115+.
1083 # If we are matching an older version of Chrome, use the old ChromeDriver source.
1084 if int(major_version) < 115:
1085 return self._get_old_webdriver_url(formatted_version)
1086
1087 # Check if a file exists containing the matching ChromeDriver version download URL.
1088 # This is generated when installing Chrome for Testing using the install command.
1089 download_url_reference_file = os.path.join(
1090 self._get_browser_binary_dir(None, channel), CHROMEDRIVER_SAVED_DOWNLOAD_FILE)
1091 if os.path.isfile(download_url_reference_file):
1092 self.logger.info("Download info for matching ChromeDriver version found.")
1093 with open(download_url_reference_file, "r") as f:
1094 return f.read()
1095
1096 # If no ChromeDriver download URL reference file exists,
1097 # try to find a download URL based on the build version.
1098 self.logger.info(f"Searching for ChromeDriver downloads for version {version}.")
1099 download_url = self._get_webdriver_url_by_build(formatted_version)
1100 if download_url is None:
1101 milestone = version.split('.')[0]
1102 self.logger.info(f'No ChromeDriver download found for build {formatted_version}. '
1103 f'Finding latest available download for milestone {milestone}')
1104 download_url = self._get_webdriver_url_by_milestone(milestone)
1105 return download_url
1106
1107 def _get_old_webdriver_url(self, version):
1108 """Find a ChromeDriver download URL for Chrome version <= 114
1109
1110 Raises: DownloadNotFoundError if no ChromeDriver download URL is found
1111 to match the given Chrome binary.
1112
1113 Returns: A ChromeDriver download URL that matches the given Chrome version.
1114 """
1115 latest_url = ("https://chromedriver.storage.googleapis.com/LATEST_RELEASE_"
1116 f"{version}")
1117 try:
1118 latest = get(latest_url).text.strip()
1119 except requests.RequestException as e:
1120 raise DownloadNotFoundError("No matching ChromeDriver download"
1121 f" found for version {version}.", e)
1122
1123 filename = f"chromedriver_{self._chromedriver_platform_string}.zip"
1124 return f"https://chromedriver.storage.googleapis.com/{latest}/{filename}"
1125
1126 def _get_webdriver_url_by_build(self, version):
1127 """Find a ChromeDriver download URL based on a MAJOR.MINOR.BUILD version.
1128
1129 Raises: RequestException if a bad responses is received from
1130 Chrome for Testing sources.
1131
1132 Returns: Download URL string or None if no matching build is found.
1133 """
1134 try:
1135 # Get a list of builds with download URLs from Chrome for Testing.
1136 resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}"
1137 "latest-patch-versions-per-build-with-downloads.json")
1138 except requests.RequestException as e:
1139 raise requests.RequestException(
1140 "Chrome for Testing versions not found", e)
1141 builds_json = resp.json()
1142 builds_dict = builds_json["builds"]
1143 if version not in builds_dict:
1144 self.logger.info(f"No builds found for version {version}.")
1145 return None
1146 download_info = builds_dict[version]["downloads"]
1147 if "chromedriver" not in download_info:
1148 self.logger.info(f"No ChromeDriver download found for build {version}")
1149 return None
1150 downloads_for_platform = [d for d in download_info["chromedriver"]
1151 if d["platform"] == self._chrome_platform_string]
1152 if len(downloads_for_platform) == 0:
1153 self.logger.info(f"No ChromeDriver download found for build {version}"
1154 f"of platform {self.platform}")
1155 return None
1156 return downloads_for_platform[0]["url"]
1157
1158 def _get_webdriver_url_by_milestone(self, milestone):
1159 """Find a ChromeDriver download URL that is the latest available
1160 for a Chrome milestone.
1161
1162 Raises: RequestException if a bad responses is received from
1163 Chrome for Testing sources.
1164
1165 Returns: Download URL string or None if no matching milestone is found.
1166 """
1167
1168 try:
1169 # Get a list of builds with download URLs from Chrome for Testing.
1170 resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}"
1171 "latest-versions-per-milestone.json")
1172 except requests.RequestException as e:
1173 raise requests.RequestException(
1174 "Chrome for Testing versions not found", e)
1175 milestones_json = resp.json()
1176 milestones_dict = milestones_json["milestones"]
1177 if milestone not in milestones_dict:
1178 self.logger.info(f"No latest version found for milestone {milestone}.")
1179 return None
1180 version_available = self._get_build_version(
1181 milestones_dict[milestone]["version"])
1182
1183 return self._get_webdriver_url_by_build(version_available)
1184
1185 def _get_download_urls_by_version(self, version):
1186 """Find Chrome for Testing and ChromeDriver download URLs matching a specific version.
1187
1188 Raises: DownloadNotFoundError if no download is found for the given version or platform.
1189 RequestException if a bad responses is received from
1190 Chrome for Testing sources.
1191
1192 Returns: Both binary downloads for Chrome and ChromeDriver.
1193 """
1194 try:
1195 # Get a list of versions with download URLs from Chrome for Testing.
1196 resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}"
1197 "known-good-versions-with-downloads.json")
1198 except requests.RequestException as e:
1199 raise requests.RequestException(
1200 "Chrome for Testing versions not found", e)
1201 versions_json = resp.json()
1202 versions_list = versions_json["versions"]
1203 # Attempt to find a version match in the list of available downloads.
1204 matching_versions = [v for v in versions_list if v["version"] == version]
1205 if len(matching_versions) == 0:
1206 raise DownloadNotFoundError(f"No Chrome for Testing download found for {version}")
1207
1208 download_info = matching_versions[0]["downloads"]
1209 # Find the download url that matches the current platform.
1210 browser_download_urls = [d for d in download_info["chrome"]
1211 if d["platform"] == self._chrome_platform_string]
1212 if len(browser_download_urls) == 0:
1213 raise DownloadNotFoundError(
1214 f"No Chrome for Testing download found for {self.platform} of version {version}")
1215 browser_download_url = browser_download_urls[0]["url"]
1216
1217 # Get the corresponding ChromeDriver download URL for later use.
1218 chromedriver_download_urls = [d for d in download_info["chromedriver"]
1219 if d["platform"] == self._chrome_platform_string]
1220 if len(chromedriver_download_urls) == 0:
1221 # Some older versions of Chrome for Testing
1222 # do not have a matching ChromeDriver download.
1223 raise DownloadNotFoundError(
1224 f"ChromeDriver download does not exist for version {version}")
1225 chromedriver_url = chromedriver_download_urls[0]["url"]
1226
1227 return browser_download_url, chromedriver_url
1228
1229 def _get_download_urls_by_channel(self, channel):
1230 """Find Chrome for Testing and ChromeDriver download URLs matching the given channel.
1231
1232 Raises: DownloadNotFoundError if no download is found for the given channel or platform.
1233 RequestException if a bad responses is received from Chrome for Testing sources.
1234
1235 Returns: Both binary downloads for Chrome and ChromeDriver.
1236 """
1237 try:
1238 resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}"
1239 "last-known-good-versions-with-downloads.json")
1240 except requests.RequestException as e:
1241 raise requests.RequestException(
1242 "Chrome for Testing versions not found", e)
1243 channels_json = resp.json()
1244 download_info = channels_json["channels"][channel.capitalize()]["downloads"]["chrome"]
1245
1246 # Find the download URL that matches the current platform.
1247 matching_download_urls = [d for d in download_info
1248 if d["platform"] == self._chrome_platform_string]
1249 if len(matching_download_urls) == 0:
1250 raise DownloadNotFoundError("No matching download for platform "
1251 f"{self.platform} of channel \"{channel}\".")
1252
1253 browser_download_url = matching_download_urls[0]["url"]
1254
1255 # Get the corresponding ChromeDriver download URL for later use.
1256 chromedriver_download_info = (
1257 channels_json["channels"][channel.capitalize()]["downloads"]["chromedriver"])
1258
1259 matching_chromedriver_urls = [d for d in chromedriver_download_info
1260 if d["platform"] == self._chrome_platform_string]
1261 if len(matching_chromedriver_urls) == 0:
1262 raise DownloadNotFoundError(
1263 f"No ChromeDriver download found in Chrome for Testing {channel}.")
1264 chromedriver_url = matching_chromedriver_urls[0]["url"]
1265
1266 return browser_download_url, chromedriver_url
1267
1268 def _save_chromedriver_download_info(self, dest, url):
1269 """Save the download URL of a ChromeDriver binary that matches the browser.
1270 This will allow for easy version matching, even in separate CLI invocations.
1271 """
1272 with open(os.path.join(dest, CHROMEDRIVER_SAVED_DOWNLOAD_FILE), "w") as f:
1273 f.write(url)
1274
1275 def download(self, dest=None, channel="canary", rename=None, version=None):
1276 """Download Chrome for Testing. For more information,
1277 see: https://github.com/GoogleChromeLabs/chrome-for-testing
1278 """
1279 dest = self._get_browser_binary_dir(None, channel)
1280 filename = f"{self._chrome_package_name}.zip"
1281
1282 # If a version has been supplied, try to find a download to match that version.
1283 # Otherwise, find a download for the specified channel.
1284 if version is not None:
1285 download_url, chromedriver_url = self._get_download_urls_by_version(version)
1286 else:
1287 download_url, chromedriver_url = self._get_download_urls_by_channel(channel)
1288
1289 self.logger.info(f"Downloading Chrome for Testing from {download_url}")
1290 resp = get(download_url)
1291 installer_path = os.path.join(dest, filename)
1292 with open(installer_path, "wb") as f:
1293 f.write(resp.content)
1294
1295 # Save the ChromeDriver download URL for use if a matching ChromeDriver
1296 # needs to be downloaded in a separate install invocation.
1297 self._save_chromedriver_download_info(dest, chromedriver_url)
1298
1299 return installer_path
1300
1301 def _find_binary_in_directory(self, directory):
1302 """Search for Chrome for Testing browser binary in a given directory."""
1303 if uname[0] == "Darwin":
1304 return which(
1305 "Google Chrome for Testing",
1306 path=os.path.join(directory,
1307 self._chrome_package_name,
1308 "Google Chrome for Testing.app",
1309 "Contents",
1310 "MacOS"))
1311 # "which" will add .exe on Windows automatically.
1312 return which("chrome", path=os.path.join(directory, self._chrome_package_name))
1313
1314 def find_binary(self, venv_path=None, channel=None):
1315 # Check for binary in venv first.
1316 path = self._find_binary_in_directory(self._get_browser_binary_dir(venv_path, channel))
1317 if path is not None:
1318 return path
1319
1320 if uname[0] == "Linux":
1321 name = "google-chrome"
1322 if channel == "stable":
1323 name += "-stable"
1324 elif channel == "beta":
1325 name += "-beta"
1326 elif channel == "dev":
1327 name += "-unstable"
1328 # No Canary on Linux.
1329 return which(name)
1330 if uname[0] == "Darwin":
1331 suffix = ""
1332 if channel in ("beta", "dev", "canary"):
1333 suffix = " " + channel.capitalize()
1334 return f"/Applications/Google Chrome{suffix}.app/Contents/MacOS/Google Chrome{suffix}"
1335 if uname[0] == "Windows":
1336 name = "Chrome"
1337 if channel == "beta":
1338 name += " Beta"
1339 elif channel == "dev":
1340 name += " Dev"
1341 path = os.path.expandvars(fr"$PROGRAMFILES\Google\{name}\Application\chrome.exe")
1342 if channel == "canary":
1343 path = os.path.expandvars(r"$LOCALAPPDATA\Google\Chrome SxS\Application\chrome.exe")
1344 return path
1345 self.logger.warning("Unable to find the browser binary.")
1346 return None
1347
1348 def install(self, dest=None, channel=None, version=None):
1349 dest = self._get_browser_binary_dir(dest, channel)
1350 installer_path = self.download(dest=dest, channel=channel, version=version)
1351 with open(installer_path, "rb") as f:
1352 unzip(f, dest)
1353 os.remove(installer_path)
1354 return self._find_binary_in_directory(dest)
1355
1356 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
1357 if dest is None:
1358 dest = os.pwd
1359
1360 # Detect the browser version.
1361 # The ChromeDriver that is installed will match this version.
1362 if browser_binary is None:
1363 # If a browser binary path was not given, detect a valid path.
1364 browser_binary = self.find_binary(channel=channel)
1365 # We need a browser to version match, so if a browser binary path
1366 # was not given and cannot be detected, raise an error.
1367 if browser_binary is None:
1368 raise FileNotFoundError("No browser binary detected. "
1369 "Cannot install ChromeDriver without a browser version.")
1370
1371 version = self.version(browser_binary)
1372 if version is None:
1373 # Check if the user has given a Chromium binary.
1374 chromium = Chromium(self.logger)
1375 if chromium.version(browser_binary):
1376 raise ValueError("Provided binary is a Chromium binary and should be run using "
1377 "\"./wpt run chromium\" or similar.")
1378 raise ValueError(f"Unable to detect browser version from binary at {browser_binary}. "
1379 " Cannot install ChromeDriver without a valid version to match.")
1380
1381 chromedriver_path = self.install_webdriver_by_version(version, dest, channel)
1382
1383 return chromedriver_path
1384
1385 def install_webdriver_by_version(self, version, dest, channel):
1386 # Set the destination to a specific "chrome" folder to not overwrite or remove
1387 # ChromeDriver versions used for Chromium.
1388 dest = os.path.join(dest, self.product)
1389 self._remove_existing_chromedriver_binary(dest)
1390
1391 url = self._get_webdriver_url(version, channel)
1392 if url is None:
1393 raise DownloadNotFoundError(
1394 f"No ChromeDriver download found to match browser version {version}")
1395 self.logger.info(f"Downloading ChromeDriver from {url}")
1396 unzip(get(url).raw, dest)
1397
1398 chromedriver_dir = os.path.join(
1399 dest, f"chromedriver-{self._chrome_platform_string}")
1400 chromedriver_path = which("chromedriver", path=chromedriver_dir)
1401
1402 if chromedriver_path is not None:
1403 shutil.move(chromedriver_path, dest)
1404 rmtree(chromedriver_dir)
1405
1406 chromedriver_path = which("chromedriver", path=dest)
1407 if chromedriver_path is None:
1408 raise FileNotFoundError("ChromeDriver could not be detected after installation.")
1409 return chromedriver_path
1410
1411 def webdriver_supports_browser(self, webdriver_binary, browser_binary, browser_channel):
1412 """Check that the browser binary and ChromeDriver versions are a valid match."""
1413 browser_version = self.version(browser_binary)
1414 chromedriver_version = self.webdriver_version(webdriver_binary)
1415
1416 if not chromedriver_version:
1417 self.logger.warning("Unable to get version for ChromeDriver "
1418 f"{webdriver_binary}, rejecting it")
1419 return False
1420
1421 # TODO(DanielRyanSmith): Determine if this version logic fail case is
1422 # still necessary and remove it if it isn't.
1423 if not browser_version:
1424 # If we can't get the browser version,
1425 # we just have to assume the ChromeDriver is good.
1426 return True
1427
1428 # Format versions for comparison.
1429 browser_version = self._get_build_version(browser_version)
1430 chromedriver_version = self._get_build_version(chromedriver_version)
1431
1432 # Chrome and ChromeDriver versions should match on the same MAJOR.MINOR.BUILD version.
1433 if browser_version is not None and browser_version != chromedriver_version:
1434 # Consider the same milestone as matching.
1435 # Workaround for https://github.com/web-platform-tests/wpt/issues/42545
1436 # TODO(DanielRyanSmith): Remove this logic when browser binary is
1437 # downloaded from Chrome for Testing in CI runs.
1438 browser_milestone = browser_version.split('.')[0]
1439 chromedriver_milestone = chromedriver_version.split('.')[0]
1440 if browser_milestone != chromedriver_milestone:
1441 self.logger.warning(
1442 f"ChromeDriver {chromedriver_version} does not match Chrome {browser_version}")
1443 return False
1444 return True
1445
1446 def version(self, binary=None, webdriver_binary=None):
1447 """Get version string from browser binary."""
1448 if not binary:
1449 self.logger.warning("No browser binary provided.")
1450 return None
1451 if uname[0] == "Windows":
1452 return _get_fileversion(binary, self.logger)
1453
1454 try:
1455 version_string = call(binary, "--version").strip()
1456 except (subprocess.CalledProcessError, OSError) as e:
1457 self.logger.warning(f"Failed to call {binary}: {e}")
1458 return None
1459 m = re.match(r"(?:Google Chrome for Testing|Google Chrome) (.*)", version_string)
1460 if not m:
1461 self.logger.warning(f"Failed to extract version from: {version_string}")
1462 return None
1463 return m.group(1)
1464
1465 def webdriver_version(self, webdriver_binary):
1466 """Get version string from ChromeDriver binary."""
1467 if webdriver_binary is None:
1468 self.logger.warning("No valid webdriver supplied to detect version.")
1469 return None
1470
1471 try:
1472 version_string = call(webdriver_binary, "--version").strip()
1473 except (subprocess.CalledProcessError, OSError) as e:
1474 self.logger.warning(f"Failed to call {webdriver_binary}: {e}")
1475 return None
1476 m = re.match(r"ChromeDriver ([0-9][0-9.]*)", version_string)
1477 if not m:
1478 self.logger.warning(f"Failed to extract version from: {version_string}")
1479 return None
1480 return m.group(1)
1481
1482
1483 class HeadlessShell(ChromeChromiumBase):
1484 """Interface for the Chromium headless shell [0].
1485
1486 [0]: https://chromium.googlesource.com/chromium/src/+/HEAD/headless/README.md
1487 """
1488
1489 product = "headless_shell"
1490 requirements = None
1491
1492 def download(self, dest=None, channel=None, rename=None):
1493 # TODO(crbug.com/344669542): Download binaries via CfT.
1494 raise NotImplementedError
1495
1496 def install(self, dest=None, channel=None):
1497 raise NotImplementedError
1498
1499 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
1500 raise NotImplementedError
1501
1502 def find_binary(self, venv_path=None, channel=None):
1503 # `which()` adds `.exe` extension automatically for Windows.
1504 # Chromium builds an executable named `headless_shell`, whereas CfT
1505 # ships under the name `chrome-headless-shell`.
1506 return which("headless_shell") or which("chrome-headless-shell")
1507
1508 def version(self, binary=None, webdriver_binary=None):
1509 # TODO(crbug.com/327767951): Support `headless_shell --version`.
1510 return "N/A"
1511
1512
1513 class ChromeAndroidBase(Browser):
1514 """A base class for ChromeAndroid and AndroidWebView.
1515
1516 On Android, WebView is based on Chromium open source project, and on some
1517 versions of Android we share the library with Chrome. Therefore, we have
1518 a very similar WPT runner implementation.
1519 Includes webdriver installation.
1520 """
1521 __metaclass__ = ABCMeta # This is an abstract class.
1522
1523 def __init__(self, logger):
1524 super().__init__(logger)
1525 self.device_serial = None
1526 self.adb_binary = "adb"
1527
1528 def download(self, dest=None, channel=None, rename=None):
1529 raise NotImplementedError
1530
1531 def install(self, dest=None, channel=None):
1532 raise NotImplementedError
1533
1534 @abstractmethod
1535 def find_binary(self, venv_path=None, channel=None):
1536 raise NotImplementedError
1537
1538 def find_webdriver(self, venv_path=None, channel=None):
1539 return which("chromedriver")
1540
1541 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
1542 if browser_binary is None:
1543 browser_binary = self.find_binary(channel)
1544 chrome = Chrome(self.logger)
1545 return chrome.install_webdriver_by_version(self.version(browser_binary), dest, channel)
1546
1547 def version(self, binary=None, webdriver_binary=None):
1548 if not binary:
1549 self.logger.warning("No package name provided.")
1550 return None
1551
1552 command = [self.adb_binary]
1553 if self.device_serial:
1554 # Assume we have same version of browser on all devices
1555 command.extend(['-s', self.device_serial[0]])
1556 command.extend(['shell', 'dumpsys', 'package', binary])
1557 try:
1558 output = call(*command)
1559 except (subprocess.CalledProcessError, OSError):
1560 self.logger.warning("Failed to call %s" % " ".join(command))
1561 return None
1562 match = re.search(r'versionName=(.*)', output)
1563 if not match:
1564 self.logger.warning("Failed to find versionName")
1565 return None
1566 return match.group(1)
1567
1568
1569 class ChromeAndroid(ChromeAndroidBase):
1570 """Chrome-specific interface for Android.
1571 """
1572
1573 product = "chrome_android"
1574 requirements = "requirements_chromium.txt"
1575
1576 def find_binary(self, venv_path=None, channel=None):
1577 if channel in ("beta", "dev", "canary"):
1578 return "com.chrome." + channel
1579 return "com.android.chrome"
1580
1581
1582 class AndroidWebview(ChromeAndroidBase):
1583 """Webview-specific interface for Android.
1584
1585 Design doc:
1586 https://docs.google.com/document/d/19cGz31lzCBdpbtSC92svXlhlhn68hrsVwSB7cfZt54o/view
1587 """
1588
1589 product = "android_webview"
1590 requirements = "requirements_chromium.txt"
1591
1592 def find_binary(self, venv_path=None, channel=None):
1593 # Just get the current package name of the WebView provider.
1594 # For WebView, it is not trivial to change the WebView provider, so
1595 # we will just grab whatever is available.
1596 # https://chromium.googlesource.com/chromium/src/+/HEAD/android_webview/docs/channels.md
1597 command = [self.adb_binary]
1598 if self.device_serial:
1599 command.extend(['-s', self.device_serial[0]])
1600 command.extend(['shell', 'dumpsys', 'webviewupdate'])
1601 try:
1602 output = call(*command)
1603 except (subprocess.CalledProcessError, OSError):
1604 self.logger.warning("Failed to call %s" % " ".join(command))
1605 return None
1606 m = re.search(r'^\s*Current WebView package \(name, version\): \((.*), ([0-9.]*)\)$',
1607 output, re.M)
1608 if m is None:
1609 self.logger.warning("Unable to find current WebView package in dumpsys output")
1610 return None
1611 self.logger.warning("Final package name: " + m.group(1))
1612 return m.group(1)
1613
1614
1615 class ChromeiOS(Browser):
1616 """Chrome-specific interface for iOS.
1617 """
1618
1619 product = "chrome_ios"
1620 requirements = None
1621
1622 def download(self, dest=None, channel=None, rename=None):
1623 raise NotImplementedError
1624
1625 def install(self, dest=None, channel=None):
1626 raise NotImplementedError
1627
1628 def find_binary(self, venv_path=None, channel=None):
1629 raise NotImplementedError
1630
1631 def find_webdriver(self, venv_path=None, channel=None):
1632 raise NotImplementedError
1633
1634 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
1635 raise NotImplementedError
1636
1637 def version(self, binary=None, webdriver_binary=None):
1638 if webdriver_binary is None:
1639 self.logger.warning(
1640 "Cannot find ChromeiOS version without CWTChromeDriver")
1641 return None
1642 # Use `chrome iOS driver --version` to get the version. Example output:
1643 # "125.0.6378.0"
1644 try:
1645 version_string = call(webdriver_binary, "--version").strip()
1646 except subprocess.CalledProcessError as e:
1647 self.logger.warning(f"Failed to call {webdriver_binary}: {e}")
1648 return None
1649 m = re.match(r"[\d][\d\.]*", version_string)
1650 if not m:
1651 self.logger.warning(
1652 f"Failed to extract version from: {version_string}")
1653 return None
1654 return m.group(0)
1655
1656
1657 class Opera(Browser):
1658 """Opera-specific interface.
1659
1660 Includes webdriver installation, and wptrunner setup methods.
1661 """
1662
1663 product = "opera"
1664 requirements = "requirements_opera.txt"
1665
1666 @property
1667 def binary(self):
1668 if uname[0] == "Linux":
1669 return "/usr/bin/opera"
1670 # TODO Windows, Mac?
1671 self.logger.warning("Unable to find the browser binary.")
1672 return None
1673
1674 def download(self, dest=None, channel=None, rename=None):
1675 raise NotImplementedError
1676
1677 def install(self, dest=None, channel=None):
1678 raise NotImplementedError
1679
1680 def platform_string(self):
1681 platform = {
1682 "Linux": "linux",
1683 "Windows": "win",
1684 "Darwin": "mac"
1685 }.get(uname[0])
1686
1687 if platform is None:
1688 raise ValueError("Unable to construct a valid Opera package name for current platform")
1689
1690 if platform == "linux":
1691 bits = "64" if uname[4] == "x86_64" else "32"
1692 elif platform == "mac":
1693 bits = "64"
1694 elif platform == "win":
1695 bits = "32"
1696
1697 return "%s%s" % (platform, bits)
1698
1699 def find_binary(self, venv_path=None, channel=None):
1700 raise NotImplementedError
1701
1702 def find_webdriver(self, venv_path=None, channel=None):
1703 return which("operadriver")
1704
1705 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
1706 if dest is None:
1707 dest = os.pwd
1708 latest = get("https://api.github.com/repos/operasoftware/operachromiumdriver/releases/latest").json()["tag_name"]
1709 url = "https://github.com/operasoftware/operachromiumdriver/releases/download/%s/operadriver_%s.zip" % (latest,
1710 self.platform_string())
1711 unzip(get(url).raw, dest)
1712
1713 operadriver_dir = os.path.join(dest, "operadriver_%s" % self.platform_string())
1714 shutil.move(os.path.join(operadriver_dir, "operadriver"), dest)
1715 rmtree(operadriver_dir)
1716
1717 path = which("operadriver")
1718 st = os.stat(path)
1719 os.chmod(path, st.st_mode | stat.S_IEXEC)
1720 return path
1721
1722 def version(self, binary=None, webdriver_binary=None):
1723 """Retrieve the release version of the installed browser."""
1724 binary = binary or self.binary
1725 try:
1726 output = call(binary, "--version")
1727 except subprocess.CalledProcessError:
1728 self.logger.warning("Failed to call %s" % binary)
1729 return None
1730 m = re.search(r"[0-9\.]+( [a-z]+)?$", output.strip())
1731 if m:
1732 return m.group(0)
1733
1734
1735 class Edge(Browser):
1736 """Microsoft Edge Chromium Browser class."""
1737
1738 product = "edge"
1739 requirements = "requirements_chromium.txt"
1740 platform = {
1741 "Linux": "linux",
1742 "Windows": "win",
1743 "Darwin": "macos"
1744 }.get(uname[0])
1745
1746 def _get_build_version(self, version):
1747 """Convert a Edge/MSEdgeDriver version into MAJOR.MINOR.BUILD format."""
1748 version_parts = version.split(".")
1749 if len(version_parts) < 3:
1750 self.logger.info(f"Version {version} could not be formatted for build matching.")
1751 return None
1752 return ".".join(version_parts[0:3])
1753
1754 def _remove_existing_edgedriver_binary(self, path):
1755 """Remove an existing MSEdgeDriver for this product if it exists
1756 in the virtual environment.
1757 """
1758 # There may be an existing MSEdgeDriver binary from a previous install.
1759 # To provide a clean install experience, remove the old binary - this
1760 # avoids tricky issues like unzipping over a read-only file.
1761 existing_edgedriver_path = which("MSEdgeDriver", path=path)
1762 if existing_edgedriver_path:
1763 self.logger.info(f"Removing existing MSEdgeDriver binary: {existing_edgedriver_path}")
1764 os.chmod(existing_edgedriver_path, stat.S_IWUSR)
1765 os.remove(existing_edgedriver_path)
1766 existing_driver_notes_path = os.path.join(path, "Driver_notes")
1767 if os.path.isdir(existing_driver_notes_path):
1768 self.logger.info(f"Removing existing MSEdgeDriver binary: {existing_driver_notes_path}")
1769 rmtree(existing_driver_notes_path)
1770
1771 def download(self, dest=None, channel=None, rename=None):
1772 raise NotImplementedError
1773
1774 def install_mojojs(self, dest, browser_binary):
1775 # MojoJS is platform agnostic, but the version number must be an
1776 # exact match of the Edge version to be compatible.
1777 edge_version = self.version(binary=browser_binary)
1778 if not edge_version:
1779 return None
1780
1781 try:
1782 # MojoJS version url must match the browser binary version exactly.
1783 url = ("https://msedgedriver.azureedge.net/wpt-mojom/"
1784 f"{edge_version}/linux64/mojojs.zip")
1785 # Check the status without downloading the content (this is a
1786 # streaming request).
1787 get(url)
1788 except requests.RequestException:
1789 self.logger.error("A valid MojoJS version cannot be found "
1790 f"for browser binary version {edge_version}.")
1791 return None
1792
1793 extracted = os.path.join(dest, "mojojs", "gen")
1794 last_url_file = os.path.join(extracted, "DOWNLOADED_FROM")
1795 if os.path.exists(last_url_file):
1796 with open(last_url_file, "rt") as f:
1797 last_url = f.read().strip()
1798 if last_url == url:
1799 self.logger.info("Mojo bindings already up to date")
1800 return extracted
1801 rmtree(extracted)
1802
1803 try:
1804 self.logger.info(f"Downloading Mojo bindings from {url}")
1805 unzip(get(url).raw, os.path.join(dest, "mojojs"))
1806 with open(last_url_file, "wt") as f:
1807 f.write(url)
1808 return extracted
1809 except Exception as e:
1810 self.logger.error(f"Cannot enable MojoJS: {e}")
1811 return None
1812
1813 def find_binary(self, venv_path=None, channel=None):
1814 # TODO: Check for binary in virtual environment first
1815 if self.platform == "linux":
1816 name = "microsoft-edge"
1817 if channel == "stable":
1818 name += "-stable"
1819 elif channel == "beta":
1820 name += "-beta"
1821 elif channel == "dev":
1822 name += "-dev"
1823 # No Canary on Linux.
1824 return which(name)
1825 if self.platform == "macos":
1826 suffix = ""
1827 if channel in ("beta", "dev", "canary"):
1828 suffix = " " + channel.capitalize()
1829 return f"/Applications/Microsoft Edge{suffix}.app/Contents/MacOS/Microsoft Edge{suffix}"
1830 if self.platform == "win":
1831 suffix = ""
1832 if channel in ("beta", "dev"):
1833 suffix = " " + channel.capitalize()
1834 winpaths = [os.path.expandvars(fr"%PROGRAMFILES%\Microsoft\Edge{suffix}\Application"),
1835 os.path.expandvars(fr"%programfiles(x86)%\Microsoft\Edge{suffix}\Application")]
1836 path = which("msedge.exe", path=os.pathsep.join(winpaths))
1837 if channel == "canary":
1838 path = os.path.expandvars(r"%LOCALAPPDATA%\Microsoft\Edge SxS\Application\msedge.exe")
1839 return path
1840 self.logger.warning("Unable to find the browser binary.")
1841 return None
1842
1843 def find_webdriver(self, venv_path=None, channel=None):
1844 return which("msedgedriver")
1845
1846 def install(self, dest=None, channel=None):
1847 raise NotImplementedError
1848
1849 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
1850 if dest is None:
1851 dest = os.pwd
1852
1853 # Detect the browser version.
1854 # The MSEdgeDriver that is installed will match this version.
1855 if browser_binary is None:
1856 # If a browser binary path was not given, detect a valid path.
1857 browser_binary = self.find_binary(channel=channel)
1858 # We need a browser to version match, so if a browser binary path
1859 # was not given and cannot be detected, raise an error.
1860 if browser_binary is None:
1861 raise FileNotFoundError("No browser binary detected. "
1862 "Cannot install MSEdgeDriver without a browser version.")
1863
1864 version = self.version(browser_binary)
1865 if version is None:
1866 raise ValueError(f"Unable to detect browser version from binary at {browser_binary}. "
1867 "Cannot install MSEdgeDriver without a valid version to match.")
1868
1869 edgedriver_path = self.install_webdriver_by_version(version, dest, channel)
1870
1871 return edgedriver_path
1872
1873 def install_webdriver_by_version(self, version, dest, channel):
1874 self._remove_existing_edgedriver_binary(dest)
1875
1876 if self.platform == "linux":
1877 bits = "linux64"
1878 elif self.platform == "macos":
1879 bits = "mac64"
1880 elif self.platform == "win":
1881 bits = "win64" if uname[4] == "x86_64" else "win32"
1882
1883 url = f"https://msedgedriver.azureedge.net/{version}/edgedriver_{bits}.zip"
1884 self.logger.info(f"Downloading MSEdgeDriver from {url}")
1885 unzip(get(url).raw, dest)
1886 edgedriver_path = which("msedgedriver", path=dest)
1887 assert edgedriver_path is not None
1888 return edgedriver_path
1889
1890 def webdriver_supports_browser(self, webdriver_binary, browser_binary, browser_channel):
1891 """Check that the browser binary and MSEdgeDriver versions are a valid match."""
1892 browser_version = self.version(browser_binary)
1893 edgedriver_version = self.webdriver_version(webdriver_binary)
1894
1895 if not edgedriver_version:
1896 self.logger.warning("Unable to get version for MSEdgeDriver "
1897 f"{webdriver_binary}, rejecting it")
1898 return False
1899
1900 if not browser_version:
1901 # If we can't get the browser version, we just have to assume the
1902 # MSEdgeDriver is good.
1903 self.logger.warning("Unable to get version for the browser "
1904 f"{browser_binary}, assuming MSEdgeDriver is good.")
1905 return True
1906
1907 # Check that the EdgeDriver version matches the Edge version.
1908 browser_version = self._get_build_version(browser_version)
1909 edgedriver_version = self._get_build_version(edgedriver_version)
1910
1911 # Edge and MSEdgeDriver versions should match on the same MAJOR.MINOR.BUILD version.
1912 if browser_version is not None and browser_version != edgedriver_version:
1913 self.logger.warning(
1914 f"MSEdgeDriver {edgedriver_version} does not match Edge {browser_version}")
1915 return False
1916 return True
1917
1918 def version(self, binary=None, webdriver_binary=None):
1919 """Get version string from browser binary."""
1920 if not binary:
1921 self.logger.warning("No browser binary provided.")
1922 return None
1923
1924 if uname[0] == "Windows":
1925 return _get_fileversion(binary, self.logger)
1926
1927 try:
1928 version_string = call(binary, "--version").strip()
1929 except (subprocess.CalledProcessError, OSError) as e:
1930 self.logger.warning(f"Failed to call {binary}: {e}")
1931 return None
1932 m = re.match(r"Microsoft Edge ([0-9][0-9.]*)", version_string)
1933 if not m:
1934 self.logger.warning(f"Failed to extract version from: {version_string}")
1935 return None
1936 return m.group(1)
1937
1938 def webdriver_version(self, webdriver_binary):
1939 """Get version string from MSEdgeDriver binary."""
1940 if webdriver_binary is None:
1941 self.logger.warning("No valid webdriver supplied to detect version.")
1942 return None
1943
1944 try:
1945 version_string = call(webdriver_binary, "--version").strip()
1946 except (subprocess.CalledProcessError, OSError) as e:
1947 self.logger.warning(f"Failed to call {webdriver_binary}: {e}")
1948 return None
1949 m = re.match(r"Microsoft Edge WebDriver ([0-9][0-9.]*)", version_string)
1950 if not m:
1951 self.logger.warning(f"Failed to extract version from: {version_string}")
1952 return None
1953 return m.group(1)
1954
1955
1956 class Safari(Browser):
1957 """Safari-specific interface.
1958
1959 Includes installation, webdriver installation, and wptrunner setup methods.
1960 """
1961
1962 product = "safari"
1963 requirements = "requirements_safari.txt"
1964
1965 def _find_downloads(self):
1966 def text_content(e, __output=None):
1967 # this doesn't use etree.tostring so that we can add spaces for p and br
1968 if __output is None:
1969 __output = []
1970
1971 if e.tag == "p":
1972 __output.append("\n\n")
1973
1974 if e.tag == "br":
1975 __output.append("\n")
1976
1977 if e.text is not None:
1978 __output.append(e.text)
1979
1980 for child in e:
1981 text_content(child, __output)
1982 if child.tail is not None:
1983 __output.append(child.tail)
1984
1985 return "".join(__output)
1986
1987 self.logger.info("Finding STP download URLs")
1988 resp = get("https://developer.apple.com/safari/download/")
1989
1990 doc = html5lib.parse(
1991 resp.content,
1992 "etree",
1993 namespaceHTMLElements=False,
1994 transport_encoding=resp.encoding,
1995 )
1996 ascii_ws = re.compile(r"[\x09\x0A\x0C\x0D\x20]+")
1997
1998 downloads = []
1999 for candidate in doc.iterfind(".//li[@class]"):
2000 class_names = set(ascii_ws.split(candidate.attrib["class"]))
2001 if {"download", "dmg", "zip"} & class_names:
2002 downloads.append(candidate)
2003
2004 # Note we use \s throughout for space as we don't care what form the whitespace takes
2005 stp_link_text = re.compile(
2006 r"^\s*Safari\s+Technology\s+Preview\s+(?:[0-9]+\s+)?for\s+macOS"
2007 )
2008 requirement = re.compile(
2009 r"""(?x) # (extended regexp syntax for comments)
2010 ^\s*Requires\s+macOS\s+ # Starting with the magic string
2011 ([0-9]+(?:\.[0-9]+)*) # A macOS version number of numbers and dots
2012 (?:\s+beta(?:\s+[0-9]+)?)? # Optionally a beta, itself optionally with a number (no dots!)
2013 (?:\s+or\s+later)? # Optionally an 'or later'
2014 \.?\s*$ # Optionally ending with a literal dot
2015 """
2016 )
2017
2018 stp_downloads = []
2019 for download in downloads:
2020 for link in download.iterfind(".//a[@href]"):
2021 if stp_link_text.search(text_content(link)):
2022 break
2023 else:
2024 self.logger.debug("non-matching anchor: " + text_content(link))
2025 else:
2026 continue
2027
2028 for el in download.iter():
2029 # avoid assuming any given element here, just assume it is a single element
2030 m = requirement.search(text_content(el))
2031 if m:
2032 version = m.group(1)
2033
2034 # This assumes the current macOS numbering, whereby X.Y is compatible
2035 # with X.(Y+1), e.g. 12.4 is compatible with 12.3, but 13.0 isn't
2036 # compatible with 12.3.
2037 if version.count(".") >= (2 if version.startswith("10.") else 1):
2038 spec = SpecifierSet(f"~={version}")
2039 else:
2040 spec = SpecifierSet(f"=={version}.*")
2041
2042 stp_downloads.append((spec, link.attrib["href"].strip()))
2043 break
2044 else:
2045 self.logger.debug(
2046 "Found a link but no requirement: " + text_content(download)
2047 )
2048
2049 if stp_downloads:
2050 self.logger.info(
2051 "Found STP URLs for macOS " +
2052 ", ".join(str(dl[0]) for dl in stp_downloads)
2053 )
2054 else:
2055 self.logger.warning("Did not find any STP URLs")
2056
2057 return stp_downloads
2058
2059 def _download_image(self, downloads, dest, system_version=None):
2060 if system_version is None:
2061 system_version, _, _ = platform.mac_ver()
2062
2063 chosen_url = None
2064 for version_spec, url in downloads:
2065 if system_version in version_spec:
2066 self.logger.debug(f"Will download Safari for {version_spec}")
2067 chosen_url = url
2068 break
2069
2070 if chosen_url is None:
2071 raise ValueError(f"no download for {system_version}")
2072
2073 self.logger.info(f"Downloading Safari from {chosen_url}")
2074 resp = get(chosen_url)
2075
2076 filename = get_download_filename(resp, "SafariTechnologyPreview.dmg")
2077 installer_path = os.path.join(dest, filename)
2078 with open(installer_path, "wb") as f:
2079 f.write(resp.content)
2080
2081 return installer_path
2082
2083 def _download_extract(self, image_path, dest, rename=None):
2084 with tempfile.TemporaryDirectory() as tmpdir:
2085 self.logger.debug(f"Mounting {image_path}")
2086 r = subprocess.run(
2087 [
2088 "hdiutil",
2089 "attach",
2090 "-readonly",
2091 "-mountpoint",
2092 tmpdir,
2093 "-nobrowse",
2094 "-verify",
2095 "-noignorebadchecksums",
2096 "-autofsck",
2097 image_path,
2098 ],
2099 encoding="utf-8",
2100 capture_output=True,
2101 check=True,
2102 )
2103
2104 mountpoint = None
2105 for line in r.stdout.splitlines():
2106 if not line.startswith("/dev/"):
2107 continue
2108
2109 _, _, mountpoint = line.split("\t", 2)
2110 if mountpoint:
2111 break
2112
2113 if mountpoint is None:
2114 raise ValueError("no volume mounted from image")
2115
2116 pkgs = [p for p in os.listdir(mountpoint) if p.endswith((".pkg", ".mpkg"))]
2117 if len(pkgs) != 1:
2118 raise ValueError(
2119 f"Expected a single .pkg/.mpkg, found {len(pkgs)}: {', '.join(pkgs)}"
2120 )
2121
2122 source_path = os.path.join(mountpoint, pkgs[0])
2123 dest_path = os.path.join(
2124 dest, (rename + get_ext(pkgs[0])) if rename is not None else pkgs[0]
2125 )
2126
2127 self.logger.debug(f"Copying {source_path} to {dest_path}")
2128 shutil.copy2(
2129 source_path,
2130 dest_path,
2131 )
2132
2133 self.logger.debug(f"Unmounting {mountpoint}")
2134 subprocess.run(
2135 ["hdiutil", "detach", mountpoint],
2136 encoding="utf-8",
2137 capture_output=True,
2138 check=True,
2139 )
2140
2141 return dest_path
2142
2143 def download(self, dest=None, channel="preview", rename=None, system_version=None):
2144 if channel != "preview":
2145 raise ValueError(f"can only install 'preview', not '{channel}'")
2146
2147 dest = self._get_browser_download_dir(dest, channel)
2148
2149 stp_downloads = self._find_downloads()
2150
2151 with tempfile.TemporaryDirectory() as tmpdir:
2152 image_path = self._download_image(stp_downloads, tmpdir, system_version)
2153 return self._download_extract(image_path, dest, rename)
2154
2155 def install(self, dest=None, channel=None):
2156 # We can't do this because stable/beta releases are system components and STP
2157 # requires admin permissions to install.
2158 raise NotImplementedError
2159
2160 def find_binary(self, venv_path=None, channel=None):
2161 raise NotImplementedError
2162
2163 def find_webdriver(self, venv_path=None, channel=None):
2164 path = None
2165 if channel == "preview":
2166 path = "/Applications/Safari Technology Preview.app/Contents/MacOS"
2167 return which("safaridriver", path=path)
2168
2169 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
2170 raise NotImplementedError
2171
2172 def version(self, binary=None, webdriver_binary=None):
2173 if webdriver_binary is None:
2174 self.logger.warning("Cannot find Safari version without safaridriver")
2175 return None
2176 # Use `safaridriver --version` to get the version. Example output:
2177 # "Included with Safari 12.1 (14607.1.11)"
2178 # "Included with Safari Technology Preview (Release 67, 13607.1.9.0.1)"
2179 # The `--version` flag was added in STP 67, so allow the call to fail.
2180 try:
2181 version_string = call(webdriver_binary, "--version").strip()
2182 except subprocess.CalledProcessError:
2183 self.logger.warning("Failed to call %s --version" % webdriver_binary)
2184 return None
2185 m = re.match(r"Included with Safari (.*)", version_string)
2186 if not m:
2187 self.logger.warning("Failed to extract version from: %s" % version_string)
2188 return None
2189 return m.group(1)
2190
2191
2192 class Servo(Browser):
2193 """Servo-specific interface."""
2194
2195 product = "servo"
2196 requirements = None
2197
2198 def platform_components(self):
2199 platform = {
2200 "Linux": "linux",
2201 "Windows": "win",
2202 "Darwin": "mac"
2203 }.get(uname[0])
2204
2205 if platform is None:
2206 raise ValueError("Unable to construct a valid Servo package for current platform")
2207
2208 if platform == "linux":
2209 extension = ".tar.gz"
2210 decompress = untar
2211 elif platform == "win" or platform == "mac":
2212 raise ValueError("Unable to construct a valid Servo package for current platform")
2213
2214 return (platform, extension, decompress)
2215
2216 def _get(self, channel="nightly"):
2217 if channel != "nightly":
2218 raise ValueError("Only nightly versions of Servo are available")
2219
2220 platform, extension, _ = self.platform_components()
2221 url = "https://download.servo.org/nightly/%s/servo-latest%s" % (platform, extension)
2222 return get(url)
2223
2224 def download(self, dest=None, channel="nightly", rename=None):
2225 if dest is None:
2226 dest = os.pwd
2227
2228 resp = self._get(dest, channel)
2229 _, extension, _ = self.platform_components()
2230
2231 filename = rename if rename is not None else "servo-latest"
2232 with open(os.path.join(dest, "%s%s" % (filename, extension,)), "w") as f:
2233 f.write(resp.content)
2234
2235 def install(self, dest=None, channel="nightly"):
2236 """Install latest Browser Engine."""
2237 if dest is None:
2238 dest = os.pwd
2239
2240 _, _, decompress = self.platform_components()
2241
2242 resp = self._get(channel)
2243 decompress(resp.raw, dest=dest)
2244 path = which("servo", path=os.path.join(dest, "servo"))
2245 st = os.stat(path)
2246 os.chmod(path, st.st_mode | stat.S_IEXEC)
2247 return path
2248
2249 def find_binary(self, venv_path=None, channel=None):
2250 path = which("servo", path=os.path.join(venv_path, "servo"))
2251 if path is None:
2252 path = which("servo")
2253 return path
2254
2255 def find_webdriver(self, venv_path=None, channel=None):
2256 return None
2257
2258 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
2259 raise NotImplementedError
2260
2261 def version(self, binary=None, webdriver_binary=None):
2262 """Retrieve the release version of the installed browser."""
2263 output = call(binary, "--version")
2264 m = re.search(r"Servo ([0-9\.]+-[a-f0-9]+)?(-dirty)?$", output.strip())
2265 if m:
2266 return m.group(0)
2267
2268
2269 class ServoWebDriver(Servo):
2270 product = "servodriver"
2271
2272
2273 class Sauce(Browser):
2274 """Sauce-specific interface."""
2275
2276 product = "sauce"
2277 requirements = "requirements_sauce.txt"
2278
2279 def download(self, dest=None, channel=None, rename=None):
2280 raise NotImplementedError
2281
2282 def install(self, dest=None, channel=None):
2283 raise NotImplementedError
2284
2285 def find_binary(self, venev_path=None, channel=None):
2286 raise NotImplementedError
2287
2288 def find_webdriver(self, venv_path=None, channel=None):
2289 raise NotImplementedError
2290
2291 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
2292 raise NotImplementedError
2293
2294 def version(self, binary=None, webdriver_binary=None):
2295 return None
2296
2297
2298 class WebKit(Browser):
2299 """WebKit-specific interface."""
2300
2301 product = "webkit"
2302 requirements = None
2303
2304 def download(self, dest=None, channel=None, rename=None):
2305 raise NotImplementedError
2306
2307 def install(self, dest=None, channel=None):
2308 raise NotImplementedError
2309
2310 def find_binary(self, venv_path=None, channel=None):
2311 return None
2312
2313 def find_webdriver(self, venv_path=None, channel=None):
2314 return None
2315
2316 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
2317 raise NotImplementedError
2318
2319 def version(self, binary=None, webdriver_binary=None):
2320 return None
2321
2322 class Ladybird(Browser):
2323 product = "ladybird"
2324 requirements = None
2325
2326 def download(self, dest=None, channel=None, rename=None):
2327 raise NotImplementedError
2328
2329 def install(self, dest=None, channel=None):
2330 raise NotImplementedError
2331
2332 def find_binary(self, venv_path=None, channel=None):
2333 return which("ladybird")
2334
2335 def find_webdriver(self, venv_path=None, channel=None):
2336 return which("WebDriver")
2337
2338 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
2339 raise NotImplementedError
2340
2341 def version(self, binary=None, webdriver_binary=None):
2342 if not binary:
2343 self.logger.warning("No browser binary provided.")
2344 return None
2345 output = call(binary, "--version")
2346 if output:
2347 version_string = output.strip()
2348 match = re.match(r"Version (.*)", version_string)
2349 if match:
2350 return match.group(1)
2351 return None
2352
2353 class WebKitTestRunner(Browser):
2354 """Interface for WebKitTestRunner.
2355 """
2356
2357 product = "wktr"
2358 requirements = None
2359
2360 def _find_apple_port_builds(self, channel="main"):
2361 if channel != "main":
2362 raise ValueError(f"unable to get builds for branch {channel}")
2363
2364 system_version, _, _ = platform.mac_ver()
2365 if system_version in SpecifierSet("==13.*"):
2366 platform_key = "mac-ventura-x86_64%20arm64"
2367 elif system_version in SpecifierSet("==12.*"):
2368 platform_key = "mac-monterey-x86_64%20arm64"
2369 else:
2370 raise ValueError(
2371 f"don't know what platform to use for macOS {system_version}"
2372 )
2373
2374 # This should match http://github.com/WebKit/WebKit/blob/main/Websites/webkit.org/wp-content/themes/webkit/build-archives.php
2375 build_index = get(
2376 f"https://q1tzqfy48e.execute-api.us-west-2.amazonaws.com/v3/latest/{platform_key}-release"
2377 ).json()
2378
2379 builds = []
2380
2381 for entry in build_index["Items"]:
2382 creation_time = datetime.fromtimestamp(
2383 int(entry["creationTime"]["N"]), timezone.utc
2384 )
2385 identifier = entry["identifier"]["S"]
2386 s3_url = entry["s3_url"]["S"]
2387
2388 builds.append((s3_url, identifier, creation_time))
2389
2390 return builds
2391
2392 def _download_metadata_apple_port(self, channel="main"):
2393 digit_re = re.compile("([0-9]+)")
2394
2395 def natsort(string_to_split):
2396 split = digit_re.split(string_to_split)
2397 # this converts the split numbers into tuples so that "01" < "1"
2398 split[1::2] = [(int(i), i) for i in split[1::2]]
2399 return split
2400
2401 builds = sorted(
2402 self._find_apple_port_builds(channel),
2403 key=lambda x: natsort(x[1]),
2404 reverse=True,
2405 )
2406 latest_build = builds[0]
2407
2408 return {
2409 "url": latest_build[0],
2410 "identifier": latest_build[1],
2411 "creation_time": latest_build[2],
2412 }
2413
2414 def download(
2415 self, dest=None, channel="main", rename=None, version=None, revision=None
2416 ):
2417 if platform.system() == "Darwin":
2418 meta = self._download_metadata_apple_port(channel)
2419 else:
2420 raise ValueError("Unsupported platform")
2421
2422 output_path = self.download_from_url(
2423 meta["url"],
2424 dest=dest,
2425 channel=channel,
2426 rename=rename,
2427 )
2428
2429 dest = os.path.dirname(output_path) # This is the actual, used dest.
2430
2431 self.last_revision_used = meta["identifier"]
2432 with open(os.path.join(dest, "identifier"), "w") as f:
2433 f.write(self.last_revision_used)
2434
2435 return output_path
2436
2437 def install(self, dest=None, channel="main"):
2438 dest = self._get_browser_binary_dir(dest, channel)
2439 installer_path = self.download(dest=dest, channel=channel)
2440 self.logger.info(f"Extracting to {dest}")
2441 with open(installer_path, "rb") as f:
2442 unzip(f, dest)
2443
2444 def install_webdriver(self, dest=None, channel="main", browser_binary=None):
2445 raise NotImplementedError
2446
2447 def find_binary(self, venv_path=None, channel="main"):
2448 path = self._get_browser_binary_dir(venv_path, channel)
2449 return which("WebKitTestRunner", path=os.path.join(path, "Release"))
2450
2451 def find_webdriver(self, venv_path=None, channel="main"):
2452 return None
2453
2454 def version(self, binary=None, webdriver_binary=None):
2455 dirname = os.path.dirname(binary)
2456 identifier = os.path.join(dirname, "..", "identifier")
2457 if not os.path.exists(identifier):
2458 return None
2459
2460 with open(identifier, "r") as f:
2461 return f.read().strip()
2462
2463
2464 class WebKitGlibBaseMiniBrowser(WebKit):
2465 """WebKitGTK and WPE MiniBrowser specific interface (base class)."""
2466
2467 # This class is not meant to be used directly.
2468 # And the class variables below should be defined on the subclasses.
2469 BASE_DOWNLOAD_URI = ""
2470 PORT_PRETTY_NAME = ""
2471 WEBDRIVER_BINARY_NAME = ""
2472 LIBEXEC_SUBDIR_PREFIXES = [""]
2473 product = ""
2474
2475 def __init__(self, *args, **kwargs):
2476 if self.__class__.__name__ == "WebKitGlibBaseMiniBrowser":
2477 raise RuntimeError("class WebKitGlibBaseMiniBrowser should not be used directly, but subclassed")
2478 for required_class_var in ["BASE_DOWNLOAD_URI", "PORT_PRETTY_NAME", "WEBDRIVER_BINARY_NAME", "LIBEXEC_SUBDIR_PREFIXES", "product"]:
2479 class_var_value = getattr(self, required_class_var, "")
2480 if all(len(i) == 0 for i in class_var_value):
2481 raise NotImplementedError('subclass "%s" should define class variable "%s"' % (self.__class__.__name__, required_class_var))
2482 return super().__init__(*args, **kwargs)
2483
2484 def download(self, dest=None, channel=None, rename=None):
2485 base_download_dir = self.BASE_DOWNLOAD_URI + platform.machine() + "/release/" + channel + "/MiniBrowser/"
2486 try:
2487 response = get(base_download_dir + "LAST-IS")
2488 except requests.exceptions.HTTPError as e:
2489 if e.response.status_code == 404:
2490 raise RuntimeError("Can't find a %s MiniBrowser %s bundle for %s at %s"
2491 % (self.PORT_PRETTY_NAME, channel, platform.machine(), self.BASE_DOWNLOAD_URI))
2492 raise
2493
2494 bundle_filename = response.text.strip()
2495 bundle_url = base_download_dir + quote(bundle_filename)
2496
2497 dest = self._get_browser_download_dir(dest, channel)
2498 bundle_file_path = os.path.join(dest, bundle_filename)
2499
2500 self.logger.info("Downloading %s MiniBrowser bundle from %s" % (self.PORT_PRETTY_NAME, bundle_url))
2501 with open(bundle_file_path, "w+b") as f:
2502 get_download_to_descriptor(f, bundle_url)
2503
2504 ext_ndots = 2 if '.tar.' in bundle_filename else 1
2505 bundle_filename_no_ext = '.'.join(bundle_filename.split('.')[:-ext_ndots])
2506 bundle_hash_url = base_download_dir + bundle_filename_no_ext + ".sha256sum"
2507 bundle_expected_hash = get(bundle_hash_url).text.strip().split(" ")[0]
2508 bundle_computed_hash = sha256sum(bundle_file_path)
2509
2510 if bundle_expected_hash != bundle_computed_hash:
2511 self.logger.error("Calculated SHA256 hash is %s but was expecting %s" % (bundle_computed_hash, bundle_expected_hash))
2512 raise RuntimeError("The %s MiniBrowser bundle at %s has incorrect SHA256 hash." % (self.PORT_PRETTY_NAME, bundle_file_path))
2513 return bundle_file_path
2514
2515 def install(self, dest=None, channel=None, prompt=True):
2516 dest = self._get_browser_binary_dir(dest, channel)
2517 bundle_path = self.download(dest, channel)
2518 bundle_uncompress_directory = os.path.join(dest, self.product)
2519
2520 # Clean it from previous runs
2521 if os.path.exists(bundle_uncompress_directory):
2522 rmtree(bundle_uncompress_directory)
2523 os.mkdir(bundle_uncompress_directory)
2524
2525 bundle_file_name = os.path.basename(bundle_path)
2526 with open(bundle_path, "rb") as f:
2527 if bundle_file_name.endswith(".zip"):
2528 unzip(f, bundle_uncompress_directory)
2529 elif ".tar." in bundle_file_name:
2530 untar(f, bundle_uncompress_directory)
2531 else:
2532 raise NotImplementedError("Don't know how to install the file: %s" % bundle_file_name)
2533 os.remove(bundle_path)
2534
2535 for expected_binary in ["MiniBrowser", self.WEBDRIVER_BINARY_NAME]:
2536 binary_path = os.path.join(bundle_uncompress_directory, expected_binary)
2537 if not (os.path.isfile(binary_path) and os.access(binary_path, os.X_OK)):
2538 raise RuntimeError("Can't find a %s binary at %s" % (expected_binary, binary_path))
2539
2540 minibrowser_path = os.path.join(bundle_uncompress_directory, "MiniBrowser")
2541 version_str = subprocess.check_output([minibrowser_path, "--version"]).decode("utf-8").strip()
2542 self.logger.info("%s MiniBrowser bundle for channel %s installed: %s" % (self.PORT_PRETTY_NAME, channel, version_str))
2543 install_ok_file = os.path.join(bundle_uncompress_directory, ".installation-ok")
2544 open(install_ok_file, "w").close() # touch
2545 return minibrowser_path
2546
2547 def _find_executable_in_channel_bundle(self, binary, venv_path=None, channel=None):
2548 if venv_path:
2549 venv_base_path = self._get_browser_binary_dir(venv_path, channel)
2550 bundle_dir = os.path.join(venv_base_path, self.product)
2551 install_ok_file = os.path.join(bundle_dir, ".installation-ok")
2552 if os.path.isfile(install_ok_file):
2553 return shutil.which(binary, path=bundle_dir)
2554 return None
2555
2556 def find_binary(self, venv_path=None, channel=None):
2557 minibrowser_path = self._find_executable_in_channel_bundle("MiniBrowser", venv_path, channel)
2558 if minibrowser_path:
2559 self.logger.info("Found %s MiniBrowser %s at path: %s" % (self.PORT_PRETTY_NAME, channel, minibrowser_path))
2560 return minibrowser_path
2561
2562 # Find MiniBrowser on the system which is usually installed on the libexec dir
2563 triplet = "x86_64-linux-gnu"
2564 # Try to use GCC to detect this machine triplet
2565 gcc = shutil.which("gcc")
2566 if gcc:
2567 try:
2568 triplet = call(gcc, "-dumpmachine").strip()
2569 except subprocess.CalledProcessError:
2570 pass
2571 for libexec_dir in ["/usr/libexec", f"/usr/lib/{triplet}", "/usr/lib"]:
2572 if os.path.isdir(libexec_dir):
2573 for libexec_entry in sorted(os.listdir(libexec_dir), reverse=True):
2574 for libexec_subdir_prefix in self.LIBEXEC_SUBDIR_PREFIXES:
2575 if libexec_entry.startswith(libexec_subdir_prefix):
2576 minibrowser_candidate_path = os.path.join(libexec_dir, libexec_entry, 'MiniBrowser')
2577 if os.path.isfile(minibrowser_candidate_path) and os.access(minibrowser_candidate_path, os.X_OK):
2578 self.logger.info("Found %s MiniBrowser at path: %s" % (self.PORT_PRETTY_NAME, minibrowser_candidate_path))
2579 return minibrowser_candidate_path
2580 return None
2581
2582 def find_webdriver(self, venv_path=None, channel=None):
2583 webdriver_path = self._find_executable_in_channel_bundle(self.WEBDRIVER_BINARY_NAME, venv_path, channel)
2584 if not webdriver_path:
2585 webdriver_path = shutil.which(self.WEBDRIVER_BINARY_NAME)
2586 if webdriver_path:
2587 self.logger.info("Found %s WebDriver at path: %s" % (self.PORT_PRETTY_NAME, webdriver_path))
2588 return webdriver_path
2589
2590 def version(self, binary=None, webdriver_binary=None):
2591 if binary is None:
2592 return None
2593 try: # WebKitGTK MiniBrowser before 2.26.0 doesn't support --version
2594 output = call(binary, "--version").strip()
2595 except subprocess.CalledProcessError:
2596 return None
2597 # Example output: "WebKitGTK 2.26.1"
2598 if output:
2599 m = re.match(r"%s (.+)" % self.PORT_PRETTY_NAME, output)
2600 if not m:
2601 self.logger.warning("Failed to extract version from: %s" % output)
2602 return None
2603 return m.group(1)
2604 return None
2605
2606
2607 class WebKitGTKMiniBrowser(WebKitGlibBaseMiniBrowser):
2608 """WebKitGTK MiniBrowser specific interface."""
2609
2610 BASE_DOWNLOAD_URI = "https://webkitgtk.org/built-products/"
2611 PORT_PRETTY_NAME = "WebKitGTK"
2612 WEBDRIVER_BINARY_NAME = "WebKitWebDriver"
2613 LIBEXEC_SUBDIR_PREFIXES = ["webkitgtk", "webkit2gtk"]
2614 product = "webkitgtk_minibrowser"
2615
2616
2617 class WPEWebKitMiniBrowser(WebKitGlibBaseMiniBrowser):
2618 """WPE WebKit MiniBrowser specific interface."""
2619
2620 BASE_DOWNLOAD_URI = "https://wpewebkit.org/built-products/"
2621 PORT_PRETTY_NAME = "WPE WebKit"
2622 WEBDRIVER_BINARY_NAME = "WPEWebDriver"
2623 LIBEXEC_SUBDIR_PREFIXES = ["wpe-webkit"]
2624 product = "wpewebkit_minibrowser"
2625
2626
2627 class Epiphany(Browser):
2628 """Epiphany-specific interface."""
2629
2630 product = "epiphany"
2631 requirements = None
2632
2633 def download(self, dest=None, channel=None, rename=None):
2634 raise NotImplementedError
2635
2636 def install(self, dest=None, channel=None):
2637 raise NotImplementedError
2638
2639 def find_binary(self, venv_path=None, channel=None):
2640 return which("epiphany")
2641
2642 def find_webdriver(self, venv_path=None, channel=None):
2643 return which("WebKitWebDriver")
2644
2645 def install_webdriver(self, dest=None, channel=None, browser_binary=None):
2646 raise NotImplementedError
2647
2648 def version(self, binary=None, webdriver_binary=None):
2649 if binary is None:
2650 return None
2651 output = call(binary, "--version")
2652 if output:
2653 # Stable release output looks like: "Web 3.30.2"
2654 # Tech Preview output looks like "Web 3.31.3-88-g97db4f40f"
2655 return output.split()[1]
2656 return None