blob: 499a559460523bf3a65db99efc6a92c2c08b19cb [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
Chris McDonald3c557392020-03-31 13:41:46 -060015from chromite.lib import cgroups
Mike Frysingerd7af8462020-11-11 03:44:54 -050016from chromite.lib import commandline
Chris McDonald3c557392020-03-31 13:41:46 -060017from chromite.lib import constants
18from chromite.lib import cros_build_lib
19from chromite.lib import gs
Chris McDonald5d1af6a2020-04-21 08:00:15 -060020from chromite.lib import cros_logging as logging
Chris McDonald3c557392020-03-31 13:41:46 -060021from chromite.lib import namespaces
22
Chris McDonald17d86b32020-03-18 17:28:43 -060023
24def main(argv):
Chris McDonald5d1af6a2020-04-21 08:00:15 -060025 parser = get_parser()
Mike Frysingerd7af8462020-11-11 03:44:54 -050026 opts = parser.parse_args()
27
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
Chris McDonald5d1af6a2020-04-21 08:00:15 -060055 sys.exit(pytest.main(pytest_args))
Chris McDonald3c557392020-03-31 13:41:46 -060056
57
58def re_execute_with_namespace(argv, network=False):
59 """Re-execute as root so we can unshare resources."""
60 if os.geteuid() != 0:
61 cmd = [
62 'sudo',
63 'HOME=%s' % os.environ['HOME'],
64 'PATH=%s' % os.environ['PATH'],
65 '--',
66 ] + argv
67 os.execvp(cmd[0], cmd)
68 else:
69 cgroups.Cgroup.InitSystem()
70 namespaces.SimpleUnshare(net=not network, pid=True)
71 # We got our namespaces, so switch back to the user to run the tests.
72 gid = int(os.environ.pop('SUDO_GID'))
73 uid = int(os.environ.pop('SUDO_UID'))
74 user = os.environ.pop('SUDO_USER')
75 os.initgroups(user, gid)
76 os.setresgid(gid, gid, gid)
77 os.setresuid(uid, uid, uid)
78 os.environ['USER'] = user
79
80
81def re_execute_inside_chroot(argv):
82 """Re-execute the test wrapper inside the chroot."""
Mike Frysinger6df594e2020-11-11 15:02:59 -050083 if cros_build_lib.IsInsideChroot():
84 return
85
86 target = os.path.join(constants.CHROMITE_DIR, 'scripts', 'run_pytest')
87 relpath = os.path.relpath(target, '.')
88 # If we're in the scripts dir, make sure we always have a relative path,
89 # otherwise cros_sdk will search $PATH and fail.
90 if os.path.sep not in relpath:
91 relpath = os.path.join('.', relpath)
Chris McDonald3c557392020-03-31 13:41:46 -060092 cmd = [
93 'cros_sdk',
Mike Frysinger6df594e2020-11-11 15:02:59 -050094 '--working-dir', '.',
Chris McDonald3c557392020-03-31 13:41:46 -060095 '--',
Mike Frysinger6df594e2020-11-11 15:02:59 -050096 relpath,
Chris McDonald3c557392020-03-31 13:41:46 -060097 ]
Mike Frysinger6df594e2020-11-11 15:02:59 -050098 os.execvp(cmd[0], cmd + argv)
Chris McDonald3c557392020-03-31 13:41:46 -060099
100
101def ensure_chroot_exists():
102 """Ensure that a chroot exists for us to run tests in."""
103 chroot = os.path.join(constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR)
104 if not os.path.exists(chroot) and not cros_build_lib.IsInsideChroot():
105 cros_build_lib.run(['cros_sdk', '--create'])
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600106
107
108def get_parser():
109 """Build the parser for command line arguments."""
Mike Frysingerd7af8462020-11-11 03:44:54 -0500110 parser = commandline.ArgumentParser(
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600111 description=__doc__,
Mike Frysingerd7af8462020-11-11 03:44:54 -0500112 epilog='To see the help output for pytest:\n$ %(prog)s -- --help',
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600113 )
114 parser.add_argument(
115 '--quickstart',
116 dest='quick',
117 action='store_true',
118 help='Skip normal test sandboxing and namespacing for faster start up '
119 'time.',
120 )
Chris McDonald653510e2020-05-01 17:15:16 -0600121 parser.add_argument(
122 '--no-chroot',
123 dest='chroot',
124 action='store_false',
125 help="Don't initialize or enter a chroot for the test invocation. May "
126 'cause tests to unexpectedly fail!',
127 )
Mike Frysingerd7af8462020-11-11 03:44:54 -0500128 parser.add_argument(
129 'pytest_args',
130 metavar='pytest arguments',
131 nargs='*',
132 help='Arguments to pass down to pytest (use -- to help separate)',
133 )
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600134 return parser