blob: d04a52d94aa067c0a7b9d523d8d0dab661ccaad1 [file] [log] [blame]
Ryan Cuiafd6c5c2012-07-30 17:48:22 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Steve Funge984a532013-11-25 17:09:25 -08005"""Unit tests for the deploy_chrome script."""
Ryan Cuiafd6c5c2012-07-30 17:48:22 -07006
Anushruth8d797672019-10-17 12:22:31 -07007import errno
Ryan Cuiafd6c5c2012-07-30 17:48:22 -07008import os
David James88e6f032013-03-02 08:13:20 -08009import time
Mike Frysinger166fea02021-02-12 05:30:33 -050010from unittest import mock
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070011
David Pursellcfd58872015-03-19 09:15:48 -070012from chromite.cli.cros import cros_chrome_sdk_unittest
Ryan Cuief91e702013-02-04 12:06:36 -080013from chromite.lib import chrome_util
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070014from chromite.lib import cros_build_lib
15from chromite.lib import cros_test_lib
Jae Hoon Kimdf842912022-05-19 06:40:42 +000016from chromite.lib import gs
Ryan Cui686ec052013-02-12 16:39:41 -080017from chromite.lib import osutils
Erik Chen75a2f492020-08-06 19:15:11 -070018from chromite.lib import parallel_unittest
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070019from chromite.lib import partial_mock
Robert Flack1dc7ea82014-11-26 13:50:24 -050020from chromite.lib import remote_access
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070021from chromite.lib import remote_access_unittest
22from chromite.scripts import deploy_chrome
23
Ryan Cuief91e702013-02-04 12:06:36 -080024
Mike Frysinger27e21b72018-07-12 14:20:21 -040025# pylint: disable=protected-access
26
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070027
Ben Pastene0ff0fa42020-08-14 15:10:07 -070028_REGULAR_TO = ('--device', 'monkey')
Avery Musbach3edff0e2020-03-27 13:35:53 -070029_TARGET_BOARD = 'eve'
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070030_GS_PATH = 'gs://foon'
31
32
33def _ParseCommandLine(argv):
34 return deploy_chrome._ParseCommandLine(['--log-level', 'debug'] + argv)
35
36
37class InterfaceTest(cros_test_lib.OutputTestCase):
38 """Tests the commandline interface of the script."""
39
40 def testGsLocalPathUnSpecified(self):
41 """Test no chrome path specified."""
42 with self.OutputCapturer():
Avery Musbach3edff0e2020-03-27 13:35:53 -070043 self.assertRaises2(SystemExit, _ParseCommandLine,
44 list(_REGULAR_TO) + ['--board', _TARGET_BOARD],
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070045 check_attrs={'code': 2})
46
Ryo Hashimoto77f8eca2021-04-16 16:43:37 +090047 def testBuildDirSpecified(self):
48 """Test case of build dir specified."""
49 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--build-dir',
50 '/path/to/chrome']
51 _ParseCommandLine(argv)
52
53 def testBuildDirSpecifiedWithoutBoard(self):
54 """Test case of build dir specified without --board."""
55 argv = list(_REGULAR_TO) + [
56 '--build-dir', '/path/to/chrome/out_' + _TARGET_BOARD + '/Release']
57 options = _ParseCommandLine(argv)
58 self.assertEqual(options.board, _TARGET_BOARD)
59
60 def testBuildDirSpecifiedWithoutBoardError(self):
61 """Test case of irregular build dir specified without --board."""
62 argv = list(_REGULAR_TO) + ['--build-dir', '/path/to/chrome/foo/bar']
63 self.assertParseError(argv)
64
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070065 def testGsPathSpecified(self):
66 """Test case of GS path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070067 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070068 _ParseCommandLine(argv)
69
70 def testLocalPathSpecified(self):
71 """Test case of local path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070072 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--local-pkg-path',
73 '/path/to/chrome']
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070074 _ParseCommandLine(argv)
75
Ryo Hashimoto77f8eca2021-04-16 16:43:37 +090076 def testNoBoard(self):
77 """Test no board specified."""
78 argv = list(_REGULAR_TO) + ['--gs-path', _GS_PATH]
79 self.assertParseError(argv)
80
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070081 def testNoTarget(self):
82 """Test no target specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070083 argv = ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuief91e702013-02-04 12:06:36 -080084 self.assertParseError(argv)
85
Erik Chen75a2f492020-08-06 19:15:11 -070086 def testLacros(self):
87 """Test basic lacros invocation."""
88 argv = ['--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
Ben Pastene0ff0fa42020-08-14 15:10:07 -070089 '--device', 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070090 options = _ParseCommandLine(argv)
91 self.assertTrue(options.lacros)
92 self.assertEqual(options.target_dir, deploy_chrome.LACROS_DIR)
93
94 def testLacrosRequiresNostrip(self):
95 """Lacros requires --nostrip"""
Ben Pastene0ff0fa42020-08-14 15:10:07 -070096 argv = ['--lacros', '--build-dir', '/path/to/nowhere', '--device',
97 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070098 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
99 check_attrs={'code': 2})
100
Ryan Cuief91e702013-02-04 12:06:36 -0800101 def assertParseError(self, argv):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700102 with self.OutputCapturer():
103 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
104 check_attrs={'code': 2})
105
Thiago Goncales12793312013-05-23 11:26:17 -0700106 def testMountOptionSetsTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700107 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
108 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400109 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700110 self.assertIsNot(options.target_dir, None)
111
112 def testMountOptionSetsMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700113 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
114 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400115 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700116 self.assertIsNot(options.mount_dir, None)
117
118 def testMountOptionDoesNotOverrideTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700119 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
120 '--mount', '--target-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400121 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700122 self.assertEqual(options.target_dir, '/foo/bar/cow')
123
124 def testMountOptionDoesNotOverrideMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700125 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
126 '--mount', '--mount-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400127 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700128 self.assertEqual(options.mount_dir, '/foo/bar/cow')
129
Adrian Eldera2c548a2017-11-07 19:01:29 -0500130 def testSshIdentityOptionSetsOption(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700131 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
132 '--private-key', '/foo/bar/key',
Bernie Thompson93b9ee62018-02-21 14:56:16 -0800133 '--build-dir', '/path/to/nowhere']
Adrian Eldera2c548a2017-11-07 19:01:29 -0500134 options = _ParseCommandLine(argv)
135 self.assertEqual(options.private_key, '/foo/bar/key')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700136
137class DeployChromeMock(partial_mock.PartialMock):
Steve Funge984a532013-11-25 17:09:25 -0800138 """Deploy Chrome Mock Class."""
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700139
140 TARGET = 'chromite.scripts.deploy_chrome.DeployChrome'
Erik Chen75a2f492020-08-06 19:15:11 -0700141 ATTRS = ('_KillAshChromeIfNeeded', '_DisableRootfsVerification')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700142
David James88e6f032013-03-02 08:13:20 -0800143 def __init__(self):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700144 partial_mock.PartialMock.__init__(self)
Robert Flack1dc7ea82014-11-26 13:50:24 -0500145 self.remote_device_mock = remote_access_unittest.RemoteDeviceMock()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700146 # Target starts off as having rootfs verification enabled.
Ryan Cuie18f24f2012-12-03 18:39:55 -0800147 self.rsh_mock = remote_access_unittest.RemoteShMock()
David James88e6f032013-03-02 08:13:20 -0800148 self.rsh_mock.SetDefaultCmdResult(0)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700149 self.MockMountCmd(1)
David Haddock3151d912017-10-24 03:50:32 +0000150 self.rsh_mock.AddCmdResult(
Anushruth8d797672019-10-17 12:22:31 -0700151 deploy_chrome.LSOF_COMMAND_CHROME % (deploy_chrome._CHROME_DIR,), 1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700152
153 def MockMountCmd(self, returnvalue):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700154 self.rsh_mock.AddCmdResult(deploy_chrome.MOUNT_RW_COMMAND,
David James88e6f032013-03-02 08:13:20 -0800155 returnvalue)
156
157 def _DisableRootfsVerification(self, inst):
158 with mock.patch.object(time, 'sleep'):
159 self.backup['_DisableRootfsVerification'](inst)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700160
Ryan Cui4d6fca92012-12-13 16:41:56 -0800161 def PreStart(self):
Robert Flack1dc7ea82014-11-26 13:50:24 -0500162 self.remote_device_mock.start()
Ryan Cui4d6fca92012-12-13 16:41:56 -0800163 self.rsh_mock.start()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700164
Ryan Cui4d6fca92012-12-13 16:41:56 -0800165 def PreStop(self):
166 self.rsh_mock.stop()
Robert Flack1dc7ea82014-11-26 13:50:24 -0500167 self.remote_device_mock.stop()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700168
Erik Chen75a2f492020-08-06 19:15:11 -0700169 def _KillAshChromeIfNeeded(self, _inst):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700170 # Fully stub out for now.
171 pass
172
173
Ryan Cuief91e702013-02-04 12:06:36 -0800174class DeployTest(cros_test_lib.MockTempDirTestCase):
Steve Funge984a532013-11-25 17:09:25 -0800175 """Setup a deploy object with a GS-path for use in tests."""
176
Ryan Cuief91e702013-02-04 12:06:36 -0800177 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400178 options = _ParseCommandLine(args)
Ryan Cuia56a71e2012-10-18 18:40:35 -0700179 return deploy_chrome.DeployChrome(
180 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700181
182 def setUp(self):
Ryan Cuif1416f32013-01-22 18:43:41 -0800183 self.deploy_mock = self.StartPatcher(DeployChromeMock())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700184 self.deploy = self._GetDeployChrome(list(_REGULAR_TO) +
185 ['--board', _TARGET_BOARD, '--gs-path',
186 _GS_PATH, '--force', '--mount'])
Mike Frysingerfcca49e2021-03-17 01:09:20 -0400187 self.remote_reboot_mock = self.PatchObject(
188 remote_access.RemoteAccess, 'RemoteReboot', return_value=True)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700189
Avery Musbach3edff0e2020-03-27 13:35:53 -0700190
191class TestCheckIfBoardMatches(DeployTest):
192 """Testing checking whether the DUT board matches the target board."""
193
194 def testMatchedBoard(self):
195 """Test the case where the DUT board matches the target board."""
196 self.PatchObject(remote_access.ChromiumOSDevice, 'board', _TARGET_BOARD)
197 self.assertTrue(self.deploy.options.force)
198 self.deploy._CheckBoard()
199 self.deploy.options.force = False
200 self.deploy._CheckBoard()
201
202 def testMismatchedBoard(self):
203 """Test the case where the DUT board does not match the target board."""
204 self.PatchObject(remote_access.ChromiumOSDevice, 'board', 'cedar')
205 self.assertTrue(self.deploy.options.force)
206 self.deploy._CheckBoard()
207 self.deploy.options.force = False
208 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=True)
209 self.deploy._CheckBoard()
210 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=False)
211 self.assertRaises(deploy_chrome.DeployFailure, self.deploy._CheckBoard)
212
213
David James88e6f032013-03-02 08:13:20 -0800214class TestDisableRootfsVerification(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700215 """Testing disabling of rootfs verification and RO mode."""
216
David James88e6f032013-03-02 08:13:20 -0800217 def testDisableRootfsVerificationSuccess(self):
218 """Test the working case, disabling rootfs verification."""
219 self.deploy_mock.MockMountCmd(0)
220 self.deploy._DisableRootfsVerification()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700221 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700222
223 def testDisableRootfsVerificationFailure(self):
224 """Test failure to disable rootfs verification."""
Mike Frysinger27e21b72018-07-12 14:20:21 -0400225 # pylint: disable=unused-argument
Shuqian Zhao14e61092017-11-17 00:02:16 +0000226 def RaiseRunCommandError(timeout_sec=None):
Mike Frysinger929f3ba2019-09-12 03:24:59 -0400227 raise cros_build_lib.RunCommandError('Mock RunCommandError')
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800228 self.remote_reboot_mock.side_effect = RaiseRunCommandError
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700229 self.assertRaises(cros_build_lib.RunCommandError,
David James88e6f032013-03-02 08:13:20 -0800230 self.deploy._DisableRootfsVerification)
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800231 self.remote_reboot_mock.side_effect = None
Steven Bennettsca73efa2018-07-10 13:36:56 -0700232 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800233
234
235class TestMount(DeployTest):
236 """Testing mount success and failure."""
237
238 def testSuccess(self):
239 """Test case where we are able to mount as writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700240 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800241 self.deploy_mock.MockMountCmd(0)
242 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700243 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800244
245 def testMountError(self):
246 """Test that mount failure doesn't raise an exception by default."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700247 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700248 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500249 return_value=False, autospec=True)
David James88e6f032013-03-02 08:13:20 -0800250 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700251 self.assertTrue(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700252
253 def testMountRwFailure(self):
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500254 """Test that mount failure raises an exception if check=True."""
David James88e6f032013-03-02 08:13:20 -0800255 self.assertRaises(cros_build_lib.RunCommandError,
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500256 self.deploy._MountRootfsAsWritable, check=True)
Steven Bennettsca73efa2018-07-10 13:36:56 -0700257 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Robert Flack1dc7ea82014-11-26 13:50:24 -0500258
259 def testMountTempDir(self):
260 """Test that mount succeeds if target dir is writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700261 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700262 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500263 return_value=True, autospec=True)
264 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700265 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700266
267
Anushruth8d797672019-10-17 12:22:31 -0700268class TestMountTarget(DeployTest):
Mike Frysingerdf1d0b02019-11-12 17:44:12 -0500269 """Testing mount and umount command handling."""
Anushruth8d797672019-10-17 12:22:31 -0700270
271 def testMountTargetUmountFailure(self):
272 """Test error being thrown if umount fails.
273
274 Test that 'lsof' is run on mount-dir and 'mount -rbind' command is not run
275 if 'umount' cmd fails.
276 """
277 mount_dir = self.deploy.options.mount_dir
278 target_dir = self.deploy.options.target_dir
279 self.deploy_mock.rsh_mock.AddCmdResult(
280 deploy_chrome._UMOUNT_DIR_IF_MOUNTPOINT_CMD %
281 {'dir': mount_dir}, returncode=errno.EBUSY, stderr='Target is Busy')
282 self.deploy_mock.rsh_mock.AddCmdResult(deploy_chrome.LSOF_COMMAND %
283 (mount_dir,), returncode=0,
284 stdout='process ' + mount_dir)
285 # Check for RunCommandError being thrown.
286 self.assertRaises(cros_build_lib.RunCommandError,
287 self.deploy._MountTarget)
288 # Check for the 'mount -rbind' command not run.
289 self.deploy_mock.rsh_mock.assertCommandContains(
290 (deploy_chrome._BIND_TO_FINAL_DIR_CMD % (target_dir, mount_dir)),
291 expected=False)
292 # Check for lsof command being called.
293 self.deploy_mock.rsh_mock.assertCommandContains(
294 (deploy_chrome.LSOF_COMMAND % (mount_dir,)))
295
296
Ryan Cuief91e702013-02-04 12:06:36 -0800297class TestUiJobStarted(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700298 """Test detection of a running 'ui' job."""
299
Ryan Cuif2d1a582013-02-19 14:08:13 -0800300 def MockStatusUiCmd(self, **kwargs):
David Haddock3151d912017-10-24 03:50:32 +0000301 self.deploy_mock.rsh_mock.AddCmdResult('status ui', **kwargs)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700302
303 def testUiJobStartedFalse(self):
304 """Correct results with a stopped job."""
Mike Frysinger876a8e52022-06-23 18:07:30 -0400305 self.MockStatusUiCmd(stdout='ui stop/waiting')
Ryan Cuif2d1a582013-02-19 14:08:13 -0800306 self.assertFalse(self.deploy._CheckUiJobStarted())
307
308 def testNoUiJob(self):
309 """Correct results when the job doesn't exist."""
Mike Frysinger876a8e52022-06-23 18:07:30 -0400310 self.MockStatusUiCmd(stderr='start: Unknown job: ui', returncode=1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700311 self.assertFalse(self.deploy._CheckUiJobStarted())
312
313 def testCheckRootfsWriteableTrue(self):
314 """Correct results with a running job."""
Mike Frysinger876a8e52022-06-23 18:07:30 -0400315 self.MockStatusUiCmd(stdout='ui start/running, process 297')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700316 self.assertTrue(self.deploy._CheckUiJobStarted())
317
318
Ryan Cuief91e702013-02-04 12:06:36 -0800319class StagingTest(cros_test_lib.MockTempDirTestCase):
320 """Test user-mode and ebuild-mode staging functionality."""
321
322 def setUp(self):
Ryan Cuief91e702013-02-04 12:06:36 -0800323 self.staging_dir = os.path.join(self.tempdir, 'staging')
Jae Hoon Kimdf842912022-05-19 06:40:42 +0000324 osutils.SafeMakedirs(self.staging_dir)
325 self.staging_tarball_path = os.path.join(
326 self.tempdir, deploy_chrome._CHROME_DIR_STAGING_TARBALL_ZSTD)
Ryan Cuief91e702013-02-04 12:06:36 -0800327 self.build_dir = os.path.join(self.tempdir, 'build_dir')
Avery Musbach3edff0e2020-03-27 13:35:53 -0700328 self.common_flags = ['--board', _TARGET_BOARD,
329 '--build-dir', self.build_dir, '--staging-only',
Mike Frysinger3bb61cb2022-04-14 16:07:44 -0400330 '--cache-dir', str(self.tempdir)]
Ryan Cuia0215a72013-02-14 16:20:45 -0800331 self.sdk_mock = self.StartPatcher(cros_chrome_sdk_unittest.SDKFetcherMock())
Ryan Cui686ec052013-02-12 16:39:41 -0800332 self.PatchObject(
333 osutils, 'SourceEnvironment', autospec=True,
334 return_value={'STRIP': 'x86_64-cros-linux-gnu-strip'})
Ryan Cuief91e702013-02-04 12:06:36 -0800335
David Jamesa6e08892013-03-01 13:34:11 -0800336 def testSingleFileDeployFailure(self):
337 """Default staging enforces that mandatory files are copied"""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400338 options = _ParseCommandLine(self.common_flags)
David Jamesa6e08892013-03-01 13:34:11 -0800339 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
340 self.assertRaises(
341 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700342 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
Ryan Cuief91e702013-02-04 12:06:36 -0800343
David Jamesa6e08892013-03-01 13:34:11 -0800344 def testSloppyDeployFailure(self):
345 """Sloppy staging enforces that at least one file is copied."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400346 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800347 self.assertRaises(
348 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700349 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800350
351 def testSloppyDeploySuccess(self):
352 """Sloppy staging - stage one file."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400353 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800354 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
Steve Funge984a532013-11-25 17:09:25 -0800355 deploy_chrome._PrepareStagingDir(options, self.tempdir, self.staging_dir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700356 chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800357
Jae Hoon Kimdf842912022-05-19 06:40:42 +0000358 @cros_test_lib.pytestmark_network_test
359 def testUploadStagingDir(self):
360 """Upload staging directory."""
361 mockGsCopy = self.PatchObject(gs.GSContext, 'Copy')
362 staging_upload = 'gs://some-path'
363 options = _ParseCommandLine(
364 self.common_flags + ['--staging-upload', staging_upload])
365 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
366 deploy_chrome._UploadStagingDir(options, self.tempdir, self.staging_dir)
367 self.assertEqual(mockGsCopy.call_args_list, [
368 mock.call(self.staging_tarball_path, staging_upload, acl=''),
369 ])
370
371 @cros_test_lib.pytestmark_network_test
372 def testUploadStagingPublicReadACL(self):
373 """Upload staging directory with public-read ACL."""
374 mockGsCopy = self.PatchObject(gs.GSContext, 'Copy')
375 staging_upload = 'gs://some-path'
376 options = _ParseCommandLine(
377 self.common_flags +
378 ['--staging-upload', staging_upload, '--public-read'])
379 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
380 deploy_chrome._UploadStagingDir(options, self.tempdir, self.staging_dir)
381 self.assertEqual(mockGsCopy.call_args_list, [
382 mock.call(self.staging_tarball_path, staging_upload, acl='public-read'),
383 ])
384
Steve Funge984a532013-11-25 17:09:25 -0800385
386class DeployTestBuildDir(cros_test_lib.MockTempDirTestCase):
Daniel Erat1ae46382014-08-14 10:23:39 -0700387 """Set up a deploy object with a build-dir for use in deployment type tests"""
Steve Funge984a532013-11-25 17:09:25 -0800388
389 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400390 options = _ParseCommandLine(args)
Steve Funge984a532013-11-25 17:09:25 -0800391 return deploy_chrome.DeployChrome(
392 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
393
394 def setUp(self):
395 self.staging_dir = os.path.join(self.tempdir, 'staging')
396 self.build_dir = os.path.join(self.tempdir, 'build_dir')
397 self.deploy_mock = self.StartPatcher(DeployChromeMock())
398 self.deploy = self._GetDeployChrome(
Avery Musbach3edff0e2020-03-27 13:35:53 -0700399 list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
400 '--build-dir', self.build_dir, '--staging-only',
Mike Frysinger3bb61cb2022-04-14 16:07:44 -0400401 '--cache-dir', str(self.tempdir), '--sloppy'])
Steve Funge984a532013-11-25 17:09:25 -0800402
Daniel Erat1ae46382014-08-14 10:23:39 -0700403 def getCopyPath(self, source_path):
404 """Return a chrome_util.Path or None if not present."""
405 paths = [p for p in self.deploy.copy_paths if p.src == source_path]
406 return paths[0] if paths else None
Steve Funge984a532013-11-25 17:09:25 -0800407
Daniel Erat1ae46382014-08-14 10:23:39 -0700408class TestDeploymentType(DeployTestBuildDir):
Steve Funge984a532013-11-25 17:09:25 -0800409 """Test detection of deployment type using build dir."""
410
Daniel Erat1ae46382014-08-14 10:23:39 -0700411 def testAppShellDetection(self):
412 """Check for an app_shell deployment"""
413 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Funge984a532013-11-25 17:09:25 -0800414 makedirs=True)
415 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700416 self.assertTrue(self.getCopyPath('app_shell'))
417 self.assertFalse(self.getCopyPath('chrome'))
Steve Funge984a532013-11-25 17:09:25 -0800418
Daniel Erat1ae46382014-08-14 10:23:39 -0700419 def testChromeAndAppShellDetection(self):
Daniel Eratf53bd3a2016-12-02 11:28:36 -0700420 """Check for a chrome deployment when app_shell also exists."""
Steve Fung63d705d2014-03-16 03:14:03 -0700421 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
422 makedirs=True)
Daniel Erat1ae46382014-08-14 10:23:39 -0700423 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Fung63d705d2014-03-16 03:14:03 -0700424 makedirs=True)
425 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700426 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700427 self.assertFalse(self.getCopyPath('app_shell'))
Steve Fung63d705d2014-03-16 03:14:03 -0700428
Steve Funge984a532013-11-25 17:09:25 -0800429 def testChromeDetection(self):
430 """Check for a regular chrome deployment"""
431 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
432 makedirs=True)
433 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700434 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700435 self.assertFalse(self.getCopyPath('app_shell'))
Ben Pastenee484b342020-06-30 18:29:27 -0700436
437
438class TestDeployTestBinaries(cros_test_lib.RunCommandTempDirTestCase):
439 """Tests _DeployTestBinaries()."""
440
441 def setUp(self):
442 options = _ParseCommandLine(list(_REGULAR_TO) + [
443 '--board', _TARGET_BOARD, '--force', '--mount',
444 '--build-dir', os.path.join(self.tempdir, 'build_dir'),
445 '--nostrip'])
446 self.deploy = deploy_chrome.DeployChrome(
447 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
448
Brian Sheedy86f12342020-10-29 15:30:02 -0700449 def _SimulateBinaries(self):
450 # Ensure the staging dir contains the right binaries to copy over.
Ben Pastenee484b342020-06-30 18:29:27 -0700451 test_binaries = [
452 'run_a_tests',
453 'run_b_tests',
454 'run_c_tests',
455 ]
456 # Simulate having the binaries both on the device and in our local build
457 # dir.
458 self.rc.AddCmdResult(
459 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD),
460 stdout='\n'.join(test_binaries))
461 for binary in test_binaries:
462 osutils.Touch(os.path.join(self.deploy.options.build_dir, binary),
463 makedirs=True, mode=0o700)
Brian Sheedy86f12342020-10-29 15:30:02 -0700464 return test_binaries
Ben Pastenee484b342020-06-30 18:29:27 -0700465
Brian Sheedy86f12342020-10-29 15:30:02 -0700466 def _AssertBinariesInStagingDir(self, test_binaries):
Ben Pastenee484b342020-06-30 18:29:27 -0700467 # Ensure the binaries were placed in the staging dir used to copy them over.
468 staging_dir = os.path.join(
469 self.tempdir, os.path.basename(deploy_chrome._CHROME_TEST_BIN_DIR))
470 for binary in test_binaries:
471 self.assertIn(binary, os.listdir(staging_dir))
Erik Chen75a2f492020-08-06 19:15:11 -0700472
Brian Sheedy86f12342020-10-29 15:30:02 -0700473 def testFindError(self):
474 """Ensure an error is thrown if we can't inspect the device."""
475 self.rc.AddCmdResult(
476 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD), 1)
477 self.assertRaises(
478 deploy_chrome.DeployFailure, self.deploy._DeployTestBinaries)
479
480 def testSuccess(self):
481 """Ensure that the happy path succeeds as expected."""
482 test_binaries = self._SimulateBinaries()
483 self.deploy._DeployTestBinaries()
484 self._AssertBinariesInStagingDir(test_binaries)
485
486 def testRetrySuccess(self):
487 """Ensure that a transient exception still results in success."""
488 # Raises a RunCommandError on its first invocation, but passes on subsequent
489 # calls.
490 def SideEffect(*args, **kwargs):
Yuke Liaobe6bac32020-12-26 22:16:49 -0800491 # pylint: disable=unused-argument
Brian Sheedy86f12342020-10-29 15:30:02 -0700492 if not SideEffect.called:
493 SideEffect.called = True
494 raise cros_build_lib.RunCommandError('fail')
495 SideEffect.called = False
496
497 test_binaries = self._SimulateBinaries()
498 with mock.patch.object(
499 remote_access.ChromiumOSDevice, 'CopyToDevice',
500 side_effect=SideEffect) as copy_mock:
501 self.deploy._DeployTestBinaries()
502 self.assertEqual(copy_mock.call_count, 2)
503 self._AssertBinariesInStagingDir(test_binaries)
504
505 def testRetryFailure(self):
506 """Ensure that consistent exceptions result in failure."""
507 self._SimulateBinaries()
508 with self.assertRaises(cros_build_lib.RunCommandError):
509 with mock.patch.object(
510 remote_access.ChromiumOSDevice, 'CopyToDevice',
511 side_effect=cros_build_lib.RunCommandError('fail')):
512 self.deploy._DeployTestBinaries()
513
Erik Chen75a2f492020-08-06 19:15:11 -0700514
515class LacrosPerformTest(cros_test_lib.RunCommandTempDirTestCase):
516 """Line coverage for Perform() method with --lacros option."""
517
518 def setUp(self):
Yuke Liao24fc60c2020-12-26 22:16:49 -0800519 self.deploy = None
520 self._ran_start_command = False
521 self.StartPatcher(parallel_unittest.ParallelMock())
522
523 def start_ui_side_effect(*args, **kwargs):
524 # pylint: disable=unused-argument
525 self._ran_start_command = True
526
527 self.rc.AddCmdResult(partial_mock.In('start ui'),
528 side_effect=start_ui_side_effect)
529
530 def prepareDeploy(self, options=None):
531 if not options:
532 options = _ParseCommandLine([
533 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
534 '--device', 'monkey'
535 ])
Erik Chen75a2f492020-08-06 19:15:11 -0700536 self.deploy = deploy_chrome.DeployChrome(
537 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
538
539 # These methods being mocked are all side effects expected for a --lacros
540 # deploy.
541 self.deploy._EnsureTargetDir = mock.Mock()
542 self.deploy._GetDeviceInfo = mock.Mock()
543 self.deploy._CheckConnection = mock.Mock()
544 self.deploy._MountRootfsAsWritable = mock.Mock()
545 self.deploy._PrepareStagingDir = mock.Mock()
546 self.deploy._CheckDeviceFreeSpace = mock.Mock()
Yuke Liaobe6bac32020-12-26 22:16:49 -0800547 self.deploy._KillAshChromeIfNeeded = mock.Mock()
Erik Chen75a2f492020-08-06 19:15:11 -0700548
549 def testConfNotModified(self):
550 """When the conf file is not modified we don't restart chrome ."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800551 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700552 self.deploy.Perform()
553 self.deploy._KillAshChromeIfNeeded.assert_not_called()
554 self.assertFalse(self._ran_start_command)
555
556 def testConfModified(self):
557 """When the conf file is modified we restart chrome."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800558 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700559
560 # We intentionally add '\n' to MODIFIED_CONF_FILE to simulate echo adding a
561 # newline when invoked in the shell.
562 self.rc.AddCmdResult(
563 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
564 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
565
566 self.deploy.Perform()
567 self.deploy._KillAshChromeIfNeeded.assert_called()
568 self.assertTrue(self._ran_start_command)
Yuke Liao24fc60c2020-12-26 22:16:49 -0800569
570 def testSkipModifyingConf(self):
571 """SKip modifying the config file when the argument is specified."""
572 self.prepareDeploy(
573 _ParseCommandLine([
574 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
575 '--device', 'monkey', '--skip-modifying-config-file'
576 ]))
577
578 self.rc.AddCmdResult(
579 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
580 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
581
582 self.deploy.Perform()
583 self.deploy._KillAshChromeIfNeeded.assert_not_called()
584 self.assertFalse(self._ran_start_command)