blob: 53fdda7ee9ca1cb15d0225ee01dae442d8c39349 [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:
38 os.chdir(constants.CHROMITE_DIR)
Chris McDonaldcdfd1132020-05-12 07:09:51 -060039 pytest_args += ['--no-chroot']
Chris McDonald3c557392020-03-31 13:41:46 -060040
41 # This is a cheesy hack to make sure gsutil is populated in the cache before
42 # we run tests. This is a partial workaround for crbug.com/468838.
43 gs.GSContext.GetDefaultGSUtilBin()
44
Chris McDonald5d1af6a2020-04-21 08:00:15 -060045 if opts.quick:
46 logging.info('Skipping test namespacing due to --quickstart.')
47 # Default to running in a single process under --quickstart. User args can
48 # still override this.
49 pytest_args = ['-n', '0'] + pytest_args
50 else:
51 # Namespacing is enabled by default because tests may break each other or
52 # interfere with parts of the running system if not isolated in a namespace.
53 # Disabling namespaces is not recommended for general use.
54 re_execute_with_namespace([sys.argv[0]] + argv)
Chris McDonald3c557392020-03-31 13:41:46 -060055
Chris McDonald5d1af6a2020-04-21 08:00:15 -060056 sys.exit(pytest.main(pytest_args))
Chris McDonald3c557392020-03-31 13:41:46 -060057
58
59def re_execute_with_namespace(argv, network=False):
60 """Re-execute as root so we can unshare resources."""
61 if os.geteuid() != 0:
62 cmd = [
63 'sudo',
64 'HOME=%s' % os.environ['HOME'],
65 'PATH=%s' % os.environ['PATH'],
66 '--',
67 ] + argv
68 os.execvp(cmd[0], cmd)
69 else:
70 cgroups.Cgroup.InitSystem()
71 namespaces.SimpleUnshare(net=not network, pid=True)
72 # We got our namespaces, so switch back to the user to run the tests.
73 gid = int(os.environ.pop('SUDO_GID'))
74 uid = int(os.environ.pop('SUDO_UID'))
75 user = os.environ.pop('SUDO_USER')
76 os.initgroups(user, gid)
77 os.setresgid(gid, gid, gid)
78 os.setresuid(uid, uid, uid)
79 os.environ['USER'] = user
80
81
82def re_execute_inside_chroot(argv):
83 """Re-execute the test wrapper inside the chroot."""
84 cmd = [
85 'cros_sdk',
86 '--',
87 os.path.join('..', '..', 'chromite', 'run_pytest'),
88 ]
89 if not cros_build_lib.IsInsideChroot():
90 os.execvp(cmd[0], cmd + argv)
91 else:
92 os.chdir(constants.CHROMITE_DIR)
93
94
95def ensure_chroot_exists():
96 """Ensure that a chroot exists for us to run tests in."""
97 chroot = os.path.join(constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR)
98 if not os.path.exists(chroot) and not cros_build_lib.IsInsideChroot():
99 cros_build_lib.run(['cros_sdk', '--create'])
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600100
101
102def get_parser():
103 """Build the parser for command line arguments."""
Mike Frysingerd7af8462020-11-11 03:44:54 -0500104 parser = commandline.ArgumentParser(
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600105 description=__doc__,
Mike Frysingerd7af8462020-11-11 03:44:54 -0500106 epilog='To see the help output for pytest:\n$ %(prog)s -- --help',
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600107 )
108 parser.add_argument(
109 '--quickstart',
110 dest='quick',
111 action='store_true',
112 help='Skip normal test sandboxing and namespacing for faster start up '
113 'time.',
114 )
Chris McDonald653510e2020-05-01 17:15:16 -0600115 parser.add_argument(
116 '--no-chroot',
117 dest='chroot',
118 action='store_false',
119 help="Don't initialize or enter a chroot for the test invocation. May "
120 'cause tests to unexpectedly fail!',
121 )
Mike Frysingerd7af8462020-11-11 03:44:54 -0500122 parser.add_argument(
123 'pytest_args',
124 metavar='pytest arguments',
125 nargs='*',
126 help='Arguments to pass down to pytest (use -- to help separate)',
127 )
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600128 return parser