blob: 406866f79ba6d194b001aedbdd74a1e2314494eb [file] [log] [blame]
Chris McDonald17d86b32020-03-18 17:28:43 -06001# -*- coding: utf-8 -*-
2# Copyright 2020 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Mike Frysinger4975e5a2021-04-13 17:06:09 -04006"""Chromite main test runner.
7
8Run the specified tests. If none are specified, we'll scan the
9tree looking for tests to run and then only run the semi-fast ones.
10"""
Chris McDonald17d86b32020-03-18 17:28:43 -060011
12from __future__ import print_function
13
Chris McDonald3c557392020-03-31 13:41:46 -060014import os
Chris McDonald17d86b32020-03-18 17:28:43 -060015import sys
16
17import pytest # pylint: disable=import-error
18
Mike Frysingerd7af8462020-11-11 03:44:54 -050019from chromite.lib import commandline
Chris McDonald3c557392020-03-31 13:41:46 -060020from chromite.lib import constants
21from chromite.lib import cros_build_lib
22from chromite.lib import gs
Chris McDonald5d1af6a2020-04-21 08:00:15 -060023from chromite.lib import cros_logging as logging
Chris McDonald3c557392020-03-31 13:41:46 -060024from chromite.lib import namespaces
25
Chris McDonald17d86b32020-03-18 17:28:43 -060026
27def main(argv):
Chris McDonald5d1af6a2020-04-21 08:00:15 -060028 parser = get_parser()
Mike Frysingerd7af8462020-11-11 03:44:54 -050029 opts = parser.parse_args()
Mike Frysingera819cb32021-04-01 00:55:10 -040030 opts.Freeze()
Mike Frysingerd7af8462020-11-11 03:44:54 -050031
32 pytest_args = opts.pytest_args
33
Chris McDonald5d1af6a2020-04-21 08:00:15 -060034 if opts.quick:
Chris McDonald653510e2020-05-01 17:15:16 -060035 if not cros_build_lib.IsInsideChroot() and opts.chroot:
Mike Frysinger968c1142020-05-09 00:37:56 -040036 logging.warning('Tests start up faster when run from inside the chroot.')
Chris McDonald5d1af6a2020-04-21 08:00:15 -060037
Chris McDonald653510e2020-05-01 17:15:16 -060038 if opts.chroot:
39 ensure_chroot_exists()
40 re_execute_inside_chroot(argv)
41 else:
Chris McDonaldcdfd1132020-05-12 07:09:51 -060042 pytest_args += ['--no-chroot']
Chris McDonald3c557392020-03-31 13:41:46 -060043
Mike Frysingerc73c6b82021-04-22 00:07:54 -040044 if opts.network:
45 pytest_args += ['-m', 'not network_test or network_test']
46
Chris McDonald3c557392020-03-31 13:41:46 -060047 # This is a cheesy hack to make sure gsutil is populated in the cache before
48 # we run tests. This is a partial workaround for crbug.com/468838.
49 gs.GSContext.GetDefaultGSUtilBin()
50
Chris McDonald5d1af6a2020-04-21 08:00:15 -060051 if opts.quick:
52 logging.info('Skipping test namespacing due to --quickstart.')
53 # Default to running in a single process under --quickstart. User args can
54 # still override this.
55 pytest_args = ['-n', '0'] + pytest_args
56 else:
57 # Namespacing is enabled by default because tests may break each other or
58 # interfere with parts of the running system if not isolated in a namespace.
59 # Disabling namespaces is not recommended for general use.
Mike Frysingerc73c6b82021-04-22 00:07:54 -040060 re_execute_with_namespace([sys.argv[0]] + argv, network=opts.network)
Chris McDonald3c557392020-03-31 13:41:46 -060061
Mike Frysinger55919ef2021-04-01 00:55:39 -040062 # Check the environment. https://crbug.com/1015450
63 st = os.stat('/')
64 if st.st_mode & 0o7777 != 0o755:
65 cros_build_lib.Die(
66 f'The root directory has broken permissions: {st.st_mode:o}\n'
67 'Fix with: sudo chmod 755 /')
68 if st.st_uid or st.st_gid:
69 cros_build_lib.Die(
70 f'The root directory has broken ownership: {st.st_uid}:{st.st_gid}'
71 ' (should be 0:0)\nFix with: sudo chown 0:0 /')
72
Chris McDonald5d1af6a2020-04-21 08:00:15 -060073 sys.exit(pytest.main(pytest_args))
Chris McDonald3c557392020-03-31 13:41:46 -060074
75
76def re_execute_with_namespace(argv, network=False):
77 """Re-execute as root so we can unshare resources."""
78 if os.geteuid() != 0:
79 cmd = [
80 'sudo',
81 'HOME=%s' % os.environ['HOME'],
82 'PATH=%s' % os.environ['PATH'],
83 '--',
84 ] + argv
85 os.execvp(cmd[0], cmd)
86 else:
Chris McDonald3c557392020-03-31 13:41:46 -060087 namespaces.SimpleUnshare(net=not network, pid=True)
88 # We got our namespaces, so switch back to the user to run the tests.
89 gid = int(os.environ.pop('SUDO_GID'))
90 uid = int(os.environ.pop('SUDO_UID'))
91 user = os.environ.pop('SUDO_USER')
92 os.initgroups(user, gid)
93 os.setresgid(gid, gid, gid)
94 os.setresuid(uid, uid, uid)
95 os.environ['USER'] = user
96
97
98def re_execute_inside_chroot(argv):
99 """Re-execute the test wrapper inside the chroot."""
Mike Frysinger6df594e2020-11-11 15:02:59 -0500100 if cros_build_lib.IsInsideChroot():
101 return
102
Mike Frysinger4975e5a2021-04-13 17:06:09 -0400103 target = os.path.join(constants.CHROMITE_DIR, 'scripts', 'run_tests')
Mike Frysinger6df594e2020-11-11 15:02:59 -0500104 relpath = os.path.relpath(target, '.')
105 # If we're in the scripts dir, make sure we always have a relative path,
106 # otherwise cros_sdk will search $PATH and fail.
107 if os.path.sep not in relpath:
108 relpath = os.path.join('.', relpath)
Chris McDonald3c557392020-03-31 13:41:46 -0600109 cmd = [
110 'cros_sdk',
Mike Frysinger6df594e2020-11-11 15:02:59 -0500111 '--working-dir', '.',
Chris McDonald3c557392020-03-31 13:41:46 -0600112 '--',
Mike Frysinger6df594e2020-11-11 15:02:59 -0500113 relpath,
Chris McDonald3c557392020-03-31 13:41:46 -0600114 ]
Mike Frysinger6df594e2020-11-11 15:02:59 -0500115 os.execvp(cmd[0], cmd + argv)
Chris McDonald3c557392020-03-31 13:41:46 -0600116
117
118def ensure_chroot_exists():
119 """Ensure that a chroot exists for us to run tests in."""
120 chroot = os.path.join(constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR)
121 if not os.path.exists(chroot) and not cros_build_lib.IsInsideChroot():
122 cros_build_lib.run(['cros_sdk', '--create'])
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600123
124
125def get_parser():
126 """Build the parser for command line arguments."""
Mike Frysingerd7af8462020-11-11 03:44:54 -0500127 parser = commandline.ArgumentParser(
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600128 description=__doc__,
Mike Frysingerd7af8462020-11-11 03:44:54 -0500129 epilog='To see the help output for pytest:\n$ %(prog)s -- --help',
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600130 )
131 parser.add_argument(
132 '--quickstart',
133 dest='quick',
134 action='store_true',
135 help='Skip normal test sandboxing and namespacing for faster start up '
136 'time.',
137 )
Chris McDonald653510e2020-05-01 17:15:16 -0600138 parser.add_argument(
Mike Frysingerc73c6b82021-04-22 00:07:54 -0400139 '--network',
140 action='store_true',
141 help='Include network tests.',
142 )
143 parser.add_argument(
Chris McDonald653510e2020-05-01 17:15:16 -0600144 '--no-chroot',
145 dest='chroot',
146 action='store_false',
147 help="Don't initialize or enter a chroot for the test invocation. May "
148 'cause tests to unexpectedly fail!',
149 )
Mike Frysingerd7af8462020-11-11 03:44:54 -0500150 parser.add_argument(
151 'pytest_args',
152 metavar='pytest arguments',
153 nargs='*',
154 help='Arguments to pass down to pytest (use -- to help separate)',
155 )
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600156 return parser