blob: f7974d2e5727468beaa364695ff83450000d1e00 [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()
26
27 pytest_args = opts.pytest_args
28
Chris McDonald5d1af6a2020-04-21 08:00:15 -060029 if opts.quick:
Chris McDonald653510e2020-05-01 17:15:16 -060030 if not cros_build_lib.IsInsideChroot() and opts.chroot:
Mike Frysinger968c1142020-05-09 00:37:56 -040031 logging.warning('Tests start up faster when run from inside the chroot.')
Chris McDonald5d1af6a2020-04-21 08:00:15 -060032
Chris McDonald653510e2020-05-01 17:15:16 -060033 if opts.chroot:
34 ensure_chroot_exists()
35 re_execute_inside_chroot(argv)
36 else:
Chris McDonaldcdfd1132020-05-12 07:09:51 -060037 pytest_args += ['--no-chroot']
Chris McDonald3c557392020-03-31 13:41:46 -060038
39 # This is a cheesy hack to make sure gsutil is populated in the cache before
40 # we run tests. This is a partial workaround for crbug.com/468838.
41 gs.GSContext.GetDefaultGSUtilBin()
42
Chris McDonald5d1af6a2020-04-21 08:00:15 -060043 if opts.quick:
44 logging.info('Skipping test namespacing due to --quickstart.')
45 # Default to running in a single process under --quickstart. User args can
46 # still override this.
47 pytest_args = ['-n', '0'] + pytest_args
48 else:
49 # Namespacing is enabled by default because tests may break each other or
50 # interfere with parts of the running system if not isolated in a namespace.
51 # Disabling namespaces is not recommended for general use.
52 re_execute_with_namespace([sys.argv[0]] + argv)
Chris McDonald3c557392020-03-31 13:41:46 -060053
Chris McDonald5d1af6a2020-04-21 08:00:15 -060054 sys.exit(pytest.main(pytest_args))
Chris McDonald3c557392020-03-31 13:41:46 -060055
56
57def re_execute_with_namespace(argv, network=False):
58 """Re-execute as root so we can unshare resources."""
59 if os.geteuid() != 0:
60 cmd = [
61 'sudo',
62 'HOME=%s' % os.environ['HOME'],
63 'PATH=%s' % os.environ['PATH'],
64 '--',
65 ] + argv
66 os.execvp(cmd[0], cmd)
67 else:
Chris McDonald3c557392020-03-31 13:41:46 -060068 namespaces.SimpleUnshare(net=not network, pid=True)
69 # We got our namespaces, so switch back to the user to run the tests.
70 gid = int(os.environ.pop('SUDO_GID'))
71 uid = int(os.environ.pop('SUDO_UID'))
72 user = os.environ.pop('SUDO_USER')
73 os.initgroups(user, gid)
74 os.setresgid(gid, gid, gid)
75 os.setresuid(uid, uid, uid)
76 os.environ['USER'] = user
77
78
79def re_execute_inside_chroot(argv):
80 """Re-execute the test wrapper inside the chroot."""
Mike Frysinger6df594e2020-11-11 15:02:59 -050081 if cros_build_lib.IsInsideChroot():
82 return
83
84 target = os.path.join(constants.CHROMITE_DIR, 'scripts', 'run_pytest')
85 relpath = os.path.relpath(target, '.')
86 # If we're in the scripts dir, make sure we always have a relative path,
87 # otherwise cros_sdk will search $PATH and fail.
88 if os.path.sep not in relpath:
89 relpath = os.path.join('.', relpath)
Chris McDonald3c557392020-03-31 13:41:46 -060090 cmd = [
91 'cros_sdk',
Mike Frysinger6df594e2020-11-11 15:02:59 -050092 '--working-dir', '.',
Chris McDonald3c557392020-03-31 13:41:46 -060093 '--',
Mike Frysinger6df594e2020-11-11 15:02:59 -050094 relpath,
Chris McDonald3c557392020-03-31 13:41:46 -060095 ]
Mike Frysinger6df594e2020-11-11 15:02:59 -050096 os.execvp(cmd[0], cmd + argv)
Chris McDonald3c557392020-03-31 13:41:46 -060097
98
99def ensure_chroot_exists():
100 """Ensure that a chroot exists for us to run tests in."""
101 chroot = os.path.join(constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR)
102 if not os.path.exists(chroot) and not cros_build_lib.IsInsideChroot():
103 cros_build_lib.run(['cros_sdk', '--create'])
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600104
105
106def get_parser():
107 """Build the parser for command line arguments."""
Mike Frysingerd7af8462020-11-11 03:44:54 -0500108 parser = commandline.ArgumentParser(
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600109 description=__doc__,
Mike Frysingerd7af8462020-11-11 03:44:54 -0500110 epilog='To see the help output for pytest:\n$ %(prog)s -- --help',
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600111 )
112 parser.add_argument(
113 '--quickstart',
114 dest='quick',
115 action='store_true',
116 help='Skip normal test sandboxing and namespacing for faster start up '
117 'time.',
118 )
Chris McDonald653510e2020-05-01 17:15:16 -0600119 parser.add_argument(
120 '--no-chroot',
121 dest='chroot',
122 action='store_false',
123 help="Don't initialize or enter a chroot for the test invocation. May "
124 'cause tests to unexpectedly fail!',
125 )
Mike Frysingerd7af8462020-11-11 03:44:54 -0500126 parser.add_argument(
127 'pytest_args',
128 metavar='pytest arguments',
129 nargs='*',
130 help='Arguments to pass down to pytest (use -- to help separate)',
131 )
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600132 return parser