Debian Codegraph @

testing/mach_commands.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import argparse
6 import logging
7 import os
8 import sys
9 from datetime import date, timedelta
10 from typing import List, Optional
11
12 import requests
13 from clean_skipfails import CleanSkipfails
14 from mach.decorators import Command, CommandArgument, SubCommand
15 from mozbuild.base import BuildEnvironmentNotFoundException
16 from mozbuild.base import MachCommandConditions as conditions
17
18 UNKNOWN_TEST = """
19 I was unable to find tests from the given argument(s).
20
21 You should specify a test directory, filename, test suite name, or
22 abbreviation.
23
24 It's possible my little brain doesn't know about the type of test you are
25 trying to execute. If you suspect this, please request support by filing
26 a bug at
27 https://bugzilla.mozilla.org/enter_bug.cgi?product=Testing&component=General.
28 """.strip()
29
30 UNKNOWN_FLAVOR = """
31 I know you are trying to run a %s%s test. Unfortunately, I can't run those
32 tests yet. Sorry!
33 """.strip()
34
35 TEST_HELP = """
36 Test or tests to run. Tests can be specified by filename, directory, suite
37 name or suite alias.
38
39 The following test suites and aliases are supported: {}
40 """.strip()
41
42
43 def get_test_parser():
44 from mozlog.commandline import add_logging_group
45 from moztest.resolve import TEST_SUITES
46
47 parser = argparse.ArgumentParser()
48 parser.add_argument(
49 "what",
50 default=None,
51 nargs="+",
52 help=TEST_HELP.format(", ".join(sorted(TEST_SUITES))),
53 )
54 parser.add_argument(
55 "extra_args",
56 default=None,
57 nargs=argparse.REMAINDER,
58 help="Extra arguments to pass to the underlying test command(s). "
59 "If an underlying command doesn't recognize the argument, it "
60 "will fail.",
61 )
62 parser.add_argument(
63 "--debugger",
64 default=None,
65 action="store",
66 nargs="?",
67 help="Specify a debugger to use.",
68 )
69 add_logging_group(parser)
70 return parser
71
72
73 ADD_TEST_SUPPORTED_SUITES = [
74 "mochitest-chrome",
75 "mochitest-plain",
76 "mochitest-browser-chrome",
77 "web-platform-tests",
78 "web-platform-tests-reftest",
79 "xpcshell",
80 ]
81 ADD_TEST_SUPPORTED_DOCS = ["js", "html", "xhtml", "xul"]
82
83 SUITE_SYNONYMS = {
84 "wpt": "web-platform-tests",
85 "wpt-testharness": "web-platform-tests",
86 "wpt-reftest": "web-platform-tests-reftest",
87 }
88
89 MISSING_ARG = object()
90
91
92 def create_parser_addtest():
93 import addtest
94
95 parser = argparse.ArgumentParser()
96 parser.add_argument(
97 "--suite",
98 choices=sorted(ADD_TEST_SUPPORTED_SUITES + list(SUITE_SYNONYMS.keys())),
99 help="suite for the test. "
100 "If you pass a `test` argument this will be determined "
101 "based on the filename and the folder it is in",
102 )
103 parser.add_argument(
104 "-o",
105 "--overwrite",
106 action="store_true",
107 help="Overwrite an existing file if it exists.",
108 )
109 parser.add_argument(
110 "--doc",
111 choices=ADD_TEST_SUPPORTED_DOCS,
112 help="Document type for the test (if applicable)."
113 "If you pass a `test` argument this will be determined "
114 "based on the filename.",
115 )
116 parser.add_argument(
117 "-e",
118 "--editor",
119 action="store",
120 nargs="?",
121 default=MISSING_ARG,
122 help="Open the created file(s) in an editor; if a "
123 "binary is supplied it will be used otherwise the default editor for "
124 "your environment will be opened",
125 )
126
127 for base_suite in addtest.TEST_CREATORS:
128 cls = addtest.TEST_CREATORS[base_suite]
129 if hasattr(cls, "get_parser"):
130 group = parser.add_argument_group(base_suite)
131 cls.get_parser(group)
132
133 parser.add_argument("test", nargs="?", help=("Test to create."))
134 return parser
135
136
137 @Command(
138 "addtest",
139 category="testing",
140 description="Generate tests based on templates",
141 parser=create_parser_addtest,
142 )
143 def addtest(
144 command_context,
145 suite=None,
146 test=None,
147 doc=None,
148 overwrite=False,
149 editor=MISSING_ARG,
150 **kwargs,
151 ):
152
153 import addtest
154 from moztest.resolve import TEST_SUITES
155
156 if not suite and not test:
157 return create_parser_addtest().parse_args(["--help"])
158
159 if suite in SUITE_SYNONYMS:
160 suite = SUITE_SYNONYMS[suite]
161
162 if test:
163 if not overwrite and os.path.isfile(os.path.abspath(test)):
164 print("Error: can't generate a test that already exists:", test)
165 return 1
166
167 abs_test = os.path.abspath(test)
168 if doc is None:
169 doc = guess_doc(abs_test)
170 if suite is None:
171 guessed_suite, err = guess_suite(abs_test)
172 if err:
173 print(err)
174 return 1
175 suite = guessed_suite
176
177 else:
178 test = None
179 if doc is None:
180 doc = "html"
181
182 if not suite:
183 print(
184 "We couldn't automatically determine a suite. "
185 f"Please specify `--suite` with one of the following options:\n{ADD_TEST_SUPPORTED_SUITES}\n"
186 "If you'd like to add support to a new suite, please file a bug "
187 "blocking https://bugzilla.mozilla.org/show_bug.cgi?id=1540285."
188 )
189 return 1
190
191 if doc not in ADD_TEST_SUPPORTED_DOCS:
192 print(
193 "Error: invalid `doc`. Either pass in a test with a valid extension"
194 f"({ADD_TEST_SUPPORTED_DOCS}) or pass in the `doc` argument"
195 )
196 return 1
197
198 creator_cls = addtest.creator_for_suite(suite)
199
200 if creator_cls is None:
201 print(f"Sorry, `addtest` doesn't currently know how to add {suite}")
202 return 1
203
204 creator = creator_cls(command_context.topsrcdir, test, suite, doc, **kwargs)
205
206 creator.check_args()
207
208 paths = []
209 added_tests = False
210 for path, template in creator:
211 if not template:
212 continue
213 added_tests = True
214 if path:
215 paths.append(path)
216 print(f"Adding a test file at {path} (suite `{suite}`)")
217
218 try:
219 os.makedirs(os.path.dirname(path))
220 except OSError:
221 pass
222
223 with open(path, "w", newline="\n") as f:
224 f.write(template)
225 else:
226 # write to stdout if you passed only suite and doc and not a file path
227 print(template)
228
229 if not added_tests:
230 return 1
231
232 if test:
233 creator.update_manifest()
234
235 # Small hack, should really do this better
236 if suite.startswith("wpt-"):
237 suite = "web-platform-tests"
238
239 mach_command = TEST_SUITES[suite]["mach_command"]
240 print(
241 "Please make sure to add the new test to your commit. "
242 f"You can now run the test with:\n ./mach {mach_command} {test}"
243 )
244
245 if editor is not MISSING_ARG:
246 if editor is not None:
247 editor = editor
248 elif "VISUAL" in os.environ:
249 editor = os.environ["VISUAL"]
250 elif "EDITOR" in os.environ:
251 editor = os.environ["EDITOR"]
252 else:
253 print("Unable to determine editor; please specify a binary")
254 editor = None
255
256 proc = None
257 if editor:
258 import subprocess
259
260 proc = subprocess.Popen("%s %s" % (editor, " ".join(paths)), shell=True)
261
262 if proc:
263 proc.wait()
264
265 return 0
266
267
268 def guess_doc(abs_test):
269 filename = os.path.basename(abs_test)
270 return os.path.splitext(filename)[1].strip(".")
271
272
273 def guess_suite(abs_test):
274 # If you pass a abs_test, try to detect the type based on the name
275 # and folder. This detection can be skipped if you pass the `type` arg.
276 err = None
277 guessed_suite = None
278 parent = os.path.dirname(abs_test)
279 filename = os.path.basename(abs_test)
280
281 has_browser_ini = os.path.isfile(os.path.join(parent, "browser.ini"))
282 has_browser_toml = os.path.isfile(os.path.join(parent, "browser.toml"))
283 has_chrome_ini = os.path.isfile(os.path.join(parent, "chrome.ini"))
284 has_chrome_toml = os.path.isfile(os.path.join(parent, "chrome.toml"))
285 has_plain_ini = os.path.isfile(os.path.join(parent, "mochitest.ini"))
286 has_plain_toml = os.path.isfile(os.path.join(parent, "mochitest.toml"))
287 has_xpcshell_ini = os.path.isfile(os.path.join(parent, "xpcshell.ini"))
288 has_xpcshell_toml = os.path.isfile(os.path.join(parent, "xpcshell.toml"))
289
290 in_wpt_folder = abs_test.startswith(
291 os.path.abspath(os.path.join("testing", "web-platform"))
292 )
293
294 if in_wpt_folder:
295 guessed_suite = "web-platform-tests"
296 if "/css/" in abs_test:
297 guessed_suite = "web-platform-tests-reftest"
298 elif (
299 filename.startswith("test_")
300 and (has_xpcshell_ini or has_xpcshell_toml)
301 and guess_doc(abs_test) == "js"
302 ):
303 guessed_suite = "xpcshell"
304 else:
305 if filename.startswith("browser_") and (has_browser_ini or has_browser_toml):
306 guessed_suite = "mochitest-browser-chrome"
307 elif filename.startswith("test_"):
308 if (has_chrome_ini or has_chrome_toml) and (
309 has_plain_ini or has_plain_toml
310 ):
311 err = (
312 "Error: directory contains both a chrome.{ini|toml} and mochitest.{ini|toml}. "
313 "Please set --suite=mochitest-chrome or --suite=mochitest-plain."
314 )
315 elif has_chrome_ini or has_chrome_toml:
316 guessed_suite = "mochitest-chrome"
317 elif has_plain_ini or has_plain_toml:
318 guessed_suite = "mochitest-plain"
319 return guessed_suite, err
320
321
322 class MachTestRunner:
323 """Adapter for mach test to simplify it's import externally."""
324
325 def test(command_context, what, extra_args, **log_args):
326 return test(command_context, what, extra_args, **log_args)
327
328
329 @Command(
330 "test",
331 category="testing",
332 description="Run tests (detects the kind of test and runs it).",
333 parser=get_test_parser,
334 )
335 def test(command_context, what, extra_args, **log_args):
336 """Run tests from names or paths.
337
338 mach test accepts arguments specifying which tests to run. Each argument
339 can be:
340
341 * The path to a test file
342 * A directory containing tests
343 * A test suite name
344 * An alias to a test suite name (codes used on TreeHerder)
345 * path to a test manifest
346
347 When paths or directories are given, they are first resolved to test
348 files known to the build system.
349
350 If resolved tests belong to more than one test type/flavor/harness,
351 the harness for each relevant type/flavor will be invoked. e.g. if
352 you specify a directory with xpcshell and browser chrome mochitests,
353 both harnesses will be invoked.
354
355 Warning: `mach test` does not automatically re-build.
356 Please remember to run `mach build` when necessary.
357
358 EXAMPLES
359
360 Run all test files in the devtools/client/shared/redux/middleware/xpcshell/
361 directory:
362
363 `./mach test devtools/client/shared/redux/middleware/xpcshell/`
364
365 The below command prints a short summary of results instead of
366 the default more verbose output.
367 Do not forget the - (minus sign) after --log-grouped!
368
369 `./mach test --log-grouped - devtools/client/shared/redux/middleware/xpcshell/`
370
371 To learn more about arguments for each test type/flavor/harness, please run
372 `./mach <test-harness> --help`. For example, `./mach mochitest --help`.
373 """
374 from mozlog.commandline import setup_logging
375 from mozlog.handlers import StreamHandler
376 from moztest.resolve import TEST_SUITES, TestResolver, get_suite_definition
377
378 resolver = command_context._spawn(TestResolver)
379 run_suites, run_tests = resolver.resolve_metadata(what)
380
381 if not run_suites and not run_tests:
382 print(UNKNOWN_TEST)
383 return 1
384
385 if log_args.get("debugger", None):
386 import mozdebug
387
388 if not mozdebug.get_debugger_info(log_args.get("debugger")):
389 sys.exit(1)
390 extra_args_debugger_notation = "=".join(
391 ["--debugger", log_args.get("debugger")]
392 )
393 if extra_args:
394 extra_args.append(extra_args_debugger_notation)
395 else:
396 extra_args = [extra_args_debugger_notation]
397
398 # Create shared logger
399 format_args = {"level": command_context._mach_context.settings["test"]["level"]}
400 if not run_suites and len(run_tests) == 1:
401 format_args["verbose"] = True
402 format_args["compact"] = False
403
404 default_format = command_context._mach_context.settings["test"]["format"]
405 log = setup_logging(
406 "mach-test", log_args, {default_format: sys.stdout}, format_args
407 )
408 for handler in log.handlers:
409 if isinstance(handler, StreamHandler):
410 handler.formatter.inner.summary_on_shutdown = True
411
412 if log_args.get("custom_handler", None) is not None:
413 log.add_handler(log_args.get("custom_handler"))
414
415 status = None
416 for suite_name in run_suites:
417 suite = TEST_SUITES[suite_name]
418 kwargs = suite["kwargs"]
419 kwargs["log"] = log
420 kwargs.setdefault("subsuite", None)
421
422 if "mach_command" in suite:
423 res = command_context._mach_context.commands.dispatch(
424 suite["mach_command"],
425 command_context._mach_context,
426 argv=extra_args,
427 **kwargs,
428 )
429 if res:
430 status = res
431
432 buckets = {}
433 for test in run_tests:
434 key = (test["flavor"], test.get("subsuite", ""))
435 buckets.setdefault(key, []).append(test)
436
437 for (flavor, subsuite), tests in sorted(buckets.items()):
438 _, m = get_suite_definition(flavor, subsuite)
439 if "mach_command" not in m:
440 substr = f"-{subsuite}" if subsuite else ""
441 print(UNKNOWN_FLAVOR % (flavor, substr))
442 status = 1
443 continue
444
445 kwargs = dict(m["kwargs"])
446 kwargs["log"] = log
447 kwargs.setdefault("subsuite", None)
448
449 res = command_context._mach_context.commands.dispatch(
450 m["mach_command"],
451 command_context._mach_context,
452 argv=extra_args,
453 test_objects=tests,
454 **kwargs,
455 )
456 if res:
457 status = res
458
459 if not log.has_shutdown:
460 log.shutdown()
461 return status
462
463
464 @Command(
465 "cppunittest", category="testing", description="Run cpp unit tests (C++ tests)."
466 )
467 @CommandArgument(
468 "test_files",
469 nargs="*",
470 metavar="N",
471 help="Test to run. Can be specified as one or more files or "
472 "directories, or omitted. If omitted, the entire test suite is "
473 "executed.",
474 )
475 def run_cppunit_test(command_context, **params):
476 from mozlog import commandline
477
478 log = params.get("log")
479 if not log:
480 log = commandline.setup_logging("cppunittest", {}, {"tbpl": sys.stdout})
481
482 # See if we have crash symbols
483 symbols_path = os.path.join(command_context.distdir, "crashreporter-symbols")
484 if not os.path.isdir(symbols_path):
485 symbols_path = None
486
487 # If no tests specified, run all tests in main manifest
488 tests = params["test_files"]
489 if not tests:
490 tests = [os.path.join(command_context.distdir, "cppunittests")]
491 manifest_path = os.path.join(
492 command_context.topsrcdir, "testing", "cppunittest.toml"
493 )
494 else:
495 manifest_path = None
496
497 utility_path = command_context.bindir
498
499 if conditions.is_android(command_context):
500 from mozrunner.devices.android_device import (
501 InstallIntent,
502 verify_android_device,
503 )
504
505 verify_android_device(command_context, install=InstallIntent.NO)
506 return run_android_test(tests, symbols_path, manifest_path, log)
507
508 return run_desktop_test(
509 command_context, tests, symbols_path, manifest_path, utility_path, log
510 )
511
512
513 def run_desktop_test(
514 command_context, tests, symbols_path, manifest_path, utility_path, log
515 ):
516 import runcppunittests as cppunittests
517 from mozlog import commandline
518
519 parser = cppunittests.CPPUnittestOptions()
520 commandline.add_logging_group(parser)
521 options, args = parser.parse_args()
522
523 options.symbols_path = symbols_path
524 options.manifest_path = manifest_path
525 options.utility_path = utility_path
526 options.xre_path = command_context.bindir
527
528 try:
529 result = cppunittests.run_test_harness(options, tests)
530 except Exception as e:
531 log.error("Caught exception running cpp unit tests: %s" % str(e))
532 result = False
533 raise
534
535 return 0 if result else 1
536
537
538 def run_android_test(command_context, tests, symbols_path, manifest_path, log):
539 import remotecppunittests
540 from mozlog import commandline
541
542 parser = remotecppunittests.RemoteCPPUnittestOptions()
543 commandline.add_logging_group(parser)
544 options, args = parser.parse_args()
545
546 if not options.adb_path:
547 from mozrunner.devices.android_device import get_adb_path
548
549 options.adb_path = get_adb_path(command_context)
550 options.symbols_path = symbols_path
551 options.manifest_path = manifest_path
552 options.xre_path = command_context.bindir
553 options.local_lib = command_context.bindir.replace("bin", "fennec")
554 for file in os.listdir(os.path.join(command_context.topobjdir, "dist")):
555 if file.endswith(".apk") and file.startswith("fennec"):
556 options.local_apk = os.path.join(command_context.topobjdir, "dist", file)
557 log.info("using APK: " + options.local_apk)
558 break
559
560 try:
561 result = remotecppunittests.run_test_harness(options, tests)
562 except Exception as e:
563 log.error("Caught exception running cpp unit tests: %s" % str(e))
564 result = False
565 raise
566
567 return 0 if result else 1
568
569
570 def executable_name(name):
571 return name + ".exe" if sys.platform.startswith("win") else name
572
573
574 @Command(
575 "jstests",
576 category="testing",
577 description="Run SpiderMonkey JS tests in the JS shell.",
578 ok_if_tests_disabled=True,
579 )
580 @CommandArgument("--shell", help="The shell to be used")
581 @CommandArgument(
582 "params",
583 nargs=argparse.REMAINDER,
584 help="Extra arguments to pass down to the test harness.",
585 )
586 def run_jstests(command_context, shell, params):
587 import subprocess
588
589 command_context.virtualenv_manager.ensure()
590 python = command_context.virtualenv_manager.python_path
591
592 js = shell or os.path.join(command_context.bindir, executable_name("js"))
593 jstest_cmd = [
594 python,
595 os.path.join(command_context.topsrcdir, "js", "src", "tests", "jstests.py"),
596 js,
597 ] + params
598
599 return subprocess.call(jstest_cmd)
600
601
602 @Command(
603 "jit-test",
604 category="testing",
605 description="Run SpiderMonkey jit-tests in the JS shell.",
606 ok_if_tests_disabled=True,
607 )
608 @CommandArgument("--shell", help="The shell to be used")
609 @CommandArgument(
610 "--cgc",
611 action="store_true",
612 default=False,
613 help="Run with the SM(cgc) job's env vars",
614 )
615 @CommandArgument(
616 "params",
617 nargs=argparse.REMAINDER,
618 help="Extra arguments to pass down to the test harness.",
619 )
620 def run_jittests(command_context, shell, cgc, params):
621 import subprocess
622
623 command_context.virtualenv_manager.ensure()
624 python = command_context.virtualenv_manager.python_path
625
626 js = shell or os.path.join(command_context.bindir, executable_name("js"))
627 jittest_cmd = [
628 python,
629 os.path.join(command_context.topsrcdir, "js", "src", "jit-test", "jit_test.py"),
630 js,
631 ] + params
632
633 env = os.environ.copy()
634 if cgc:
635 env["JS_GC_ZEAL"] = "IncrementalMultipleSlices"
636
637 return subprocess.call(jittest_cmd, env=env)
638
639
640 @Command("jsapi-tests", category="testing", description="Run SpiderMonkey JSAPI tests.")
641 @CommandArgument(
642 "--list",
643 action="store_true",
644 default=False,
645 help="List all tests",
646 )
647 @CommandArgument(
648 "--frontend-only",
649 action="store_true",
650 default=False,
651 help="Run tests for frontend-only APIs, with light-weight entry point",
652 )
653 @CommandArgument(
654 "test_name",
655 nargs="?",
656 metavar="N",
657 help="Test to run. Can be a prefix or omitted. If "
658 "omitted, the entire test suite is executed.",
659 )
660 def run_jsapitests(command_context, list=False, frontend_only=False, test_name=None):
661 import subprocess
662
663 jsapi_tests_cmd = [
664 os.path.join(command_context.bindir, executable_name("jsapi-tests"))
665 ]
666 if list:
667 jsapi_tests_cmd.append("--list")
668 if frontend_only:
669 jsapi_tests_cmd.append("--frontend-only")
670 if test_name:
671 jsapi_tests_cmd.append(test_name)
672
673 test_env = os.environ.copy()
674 test_env["TOPSRCDIR"] = command_context.topsrcdir
675
676 result = subprocess.call(jsapi_tests_cmd, env=test_env)
677 if result != 0:
678 print(f"jsapi-tests failed, exit code {result}")
679 return result
680
681
682 def run_check_js_msg(command_context):
683 import subprocess
684
685 command_context.virtualenv_manager.ensure()
686 python = command_context.virtualenv_manager.python_path
687
688 check_cmd = [
689 python,
690 os.path.join(command_context.topsrcdir, "config", "check_js_msg_encoding.py"),
691 ]
692
693 return subprocess.call(check_cmd)
694
695
696 def get_jsshell_parser():
697 from jsshell.benchmark import get_parser
698
699 return get_parser()
700
701
702 @Command(
703 "jsshell-bench",
704 category="testing",
705 parser=get_jsshell_parser,
706 description="Run benchmarks in the SpiderMonkey JS shell.",
707 )
708 def run_jsshelltests(command_context, **kwargs):
709 from jsshell import benchmark
710
711 return benchmark.run(**kwargs)
712
713
714 @Command(
715 "test-info", category="testing", description="Display historical test results."
716 )
717 def test_info(command_context):
718 """
719 All functions implemented as subcommands.
720 """
721
722
723 @SubCommand(
724 "test-info",
725 "tests",
726 description="Display historical test result summary for named tests.",
727 )
728 @CommandArgument("test_names", nargs=argparse.REMAINDER, help="Test(s) of interest.")
729 @CommandArgument(
730 "--start",
731 default=(date.today() - timedelta(7)).strftime("%Y-%m-%d"),
732 help="Start date (YYYY-MM-DD)",
733 )
734 @CommandArgument(
735 "--end", default=date.today().strftime("%Y-%m-%d"), help="End date (YYYY-MM-DD)"
736 )
737 @CommandArgument(
738 "--show-info",
739 action="store_true",
740 help="Retrieve and display general test information.",
741 )
742 @CommandArgument(
743 "--show-bugs",
744 action="store_true",
745 help="Retrieve and display related Bugzilla bugs.",
746 )
747 @CommandArgument("--verbose", action="store_true", help="Enable debug logging.")
748 def test_info_tests(
749 command_context,
750 test_names,
751 start,
752 end,
753 show_info,
754 show_bugs,
755 verbose,
756 ):
757 import testinfo
758
759 ti = testinfo.TestInfoTests(verbose)
760 ti.report(
761 test_names,
762 start,
763 end,
764 show_info,
765 show_bugs,
766 )
767
768
769 @SubCommand(
770 "test-info",
771 "report",
772 description="Generate a json report of test manifests and/or tests "
773 "categorized by Bugzilla component and optionally filtered "
774 "by path, component, and/or manifest annotations.",
775 )
776 @CommandArgument(
777 "--components",
778 default=None,
779 help="Comma-separated list of Bugzilla components."
780 " eg. Testing::General,Core::WebVR",
781 )
782 @CommandArgument(
783 "--flavor",
784 help='Limit results to tests of the specified flavor (eg. "xpcshell").',
785 )
786 @CommandArgument(
787 "--subsuite",
788 help='Limit results to tests of the specified subsuite (eg. "devtools").',
789 )
790 @CommandArgument(
791 "paths", nargs=argparse.REMAINDER, help="File system paths of interest."
792 )
793 @CommandArgument(
794 "--show-manifests",
795 action="store_true",
796 help="Include test manifests in report.",
797 )
798 @CommandArgument(
799 "--show-tests", action="store_true", help="Include individual tests in report."
800 )
801 @CommandArgument(
802 "--show-summary", action="store_true", help="Include summary in report."
803 )
804 @CommandArgument(
805 "--show-annotations",
806 action="store_true",
807 help="Include list of manifest annotation conditions in report.",
808 )
809 @CommandArgument(
810 "--show-testruns",
811 action="store_true",
812 help="Include total number of runs the test has if there are failures.",
813 )
814 @CommandArgument(
815 "--filter-values",
816 help="Comma-separated list of value regular expressions to filter on; "
817 "displayed tests contain all specified values.",
818 )
819 @CommandArgument(
820 "--filter-keys",
821 help="Comma-separated list of test keys to filter on, "
822 'like "skip-if"; only these fields will be searched '
823 "for filter-values.",
824 )
825 @CommandArgument(
826 "--no-component-report",
827 action="store_false",
828 dest="show_components",
829 default=True,
830 help="Do not categorize by bugzilla component.",
831 )
832 @CommandArgument("--output-file", help="Path to report file.")
833 @CommandArgument("--runcounts-input-file", help="Optional path to report file.")
834 @CommandArgument(
835 "--config-matrix-output-file",
836 help="Path to report the config matrix for each manifest.",
837 )
838 @CommandArgument("--verbose", action="store_true", help="Enable debug logging.")
839 @CommandArgument(
840 "--start",
841 default=(date.today() - timedelta(30)).strftime("%Y-%m-%d"),
842 help="Start date (YYYY-MM-DD)",
843 )
844 @CommandArgument(
845 "--end", default=date.today().strftime("%Y-%m-%d"), help="End date (YYYY-MM-DD)"
846 )
847 def test_report(
848 command_context,
849 components,
850 flavor,
851 subsuite,
852 paths,
853 show_manifests,
854 show_tests,
855 show_summary,
856 show_annotations,
857 filter_values,
858 filter_keys,
859 show_components,
860 output_file,
861 verbose,
862 start,
863 end,
864 show_testruns,
865 runcounts_input_file,
866 config_matrix_output_file,
867 ):
868 import testinfo
869 from mozbuild import build_commands
870
871 try:
872 command_context.config_environment
873 except BuildEnvironmentNotFoundException:
874 print("Looks like configure has not run yet, running it now...")
875 build_commands.configure(command_context)
876
877 ti = testinfo.TestInfoReport(verbose)
878 ti.report(
879 components,
880 flavor,
881 subsuite,
882 paths,
883 show_manifests,
884 show_tests,
885 show_summary,
886 show_annotations,
887 filter_values,
888 filter_keys,
889 show_components,
890 output_file,
891 start,
892 end,
893 show_testruns,
894 runcounts_input_file,
895 config_matrix_output_file,
896 )
897
898
899 @SubCommand(
900 "test-info",
901 "report-diff",
902 description='Compare two reports generated by "test-info reports".',
903 )
904 @CommandArgument(
905 "--before",
906 default=None,
907 help="The first (earlier) report file; path to local file or url.",
908 )
909 @CommandArgument(
910 "--after", help="The second (later) report file; path to local file or url."
911 )
912 @CommandArgument(
913 "--output-file",
914 help="Path to report file to be written. If not specified, report"
915 "will be written to standard output.",
916 )
917 @CommandArgument("--verbose", action="store_true", help="Enable debug logging.")
918 def test_report_diff(command_context, before, after, output_file, verbose):
919 import testinfo
920
921 ti = testinfo.TestInfoReport(verbose)
922 ti.report_diff(before, after, output_file)
923
924
925 @SubCommand(
926 "test-info",
927 "testrun-report",
928 description="Generate report of number of runs for each test group (manifest)",
929 )
930 @CommandArgument("--output-file", help="Path to report file.")
931 def test_info_testrun_report(command_context, output_file):
932 import json
933
934 import testinfo
935
936 ti = testinfo.TestInfoReport(verbose=True)
937 if os.environ.get("GECKO_HEAD_REPOSITORY", "") in [
938 "https://hg.mozilla.org/mozilla-central",
939 "https://hg.mozilla.org/try",
940 ]:
941 runcounts = ti.get_runcounts()
942 if output_file:
943 output_file = os.path.abspath(output_file)
944 output_dir = os.path.dirname(output_file)
945 if not os.path.isdir(output_dir):
946 os.makedirs(output_dir)
947 with open(output_file, "w") as f:
948 json.dump(runcounts, f)
949 else:
950 print(runcounts)
951
952
953 @SubCommand(
954 "test-info",
955 "failure-report",
956 description="Display failure line groupings and frequencies for "
957 "single tracking intermittent bugs.",
958 )
959 @CommandArgument(
960 "--start",
961 default=(date.today() - timedelta(30)).strftime("%Y-%m-%d"),
962 help="Start date (YYYY-MM-DD)",
963 )
964 @CommandArgument(
965 "--end", default=date.today().strftime("%Y-%m-%d"), help="End date (YYYY-MM-DD)"
966 )
967 @CommandArgument(
968 "--bugid",
969 default=None,
970 help="bugid for treeherder intermittent failures data query.",
971 )
972 def test_info_failures(
973 command_context,
974 start,
975 end,
976 bugid,
977 ):
978 # bugid comes in as a string, we need an int:
979 try:
980 bugid = int(bugid)
981 except ValueError:
982 bugid = None
983 if not bugid:
984 print("Please enter a valid bugid (i.e. '1760132')")
985 return
986
987 # get bug info
988 url = (
989 "https://bugzilla.mozilla.org/rest/bug?include_fields=summary,depends_on&id=%s"
990 % bugid
991 )
992 r = requests.get(url, headers={"User-agent": "mach-test-info/1.0"})
993 if r.status_code != 200:
994 print("%s error retrieving url: %s" % (r.status_code, url))
995
996 data = r.json()
997 if not data:
998 print("unable to get bugzilla information for %s" % bugid)
999 return
1000
1001 summary = data["bugs"][0]["summary"]
1002 parts = summary.split("|")
1003 if not summary.endswith("single tracking bug") or len(parts) != 2:
1004 print("this query only works with single tracking bugs")
1005 return
1006
1007 # get depends_on bugs:
1008 buglist = [bugid]
1009 if "depends_on" in data["bugs"][0]:
1010 buglist.extend(data["bugs"][0]["depends_on"])
1011
1012 testname = parts[0].strip().split(" ")[-1]
1013
1014 # now query treeherder to get details about annotations
1015 data = []
1016 for b in buglist:
1017 url = "https://treeherder.mozilla.org/api/failuresbybug/"
1018 url += "?startday=%s&endday=%s&tree=trunk&bug=%s" % (start, end, b)
1019 r = requests.get(url, headers={"User-agent": "mach-test-info/1.0"})
1020 r.raise_for_status()
1021
1022 bdata = r.json()
1023 data.extend(bdata)
1024
1025 if len(data) == 0:
1026 print("no failures were found for given bugid, please ensure bug is")
1027 print("accessible via: https://treeherder.mozilla.org/intermittent-failures")
1028 return
1029
1030 # query VCS to get current list of variants:
1031 import yaml
1032
1033 url = "https://hg.mozilla.org/mozilla-central/raw-file/tip/taskcluster/kinds/test/variants.yml"
1034 r = requests.get(url, headers={"User-agent": "mach-test-info/1.0"})
1035 variants = yaml.safe_load(r.text)
1036
1037 print(
1038 "\nQuerying data for bug %s annotated from %s to %s on trunk.\n\n"
1039 % (buglist, start, end)
1040 )
1041 jobs = {}
1042 lines = {}
1043 for failure in data:
1044 # config = platform/buildtype
1045 # testsuite (<suite>[-variant][-<chunk>])
1046 # lines - group by patterns that contain test name
1047 config = "%s/%s" % (failure["platform"], failure["build_type"])
1048
1049 variant = ""
1050 suite = ""
1051 varpos = len(failure["test_suite"])
1052 for v in variants.keys():
1053 var = "-%s" % variants[v]["suffix"]
1054 if var in failure["test_suite"]:
1055 if failure["test_suite"].find(var) < varpos:
1056 variant = var
1057
1058 if variant:
1059 suite = failure["test_suite"].split(variant)[0]
1060
1061 parts = failure["test_suite"].split("-")
1062 try:
1063 int(parts[-1])
1064 suite = "-".join(parts[:-1])
1065 except ValueError:
1066 pass # if this works, then the last '-X' is a number :)
1067
1068 if suite == "":
1069 print("Error: failure to find variant in %s" % failure["test_suite"])
1070
1071 job = "%s-%s%s" % (config, suite, variant)
1072 if job not in jobs.keys():
1073 jobs[job] = 0
1074 jobs[job] += 1
1075
1076 # lines - sum(hash) of all lines where we match testname
1077 hvalue = 0
1078 for line in failure["lines"]:
1079 if len(line.split(testname)) <= 1:
1080 continue
1081 # strip off timestamp and mozharness status
1082 parts = line.split("TEST-UNEXPECTED")
1083 l = "TEST-UNEXPECTED%s" % parts[-1]
1084
1085 # only keep 25 characters of the failure, often longer is random numbers
1086 parts = l.split(testname)
1087 l = "%s%s%s" % (parts[0], testname, parts[1][:25])
1088
1089 hvalue += hash(l)
1090
1091 if not failure["lines"]:
1092 hvalue = 1
1093
1094 if not hvalue:
1095 continue
1096
1097 if hvalue not in lines.keys():
1098 lines[hvalue] = {"lines": failure["lines"], "config": []}
1099 lines[hvalue]["config"].append(job)
1100
1101 for h in lines.keys():
1102 print("%s errors with:" % (len(lines[h]["config"])))
1103 for l in lines[h]["lines"]:
1104 print(l)
1105 else:
1106 print(
1107 "... no failure lines recorded in"
1108 " https://treeherder.mozilla.org/intermittent-failures ..."
1109 )
1110
1111 for job in jobs:
1112 count = len([x for x in lines[h]["config"] if x == job])
1113 if count > 0:
1114 print(" %s: %s" % (job, count))
1115 print("")
1116
1117
1118 @Command(
1119 "rusttests",
1120 category="testing",
1121 conditions=[conditions.is_non_artifact_build],
1122 description="Run rust unit tests (via cargo test).",
1123 )
1124 def run_rusttests(command_context, **kwargs):
1125 return command_context._mach_context.commands.dispatch(
1126 "build",
1127 command_context._mach_context,
1128 what=["pre-export", "export", "recurse_rusttests"],
1129 )
1130
1131
1132 @Command(
1133 "fluent-migration-test",
1134 category="testing",
1135 description="Test Fluent migration recipes.",
1136 )
1137 @CommandArgument("test_paths", nargs="*", metavar="N", help="Recipe paths to test.")
1138 def run_migration_tests(command_context, test_paths=None, **kwargs):
1139 if not test_paths:
1140 test_paths = []
1141 command_context.activate_virtualenv()
1142 from test_fluent_migrations import fmt
1143
1144 rv = 0
1145 with_context = []
1146 for to_test in test_paths:
1147 try:
1148 context = fmt.inspect_migration(to_test)
1149 for issue in context["issues"]:
1150 command_context.log(
1151 logging.ERROR,
1152 "fluent-migration-test",
1153 {
1154 "error": issue["msg"],
1155 "file": to_test,
1156 },
1157 "ERROR in {file}: {error}",
1158 )
1159 if context["issues"]:
1160 continue
1161 with_context.append(
1162 {
1163 "to_test": to_test,
1164 "references": context["references"],
1165 }
1166 )
1167 except Exception as e:
1168 command_context.log(
1169 logging.ERROR,
1170 "fluent-migration-test",
1171 {"error": str(e), "file": to_test},
1172 "ERROR in {file}: {error}",
1173 )
1174 rv |= 1
1175 obj_dir, repo_dir = fmt.prepare_directories(command_context)
1176 for context in with_context:
1177 rv |= fmt.test_migration(command_context, obj_dir, repo_dir, **context)
1178 return rv
1179
1180
1181 @Command(
1182 "manifest",
1183 category="testing",
1184 description="Manifest operations",
1185 virtualenv_name="manifest",
1186 )
1187 def manifest(_command_context):
1188 """
1189 All functions implemented as subcommands.
1190 """
1191
1192
1193 @SubCommand(
1194 "manifest",
1195 "skip-fails",
1196 description="Update manifests to skip failing tests",
1197 )
1198 @CommandArgument("try_url", nargs=1, help="Treeherder URL for try (please use quotes)")
1199 @CommandArgument(
1200 "-b",
1201 "--bugzilla",
1202 default=None,
1203 dest="bugzilla",
1204 help="Bugzilla instance (or disable)",
1205 )
1206 @CommandArgument(
1207 "-m", "--meta-bug-id", default=None, dest="meta_bug_id", help="Meta Bug id"
1208 )
1209 @CommandArgument(
1210 "-s",
1211 "--turbo",
1212 action="store_true",
1213 dest="turbo",
1214 help="Skip all secondary failures",
1215 )
1216 @CommandArgument(
1217 "-t", "--save-tasks", default=None, dest="save_tasks", help="Save tasks to file"
1218 )
1219 @CommandArgument(
1220 "-T", "--use-tasks", default=None, dest="use_tasks", help="Use tasks from file"
1221 )
1222 @CommandArgument(
1223 "-f",
1224 "--save-failures",
1225 default=None,
1226 dest="save_failures",
1227 help="Save failures to file",
1228 )
1229 @CommandArgument(
1230 "-F",
1231 "--use-failures",
1232 default=None,
1233 dest="use_failures",
1234 help="Use failures from file",
1235 )
1236 @CommandArgument(
1237 "-M",
1238 "--max-failures",
1239 default=-1,
1240 dest="max_failures",
1241 help="Maximum number of failures to skip (-1 == no limit)",
1242 )
1243 @CommandArgument("-v", "--verbose", action="store_true", help="Verbose mode")
1244 @CommandArgument(
1245 "-d",
1246 "--dry-run",
1247 action="store_true",
1248 help="Determine manifest changes, but do not write them",
1249 )
1250 @CommandArgument(
1251 "-I",
1252 "--implicit-vars",
1253 action="store_true",
1254 help="Use implicit variables in reftest manifests",
1255 )
1256 @CommandArgument(
1257 "-n",
1258 "--new-version",
1259 dest="new_version",
1260 help="New version to use for annotations",
1261 )
1262 def skipfails(
1263 command_context,
1264 try_url,
1265 bugzilla=None,
1266 meta_bug_id=None,
1267 turbo=False,
1268 save_tasks=None,
1269 use_tasks=None,
1270 save_failures=None,
1271 use_failures=None,
1272 max_failures=-1,
1273 verbose=False,
1274 dry_run=False,
1275 implicit_vars=False,
1276 new_version=None,
1277 ):
1278 from skipfails import Skipfails
1279
1280 if meta_bug_id is not None:
1281 try:
1282 meta_bug_id = int(meta_bug_id)
1283 except ValueError:
1284 meta_bug_id = None
1285
1286 if max_failures is not None:
1287 try:
1288 max_failures = int(max_failures)
1289 except ValueError:
1290 max_failures = -1
1291 else:
1292 max_failures = -1
1293
1294 Skipfails(
1295 command_context,
1296 try_url,
1297 verbose,
1298 bugzilla,
1299 dry_run,
1300 turbo,
1301 implicit_vars,
1302 new_version,
1303 ).run(
1304 meta_bug_id,
1305 save_tasks,
1306 use_tasks,
1307 save_failures,
1308 use_failures,
1309 max_failures,
1310 )
1311
1312
1313 @SubCommand(
1314 "manifest",
1315 "clean-skip-fails",
1316 description="Update manifests to remove skip-if conditions for a specific platform. Only works for TOML manifests.",
1317 )
1318 @CommandArgument(
1319 "manifest_search_path",
1320 nargs=1,
1321 help="Path to the folder containing the manifests to update, or the path to a single manifest",
1322 )
1323 @CommandArgument(
1324 "-o",
1325 "--os",
1326 default=None,
1327 dest="os_name",
1328 help="OS to remove (linux, mac, win)",
1329 )
1330 @CommandArgument(
1331 "-s",
1332 "--os_version",
1333 default=None,
1334 dest="os_version",
1335 help="Version of the OS to remove (eg: 18.04 for linux)",
1336 )
1337 @CommandArgument(
1338 "-p",
1339 "--processor",
1340 default=None,
1341 dest="processor",
1342 help="Type of processor architecture to remove (eg: x86)",
1343 )
1344 def clean_skipfails(
1345 command_context,
1346 manifest_search_path: List[str],
1347 os_name: Optional[str] = None,
1348 os_version: Optional[str] = None,
1349 processor: Optional[str] = None,
1350 ):
1351 CleanSkipfails(
1352 command_context, manifest_search_path[0], os_name, os_version, processor
1353 ).run()