Debian Codegraph @

testing/mozharness/scripts/android_emulator_unittest.py

raw
1 #!/usr/bin/env python
2 # This Source Code Form is subject to the terms of the Mozilla Public
3 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
4 # You can obtain one at http://mozilla.org/MPL/2.0/.
5
6 import copy
7 import datetime
8 import json
9 import os
10 import subprocess
11 import sys
12
13 # load modules from parent dir
14 here = os.path.abspath(os.path.dirname(__file__))
15 sys.path.insert(1, os.path.dirname(here))
16
17 from mozharness.base.log import WARNING
18 from mozharness.base.script import BaseScript, PreScriptAction
19 from mozharness.mozilla.automation import TBPL_RETRY
20 from mozharness.mozilla.mozbase import MozbaseMixin
21 from mozharness.mozilla.testing.android import AndroidMixin
22 from mozharness.mozilla.testing.codecoverage import (
23 CodeCoverageMixin,
24 code_coverage_config_options,
25 )
26 from mozharness.mozilla.testing.testbase import TestingMixin, testing_config_options
27
28 SUITE_DEFAULT_E10S = ["geckoview-junit", "mochitest", "reftest"]
29 SUITE_NO_E10S = ["cppunittest", "gtest", "jittest", "xpcshell"]
30 SUITE_REPEATABLE = ["mochitest", "reftest", "xpcshell"]
31
32
33 class AndroidEmulatorTest(
34 TestingMixin, BaseScript, MozbaseMixin, CodeCoverageMixin, AndroidMixin
35 ):
36 """
37 A mozharness script for Android functional tests (like mochitests and reftests)
38 run on an Android emulator. This script starts and manages an Android emulator
39 for the duration of the required tests. This is like desktop_unittest.py, but
40 for Android emulator test platforms.
41 """
42
43 config_options = (
44 [
45 [
46 ["--test-suite"],
47 {"action": "store", "dest": "test_suite", "default": None},
48 ],
49 [
50 ["--total-chunk"],
51 {
52 "action": "store",
53 "dest": "total_chunks",
54 "default": None,
55 "help": "Number of total chunks",
56 },
57 ],
58 [
59 ["--this-chunk"],
60 {
61 "action": "store",
62 "dest": "this_chunk",
63 "default": None,
64 "help": "Number of this chunk",
65 },
66 ],
67 [
68 ["--enable-xorigin-tests"],
69 {
70 "action": "store_true",
71 "dest": "enable_xorigin_tests",
72 "default": False,
73 "help": "Run tests in a cross origin iframe.",
74 },
75 ],
76 [
77 ["--gpu-required"],
78 {
79 "action": "store_true",
80 "dest": "gpu_required",
81 "default": False,
82 "help": "Run additional verification on modified tests using gpu instances.",
83 },
84 ],
85 [
86 ["--log-raw-level"],
87 {
88 "action": "store",
89 "dest": "log_raw_level",
90 "default": "info",
91 "help": "Set log level (debug|info|warning|error|critical|fatal)",
92 },
93 ],
94 [
95 ["--log-tbpl-level"],
96 {
97 "action": "store",
98 "dest": "log_tbpl_level",
99 "default": "info",
100 "help": "Set log level (debug|info|warning|error|critical|fatal)",
101 },
102 ],
103 [
104 ["--disable-e10s"],
105 {
106 "action": "store_false",
107 "dest": "e10s",
108 "default": True,
109 "help": "Run tests without multiple processes (e10s).",
110 },
111 ],
112 [
113 ["--disable-fission"],
114 {
115 "action": "store_true",
116 "dest": "disable_fission",
117 "default": False,
118 "help": "Run without Fission enabled.",
119 },
120 ],
121 [
122 ["--web-content-isolation-strategy"],
123 {
124 "action": "store",
125 "type": "int",
126 "dest": "web_content_isolation_strategy",
127 "help": "Strategy used to determine whether or not a particular site should"
128 "load into a webIsolated content process, see "
129 "fission.webContentIsolationStrategy.",
130 },
131 ],
132 [
133 ["--repeat"],
134 {
135 "action": "store",
136 "type": "int",
137 "dest": "repeat",
138 "default": 0,
139 "help": "Repeat the tests the given number of times. Supported "
140 "by mochitest, reftest, crashtest, ignored otherwise.",
141 },
142 ],
143 [
144 ["--setpref"],
145 {
146 "action": "append",
147 "metavar": "PREF=VALUE",
148 "dest": "extra_prefs",
149 "default": [],
150 "help": "Extra user prefs.",
151 },
152 ],
153 [
154 ["--tag"],
155 {
156 "action": "append",
157 "default": [],
158 "dest": "test_tags",
159 "help": "Filter out tests that don't have the given tag. Can be used multiple "
160 "times in which case the test must contain at least one of the given tags.",
161 },
162 ],
163 ]
164 + copy.deepcopy(testing_config_options)
165 + copy.deepcopy(code_coverage_config_options)
166 )
167
168 def __init__(self, require_config_file=False):
169 super(AndroidEmulatorTest, self).__init__(
170 config_options=self.config_options,
171 all_actions=[
172 "clobber",
173 "download-and-extract",
174 "create-virtualenv",
175 "start-emulator",
176 "verify-device",
177 "install",
178 "run-tests",
179 ],
180 require_config_file=require_config_file,
181 config={
182 "virtualenv_modules": [],
183 "virtualenv_requirements": [],
184 "require_test_zip": True,
185 },
186 )
187
188 # these are necessary since self.config is read only
189 c = self.config
190 self.installer_url = c.get("installer_url")
191 self.installer_path = c.get("installer_path")
192 self.test_url = c.get("test_url")
193 self.test_packages_url = c.get("test_packages_url")
194 self.test_manifest = c.get("test_manifest")
195 suite = c.get("test_suite")
196 self.test_suite = suite
197 self.this_chunk = c.get("this_chunk")
198 self.total_chunks = c.get("total_chunks")
199 self.xre_path = None
200 self.device_serial = "emulator-5554"
201 self.log_raw_level = c.get("log_raw_level")
202 self.log_tbpl_level = c.get("log_tbpl_level")
203 # AndroidMixin uses this when launching the emulator. We only want
204 # GLES3 if we're running WebRender (default)
205 self.use_gles3 = True
206 self.disable_e10s = c.get("disable_e10s")
207 self.disable_fission = c.get("disable_fission")
208 self.web_content_isolation_strategy = c.get("web_content_isolation_strategy")
209 self.extra_prefs = c.get("extra_prefs")
210 self.test_tags = c.get("test_tags")
211
212 def query_abs_dirs(self):
213 if self.abs_dirs:
214 return self.abs_dirs
215 abs_dirs = super(AndroidEmulatorTest, self).query_abs_dirs()
216 dirs = {}
217 dirs["abs_test_install_dir"] = os.path.join(abs_dirs["abs_work_dir"], "tests")
218 dirs["abs_test_bin_dir"] = os.path.join(
219 abs_dirs["abs_work_dir"], "tests", "bin"
220 )
221 dirs["abs_modules_dir"] = os.path.join(dirs["abs_test_install_dir"], "modules")
222 dirs["abs_blob_upload_dir"] = os.path.join(
223 abs_dirs["abs_work_dir"], "blobber_upload_dir"
224 )
225 dirs["abs_mochitest_dir"] = os.path.join(
226 dirs["abs_test_install_dir"], "mochitest"
227 )
228 dirs["abs_reftest_dir"] = os.path.join(dirs["abs_test_install_dir"], "reftest")
229 dirs["abs_xpcshell_dir"] = os.path.join(
230 dirs["abs_test_install_dir"], "xpcshell"
231 )
232 work_dir = os.environ.get("MOZ_FETCHES_DIR") or abs_dirs["abs_work_dir"]
233 dirs["abs_xre_dir"] = os.path.join(work_dir, "hostutils")
234 dirs["abs_sdk_dir"] = os.path.join(work_dir, "android-sdk-linux")
235 dirs["abs_avds_dir"] = os.path.join(work_dir, "android-device")
236 dirs["abs_bundletool_path"] = os.path.join(work_dir, "bundletool.jar")
237
238 for key in dirs.keys():
239 if key not in abs_dirs:
240 abs_dirs[key] = dirs[key]
241 self.abs_dirs = abs_dirs
242 return self.abs_dirs
243
244 def _query_tests_dir(self, test_suite):
245 dirs = self.query_abs_dirs()
246 try:
247 test_dir = self.config["suite_definitions"][test_suite]["testsdir"]
248 except Exception:
249 test_dir = test_suite
250 return os.path.join(dirs["abs_test_install_dir"], test_dir)
251
252 def _get_mozharness_test_paths(self, suite):
253 test_paths = json.loads(os.environ.get("MOZHARNESS_TEST_PATHS", '""'))
254 confirm_paths = json.loads(os.environ.get("MOZHARNESS_CONFIRM_PATHS", '""'))
255
256 if not test_paths or not test_paths.get(suite, []):
257 return None
258
259 suite_test_paths = test_paths.get(suite, [])
260 if confirm_paths and confirm_paths.get(suite, []):
261 suite_test_paths = confirm_paths.get(suite, [])
262
263 if suite in ("reftest", "crashtest"):
264 dirs = self.query_abs_dirs()
265 suite_test_paths = [
266 os.path.join(dirs["abs_reftest_dir"], "tests", p)
267 for p in suite_test_paths
268 ]
269
270 return suite_test_paths
271
272 def _build_command(self):
273 c = self.config
274 dirs = self.query_abs_dirs()
275
276 if self.test_suite not in self.config["suite_definitions"]:
277 self.fatal("Key '%s' not defined in the config!" % self.test_suite)
278
279 cmd = [
280 self.query_python_path("python"),
281 "-u",
282 os.path.join(
283 self._query_tests_dir(self.test_suite),
284 self.config["suite_definitions"][self.test_suite]["run_filename"],
285 ),
286 ]
287
288 raw_log_file, error_summary_file = self.get_indexed_logs(
289 dirs["abs_blob_upload_dir"], self.test_suite
290 )
291
292 str_format_values = {
293 "device_serial": self.device_serial,
294 # IP address of the host as seen from the emulator
295 "remote_webserver": "10.0.2.2",
296 "xre_path": self.xre_path,
297 "utility_path": self.xre_path,
298 "http_port": "8854", # starting http port to use for the mochitest server
299 "ssl_port": "4454", # starting ssl port to use for the server
300 "certs_path": os.path.join(dirs["abs_work_dir"], "tests/certs"),
301 # TestingMixin._download_and_extract_symbols() will set
302 # self.symbols_path when downloading/extracting.
303 "symbols_path": self.symbols_path,
304 "modules_dir": dirs["abs_modules_dir"],
305 "installer_path": self.installer_path,
306 "raw_log_file": raw_log_file,
307 "log_tbpl_level": self.log_tbpl_level,
308 "log_raw_level": self.log_raw_level,
309 "error_summary_file": error_summary_file,
310 "xpcshell_extra": c.get("xpcshell_extra", ""),
311 "gtest_dir": os.path.join(dirs["abs_test_install_dir"], "gtest"),
312 }
313
314 user_paths = self._get_mozharness_test_paths(self.test_suite)
315
316 for option in self.config["suite_definitions"][self.test_suite]["options"]:
317 opt = option.split("=")[0]
318 # override configured chunk options with script args, if specified
319 if opt in ("--this-chunk", "--total-chunks"):
320 if (
321 user_paths
322 or getattr(self, opt.replace("-", "_").strip("_"), None) is not None
323 ):
324 continue
325
326 if "%(app)" in option:
327 # only query package name if requested
328 cmd.extend([option % {"app": self.query_package_name()}])
329 else:
330 option = option % str_format_values
331 if option:
332 cmd.extend([option])
333
334 if "mochitest" in self.test_suite:
335 category = "mochitest"
336 elif "reftest" in self.test_suite or "crashtest" in self.test_suite:
337 category = "reftest"
338 else:
339 category = self.test_suite
340 if c.get("repeat"):
341 if category in SUITE_REPEATABLE:
342 cmd.extend(["--repeat=%s" % c.get("repeat")])
343 else:
344 self.log(f"--repeat not supported in {category}", level=WARNING)
345
346 # do not add --disable fission if we don't have --disable-e10s
347 if c["disable_fission"] and category not in ["gtest", "cppunittest"]:
348 cmd.append("--disable-fission")
349
350 if "web_content_isolation_strategy" in c:
351 cmd.append(
352 "--web-content-isolation-strategy=%s"
353 % c["web_content_isolation_strategy"]
354 )
355 cmd.extend([f"--setpref={p}" for p in self.extra_prefs])
356
357 if not (self.verify_enabled or self.per_test_coverage):
358 if user_paths or self.test_tags:
359 if user_paths:
360 cmd.extend(user_paths)
361 if self.test_tags:
362 cmd.extend([f"--tag={t}" for t in self.test_tags])
363 else:
364 if self.this_chunk is not None:
365 cmd.extend(["--this-chunk", self.this_chunk])
366 if self.total_chunks is not None:
367 cmd.extend(["--total-chunks", self.total_chunks])
368
369 if category not in SUITE_NO_E10S:
370 if category in SUITE_DEFAULT_E10S and not c["e10s"]:
371 cmd.append("--disable-e10s")
372 elif category not in SUITE_DEFAULT_E10S and c["e10s"]:
373 cmd.append("--e10s")
374
375 if c.get("enable_xorigin_tests"):
376 cmd.extend(["--enable-xorigin-tests"])
377
378 try_options, try_tests = self.try_args(self.test_suite)
379 cmd.extend(try_options)
380 if not self.verify_enabled and not self.per_test_coverage and not user_paths:
381 cmd.extend(
382 self.query_tests_args(
383 self.config["suite_definitions"][self.test_suite].get("tests"),
384 None,
385 try_tests,
386 )
387 )
388
389 if self.java_code_coverage_enabled:
390 cmd.extend(
391 [
392 "--enable-coverage",
393 "--coverage-output-dir",
394 self.java_coverage_output_dir,
395 ]
396 )
397
398 if self.config.get("restartAfterFailure", False):
399 cmd.append("--restartAfterFailure")
400
401 return cmd
402
403 def _query_suites(self):
404 if self.test_suite:
405 return [(self.test_suite, self.test_suite)]
406 # per-test mode: determine test suites to run
407
408 # For each test category, provide a list of supported sub-suites and a mapping
409 # between the per_test_base suite name and the android suite name.
410 all = [
411 (
412 "mochitest",
413 {
414 "mochitest-plain": "mochitest-plain",
415 "mochitest-media": "mochitest-media",
416 "mochitest-plain-gpu": "mochitest-plain-gpu",
417 },
418 ),
419 (
420 "reftest",
421 {
422 "reftest": "reftest",
423 "crashtest": "crashtest",
424 "jsreftest": "jsreftest",
425 },
426 ),
427 ("xpcshell", {"xpcshell": "xpcshell"}),
428 ]
429 suites = []
430 for category, all_suites in all:
431 cat_suites = self.query_per_test_category_suites(category, all_suites)
432 for k in cat_suites.keys():
433 suites.append((k, cat_suites[k]))
434 return suites
435
436 def _query_suite_categories(self):
437 if self.test_suite:
438 categories = [self.test_suite]
439 else:
440 # per-test mode
441 categories = ["mochitest", "reftest", "xpcshell"]
442 return categories
443
444 ##########################################
445 # Actions for AndroidEmulatorTest #
446 ##########################################
447
448 def preflight_install(self):
449 # in the base class, this checks for mozinstall, but we don't use it
450 pass
451
452 @PreScriptAction("create-virtualenv")
453 def pre_create_virtualenv(self, action):
454 dirs = self.query_abs_dirs()
455 requirements = None
456 suites = self._query_suites()
457 if ("mochitest-media", "mochitest-media") in suites:
458 # mochitest-media is the only thing that needs this
459 requirements = os.path.join(
460 dirs["abs_mochitest_dir"],
461 "websocketprocessbridge",
462 "websocketprocessbridge_requirements_3.txt",
463 )
464 if requirements:
465 self.register_virtualenv_module(requirements=[requirements])
466
467 def download_and_extract(self):
468 """
469 Download and extract product APK, tests.zip, and host utils.
470 """
471 super(AndroidEmulatorTest, self).download_and_extract(
472 suite_categories=self._query_suite_categories()
473 )
474 dirs = self.query_abs_dirs()
475 self.xre_path = dirs["abs_xre_dir"]
476
477 def install(self):
478 """
479 Install APKs on the device.
480 """
481 install_needed = (not self.test_suite) or self.config["suite_definitions"][
482 self.test_suite
483 ].get("install")
484 if install_needed is False:
485 self.info("Skipping apk installation for %s" % self.test_suite)
486 return
487 assert (
488 self.installer_path is not None
489 ), "Either add installer_path to the config or use --installer-path."
490 self.install_android_app(self.installer_path)
491 self.info("Finished installing apps for %s" % self.device_serial)
492
493 def run_tests(self):
494 """
495 Run the tests
496 """
497 self.start_time = datetime.datetime.now()
498 max_per_test_time = datetime.timedelta(minutes=60)
499
500 per_test_args = []
501 suites = self._query_suites()
502 minidump = self.query_minidump_stackwalk()
503 for per_test_suite, suite in suites:
504 self.test_suite = suite
505
506 try:
507 cwd = self._query_tests_dir(self.test_suite)
508 except Exception:
509 self.fatal("Don't know how to run --test-suite '%s'!" % self.test_suite)
510
511 env = self.query_env()
512 if minidump:
513 env["MINIDUMP_STACKWALK"] = minidump
514 env["MOZ_UPLOAD_DIR"] = self.query_abs_dirs()["abs_blob_upload_dir"]
515 env["MINIDUMP_SAVE_PATH"] = self.query_abs_dirs()["abs_blob_upload_dir"]
516 env["RUST_BACKTRACE"] = "full"
517 if self.config["nodejs_path"]:
518 env["MOZ_NODE_PATH"] = self.config["nodejs_path"]
519
520 summary = {}
521 for per_test_args in self.query_args(per_test_suite):
522 if (datetime.datetime.now() - self.start_time) > max_per_test_time:
523 # Running tests has run out of time. That is okay! Stop running
524 # them so that a task timeout is not triggered, and so that
525 # (partial) results are made available in a timely manner.
526 self.info(
527 "TinderboxPrint: Running tests took too long: "
528 "Not all tests were executed.<br/>"
529 )
530 # Signal per-test time exceeded, to break out of suites and
531 # suite categories loops also.
532 return
533
534 cmd = self._build_command()
535 final_cmd = copy.copy(cmd)
536 if len(per_test_args) > 0:
537 # in per-test mode, remove any chunk arguments from command
538 for arg in final_cmd:
539 if "total-chunk" in arg or "this-chunk" in arg:
540 final_cmd.remove(arg)
541 final_cmd.extend(per_test_args)
542
543 self.info("Running the command %s" % subprocess.list2cmdline(final_cmd))
544 self.info("##### %s log begins" % self.test_suite)
545
546 suite_category = self.test_suite
547 parser = self.get_test_output_parser(
548 suite_category,
549 config=self.config,
550 log_obj=self.log_obj,
551 error_list=[],
552 )
553 self.run_command(final_cmd, cwd=cwd, env=env, output_parser=parser)
554 tbpl_status, log_level, summary = parser.evaluate_parser(
555 0, previous_summary=summary
556 )
557 parser.append_tinderboxprint_line(self.test_suite)
558
559 self.info("##### %s log ends" % self.test_suite)
560
561 if len(per_test_args) > 0:
562 self.record_status(tbpl_status, level=log_level)
563 self.log_per_test_status(per_test_args[-1], tbpl_status, log_level)
564 if tbpl_status == TBPL_RETRY:
565 self.info("Per-test run abandoned due to RETRY status")
566 return
567 else:
568 self.record_status(tbpl_status, level=log_level)
569 # report as INFO instead of log_level to avoid extra Treeherder lines
570 self.info(
571 "The %s suite: %s ran with return status: %s"
572 % (suite_category, suite, tbpl_status),
573 )
574
575
576 if __name__ == "__main__":
577 test = AndroidEmulatorTest()
578 test.run_and_exit()