blob: 3f75bd1a0e101ce822b280dbd5318984ab6a1040 [file] [log] [blame]
Mike Frysingerf1ba7ad2022-09-12 05:42:57 -04001# Copyright 2020 The ChromiumOS Authors
Chris McDonald17d86b32020-03-18 17:28:43 -06002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Mike Frysinger4975e5a2021-04-13 17:06:09 -04005"""Chromite main test runner.
6
7Run the specified tests. If none are specified, we'll scan the
8tree looking for tests to run and then only run the semi-fast ones.
Mike Frysinger2aa424f2021-07-19 21:37:29 -04009
10https://docs.pytest.org/en/latest/how-to/usage.html#specifying-tests-selecting-tests
11
12Examples:
13# Run all tests in a module.
14$ ./run_tests lib/osutils_unittest.py
15# Run a class of tests in a module.
16$ ./run_tests lib/osutils_unittest.py::TestOsutils
17# Run a single test.
18$ ./run_tests lib/osutils_unittest.py::TestOsutils::testIsSubPath
19# List all tests that'd be run.
20$ ./run_tests -- --collect-only
Mike Frysinger4975e5a2021-04-13 17:06:09 -040021"""
Chris McDonald17d86b32020-03-18 17:28:43 -060022
Chris McDonald59650c32021-07-20 15:29:28 -060023import logging
Chris McDonald3c557392020-03-31 13:41:46 -060024import os
Chris McDonald17d86b32020-03-18 17:28:43 -060025import sys
26
27import pytest # pylint: disable=import-error
28
Alex Klein9ea00b52021-02-24 14:47:22 -070029from chromite.api import compile_build_api_proto
Mike Frysingerd7af8462020-11-11 03:44:54 -050030from chromite.lib import commandline
Chris McDonald3c557392020-03-31 13:41:46 -060031from chromite.lib import constants
32from chromite.lib import cros_build_lib
33from chromite.lib import gs
34from chromite.lib import namespaces
35
Chris McDonald17d86b32020-03-18 17:28:43 -060036
37def main(argv):
Alex Klein1699fab2022-09-08 08:46:06 -060038 parser = get_parser()
39 opts = parser.parse_args()
40 opts.Freeze()
Mike Frysingerd7af8462020-11-11 03:44:54 -050041
Alex Klein1699fab2022-09-08 08:46:06 -060042 pytest_args = opts.pytest_args
Mike Frysingerd7af8462020-11-11 03:44:54 -050043
Alex Klein1699fab2022-09-08 08:46:06 -060044 if opts.quick:
45 if not cros_build_lib.IsInsideChroot() and opts.chroot:
46 logging.warning(
47 "Tests start up faster when run from inside the chroot."
48 )
Chris McDonald5d1af6a2020-04-21 08:00:15 -060049
Alex Klein1699fab2022-09-08 08:46:06 -060050 if opts.chroot:
51 ensure_chroot_exists()
52 re_execute_inside_chroot(argv)
53 else:
54 pytest_args += ["--no-chroot"]
Chris McDonald3c557392020-03-31 13:41:46 -060055
Alex Klein1699fab2022-09-08 08:46:06 -060056 if opts.network:
57 pytest_args += ["-m", "not network_test or network_test"]
Mike Frysingerc73c6b82021-04-22 00:07:54 -040058
Alex Klein1699fab2022-09-08 08:46:06 -060059 precache()
Chris McDonald3c557392020-03-31 13:41:46 -060060
Alex Klein1699fab2022-09-08 08:46:06 -060061 if opts.quick:
62 logging.info("Skipping test namespacing due to --quickstart.")
Alex Klein1699fab2022-09-08 08:46:06 -060063 else:
64 # Namespacing is enabled by default because tests may break each other or
65 # interfere with parts of the running system if not isolated in a namespace.
66 # Disabling namespaces is not recommended for general use.
67 namespaces.ReExecuteWithNamespace(
68 [sys.argv[0]] + argv, network=opts.network
69 )
Chris McDonald3c557392020-03-31 13:41:46 -060070
Mike Frysinger55aa3092023-02-15 09:43:22 -050071 jobs = opts.jobs
72 if jobs is None:
73 # Default to running in a single process under --quickstart. User args can
74 # still override this.
75 jobs = 0 if opts.quick else os.cpu_count()
76 pytest_args = ["-n", str(jobs)] + pytest_args
77
Alex Klein1699fab2022-09-08 08:46:06 -060078 # Check the environment. https://crbug.com/1015450
79 st = os.stat("/")
80 if st.st_mode & 0o007 != 0o005:
81 cros_build_lib.Die(
82 f"The root directory has broken permissions: {st.st_mode:o}\n"
83 "Fix with: sudo chmod o+rx-w /"
84 )
85 if st.st_uid or st.st_gid:
86 cros_build_lib.Die(
87 f"The root directory has broken ownership: {st.st_uid}:{st.st_gid}"
88 " (should be 0:0)\nFix with: sudo chown 0:0 /"
89 )
Mike Frysinger55919ef2021-04-01 00:55:39 -040090
Alex Klein1699fab2022-09-08 08:46:06 -060091 logging.debug("Running: pytest %s", cros_build_lib.CmdToStr(pytest_args))
92 sys.exit(pytest.main(pytest_args))
Chris McDonald3c557392020-03-31 13:41:46 -060093
94
Alex Klein9ea00b52021-02-24 14:47:22 -070095def precache():
Alex Klein1699fab2022-09-08 08:46:06 -060096 """Do some network-dependent stuff before we disallow network access."""
97 # This is a cheesy hack to make sure gsutil is populated in the cache before
98 # we run tests. This is a partial workaround for crbug.com/468838.
99 gs.GSContext.InitializeCache()
100 # Ensure protoc is installed for api/compile_build_api_proto_unittest.
101 compile_build_api_proto.InstallProtoc(
102 compile_build_api_proto.ProtocVersion.CHROMITE
103 )
Alex Klein9ea00b52021-02-24 14:47:22 -0700104
105
Chris McDonald3c557392020-03-31 13:41:46 -0600106def re_execute_inside_chroot(argv):
Alex Klein1699fab2022-09-08 08:46:06 -0600107 """Re-execute the test wrapper inside the chroot."""
108 if cros_build_lib.IsInsideChroot():
109 return
Mike Frysinger6df594e2020-11-11 15:02:59 -0500110
Alex Klein1699fab2022-09-08 08:46:06 -0600111 target = os.path.join(constants.CHROMITE_DIR, "scripts", "run_tests")
112 relpath = os.path.relpath(target, ".")
113 # If we're in the scripts dir, make sure we always have a relative path,
114 # otherwise cros_sdk will search $PATH and fail.
115 if os.path.sep not in relpath:
116 relpath = os.path.join(".", relpath)
117 cmd = [
118 "cros_sdk",
119 "--working-dir",
120 ".",
121 "--",
122 relpath,
123 ]
124 os.execvp(cmd[0], cmd + argv)
Chris McDonald3c557392020-03-31 13:41:46 -0600125
126
127def ensure_chroot_exists():
Alex Klein1699fab2022-09-08 08:46:06 -0600128 """Ensure that a chroot exists for us to run tests in."""
129 chroot = os.path.join(constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR)
130 if not os.path.exists(chroot) and not cros_build_lib.IsInsideChroot():
131 cros_build_lib.run(["cros_sdk", "--create"])
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600132
133
134def get_parser():
Alex Klein1699fab2022-09-08 08:46:06 -0600135 """Build the parser for command line arguments."""
136 parser = commandline.ArgumentParser(
137 description=__doc__,
138 epilog="To see the help output for pytest:\n$ %(prog)s -- --help",
139 )
140 parser.add_argument(
Mike Frysinger55aa3092023-02-15 09:43:22 -0500141 "-j",
142 "--jobs",
143 type=int,
144 default=None,
145 help="Number of tests to run in parallel.",
146 )
147 parser.add_argument(
Alex Klein1699fab2022-09-08 08:46:06 -0600148 "--quickstart",
149 dest="quick",
150 action="store_true",
151 help="Skip normal test sandboxing and namespacing for faster start up "
152 "time.",
153 )
154 parser.add_argument(
155 "--network",
156 action="store_true",
157 help="Include network tests.",
158 )
159 parser.add_argument(
160 "--no-chroot",
161 dest="chroot",
162 action="store_false",
163 help="Don't initialize or enter a chroot for the test invocation. May "
164 "cause tests to unexpectedly fail!",
165 )
166 parser.add_argument(
167 "pytest_args",
168 metavar="pytest arguments",
169 nargs="*",
170 help="Arguments to pass down to pytest (use -- to help separate)",
171 )
172 return parser