blob: 8695a623ea51f7e43fd004293997677c53bbb51b [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
6"""Wrapper to execute pytest inside the chromite virtualenv."""
7
8from __future__ import print_function
9
Chris McDonald3c557392020-03-31 13:41:46 -060010import os
Chris McDonald17d86b32020-03-18 17:28:43 -060011import sys
12
13import pytest # pylint: disable=import-error
14
Mike Frysingerd7af8462020-11-11 03:44:54 -050015from chromite.lib import commandline
Chris McDonald3c557392020-03-31 13:41:46 -060016from chromite.lib import constants
17from chromite.lib import cros_build_lib
18from chromite.lib import gs
Chris McDonald5d1af6a2020-04-21 08:00:15 -060019from chromite.lib import cros_logging as logging
Chris McDonald3c557392020-03-31 13:41:46 -060020from chromite.lib import namespaces
21
Chris McDonald17d86b32020-03-18 17:28:43 -060022
23def main(argv):
Chris McDonald5d1af6a2020-04-21 08:00:15 -060024 parser = get_parser()
Mike Frysingerd7af8462020-11-11 03:44:54 -050025 opts = parser.parse_args()
Mike Frysingera819cb32021-04-01 00:55:10 -040026 opts.Freeze()
Mike Frysingerd7af8462020-11-11 03:44:54 -050027
28 pytest_args = opts.pytest_args
29
Chris McDonald5d1af6a2020-04-21 08:00:15 -060030 if opts.quick:
Chris McDonald653510e2020-05-01 17:15:16 -060031 if not cros_build_lib.IsInsideChroot() and opts.chroot:
Mike Frysinger968c1142020-05-09 00:37:56 -040032 logging.warning('Tests start up faster when run from inside the chroot.')
Chris McDonald5d1af6a2020-04-21 08:00:15 -060033
Chris McDonald653510e2020-05-01 17:15:16 -060034 if opts.chroot:
35 ensure_chroot_exists()
36 re_execute_inside_chroot(argv)
37 else:
Chris McDonaldcdfd1132020-05-12 07:09:51 -060038 pytest_args += ['--no-chroot']
Chris McDonald3c557392020-03-31 13:41:46 -060039
40 # This is a cheesy hack to make sure gsutil is populated in the cache before
41 # we run tests. This is a partial workaround for crbug.com/468838.
42 gs.GSContext.GetDefaultGSUtilBin()
43
Chris McDonald5d1af6a2020-04-21 08:00:15 -060044 if opts.quick:
45 logging.info('Skipping test namespacing due to --quickstart.')
46 # Default to running in a single process under --quickstart. User args can
47 # still override this.
48 pytest_args = ['-n', '0'] + pytest_args
49 else:
50 # Namespacing is enabled by default because tests may break each other or
51 # interfere with parts of the running system if not isolated in a namespace.
52 # Disabling namespaces is not recommended for general use.
53 re_execute_with_namespace([sys.argv[0]] + argv)
Chris McDonald3c557392020-03-31 13:41:46 -060054
Mike Frysinger55919ef2021-04-01 00:55:39 -040055 # Check the environment. https://crbug.com/1015450
56 st = os.stat('/')
57 if st.st_mode & 0o7777 != 0o755:
58 cros_build_lib.Die(
59 f'The root directory has broken permissions: {st.st_mode:o}\n'
60 'Fix with: sudo chmod 755 /')
61 if st.st_uid or st.st_gid:
62 cros_build_lib.Die(
63 f'The root directory has broken ownership: {st.st_uid}:{st.st_gid}'
64 ' (should be 0:0)\nFix with: sudo chown 0:0 /')
65
Chris McDonald5d1af6a2020-04-21 08:00:15 -060066 sys.exit(pytest.main(pytest_args))
Chris McDonald3c557392020-03-31 13:41:46 -060067
68
69def re_execute_with_namespace(argv, network=False):
70 """Re-execute as root so we can unshare resources."""
71 if os.geteuid() != 0:
72 cmd = [
73 'sudo',
74 'HOME=%s' % os.environ['HOME'],
75 'PATH=%s' % os.environ['PATH'],
76 '--',
77 ] + argv
78 os.execvp(cmd[0], cmd)
79 else:
Chris McDonald3c557392020-03-31 13:41:46 -060080 namespaces.SimpleUnshare(net=not network, pid=True)
81 # We got our namespaces, so switch back to the user to run the tests.
82 gid = int(os.environ.pop('SUDO_GID'))
83 uid = int(os.environ.pop('SUDO_UID'))
84 user = os.environ.pop('SUDO_USER')
85 os.initgroups(user, gid)
86 os.setresgid(gid, gid, gid)
87 os.setresuid(uid, uid, uid)
88 os.environ['USER'] = user
89
90
91def re_execute_inside_chroot(argv):
92 """Re-execute the test wrapper inside the chroot."""
Mike Frysinger6df594e2020-11-11 15:02:59 -050093 if cros_build_lib.IsInsideChroot():
94 return
95
96 target = os.path.join(constants.CHROMITE_DIR, 'scripts', 'run_pytest')
97 relpath = os.path.relpath(target, '.')
98 # If we're in the scripts dir, make sure we always have a relative path,
99 # otherwise cros_sdk will search $PATH and fail.
100 if os.path.sep not in relpath:
101 relpath = os.path.join('.', relpath)
Chris McDonald3c557392020-03-31 13:41:46 -0600102 cmd = [
103 'cros_sdk',
Mike Frysinger6df594e2020-11-11 15:02:59 -0500104 '--working-dir', '.',
Chris McDonald3c557392020-03-31 13:41:46 -0600105 '--',
Mike Frysinger6df594e2020-11-11 15:02:59 -0500106 relpath,
Chris McDonald3c557392020-03-31 13:41:46 -0600107 ]
Mike Frysinger6df594e2020-11-11 15:02:59 -0500108 os.execvp(cmd[0], cmd + argv)
Chris McDonald3c557392020-03-31 13:41:46 -0600109
110
111def ensure_chroot_exists():
112 """Ensure that a chroot exists for us to run tests in."""
113 chroot = os.path.join(constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR)
114 if not os.path.exists(chroot) and not cros_build_lib.IsInsideChroot():
115 cros_build_lib.run(['cros_sdk', '--create'])
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600116
117
118def get_parser():
119 """Build the parser for command line arguments."""
Mike Frysingerd7af8462020-11-11 03:44:54 -0500120 parser = commandline.ArgumentParser(
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600121 description=__doc__,
Mike Frysingerd7af8462020-11-11 03:44:54 -0500122 epilog='To see the help output for pytest:\n$ %(prog)s -- --help',
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600123 )
124 parser.add_argument(
125 '--quickstart',
126 dest='quick',
127 action='store_true',
128 help='Skip normal test sandboxing and namespacing for faster start up '
129 'time.',
130 )
Chris McDonald653510e2020-05-01 17:15:16 -0600131 parser.add_argument(
132 '--no-chroot',
133 dest='chroot',
134 action='store_false',
135 help="Don't initialize or enter a chroot for the test invocation. May "
136 'cause tests to unexpectedly fail!',
137 )
Mike Frysingerd7af8462020-11-11 03:44:54 -0500138 parser.add_argument(
139 'pytest_args',
140 metavar='pytest arguments',
141 nargs='*',
142 help='Arguments to pass down to pytest (use -- to help separate)',
143 )
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600144 return parser