blob: 511451f7aaf012d587aabdd0a145ff704619e097 [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 McDonald5d1af6a2020-04-21 08:00:15 -060010import argparse
Chris McDonald3c557392020-03-31 13:41:46 -060011import os
Chris McDonald17d86b32020-03-18 17:28:43 -060012import sys
13
14import pytest # pylint: disable=import-error
15
Chris McDonald3c557392020-03-31 13:41:46 -060016from chromite.lib import cgroups
17from 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()
26 opts, pytest_args = parser.parse_known_args()
27 if opts.quick:
Chris McDonald653510e2020-05-01 17:15:16 -060028 if not cros_build_lib.IsInsideChroot() and opts.chroot:
Chris McDonald5d1af6a2020-04-21 08:00:15 -060029 logging.warn('Running tests from inside the chroot will start up faster.')
30
Chris McDonald653510e2020-05-01 17:15:16 -060031 if opts.chroot:
32 ensure_chroot_exists()
33 re_execute_inside_chroot(argv)
34 else:
35 os.chdir(constants.CHROMITE_DIR)
Chris McDonald3c557392020-03-31 13:41:46 -060036
37 # This is a cheesy hack to make sure gsutil is populated in the cache before
38 # we run tests. This is a partial workaround for crbug.com/468838.
39 gs.GSContext.GetDefaultGSUtilBin()
40
Chris McDonald5d1af6a2020-04-21 08:00:15 -060041 if opts.quick:
42 logging.info('Skipping test namespacing due to --quickstart.')
43 # Default to running in a single process under --quickstart. User args can
44 # still override this.
45 pytest_args = ['-n', '0'] + pytest_args
46 else:
47 # Namespacing is enabled by default because tests may break each other or
48 # interfere with parts of the running system if not isolated in a namespace.
49 # Disabling namespaces is not recommended for general use.
50 re_execute_with_namespace([sys.argv[0]] + argv)
Chris McDonald3c557392020-03-31 13:41:46 -060051
Chris McDonald5d1af6a2020-04-21 08:00:15 -060052 sys.exit(pytest.main(pytest_args))
Chris McDonald3c557392020-03-31 13:41:46 -060053
54
55def re_execute_with_namespace(argv, network=False):
56 """Re-execute as root so we can unshare resources."""
57 if os.geteuid() != 0:
58 cmd = [
59 'sudo',
60 'HOME=%s' % os.environ['HOME'],
61 'PATH=%s' % os.environ['PATH'],
62 '--',
63 ] + argv
64 os.execvp(cmd[0], cmd)
65 else:
66 cgroups.Cgroup.InitSystem()
67 namespaces.SimpleUnshare(net=not network, pid=True)
68 # We got our namespaces, so switch back to the user to run the tests.
69 gid = int(os.environ.pop('SUDO_GID'))
70 uid = int(os.environ.pop('SUDO_UID'))
71 user = os.environ.pop('SUDO_USER')
72 os.initgroups(user, gid)
73 os.setresgid(gid, gid, gid)
74 os.setresuid(uid, uid, uid)
75 os.environ['USER'] = user
76
77
78def re_execute_inside_chroot(argv):
79 """Re-execute the test wrapper inside the chroot."""
80 cmd = [
81 'cros_sdk',
82 '--',
83 os.path.join('..', '..', 'chromite', 'run_pytest'),
84 ]
85 if not cros_build_lib.IsInsideChroot():
86 os.execvp(cmd[0], cmd + argv)
87 else:
88 os.chdir(constants.CHROMITE_DIR)
89
90
91def ensure_chroot_exists():
92 """Ensure that a chroot exists for us to run tests in."""
93 chroot = os.path.join(constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR)
94 if not os.path.exists(chroot) and not cros_build_lib.IsInsideChroot():
95 cros_build_lib.run(['cros_sdk', '--create'])
Chris McDonald5d1af6a2020-04-21 08:00:15 -060096
97
98def get_parser():
99 """Build the parser for command line arguments."""
100 parser = argparse.ArgumentParser(
101 description=__doc__,
102 epilog='To see the help output for pytest, run `pytest --help` inside '
103 'the chroot.',
104 )
105 parser.add_argument(
106 '--quickstart',
107 dest='quick',
108 action='store_true',
109 help='Skip normal test sandboxing and namespacing for faster start up '
110 'time.',
111 )
Chris McDonald653510e2020-05-01 17:15:16 -0600112 parser.add_argument(
113 '--no-chroot',
114 dest='chroot',
115 action='store_false',
116 help="Don't initialize or enter a chroot for the test invocation. May "
117 'cause tests to unexpectedly fail!',
118 )
Chris McDonald5d1af6a2020-04-21 08:00:15 -0600119 return parser