blob: 3ba6340b7cf424084c55015654c85ca391ec3961 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Ryan Cuiafd6c5c2012-07-30 17:48:22 -07002# Copyright (c) 2012 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
Steve Funge984a532013-11-25 17:09:25 -08006"""Unit tests for the deploy_chrome script."""
Ryan Cuiafd6c5c2012-07-30 17:48:22 -07007
Mike Frysinger383367e2014-09-16 15:06:17 -04008from __future__ import print_function
9
Anushruth8d797672019-10-17 12:22:31 -070010import errno
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070011import os
Mike Frysinger6165cdc2020-02-21 02:38:07 -050012import sys
David James88e6f032013-03-02 08:13:20 -080013import time
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070014
Mike Frysinger6db648e2018-07-24 19:57:58 -040015import mock
16
David Pursellcfd58872015-03-19 09:15:48 -070017from chromite.cli.cros import cros_chrome_sdk_unittest
Ryan Cuief91e702013-02-04 12:06:36 -080018from chromite.lib import chrome_util
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070019from chromite.lib import cros_build_lib
20from chromite.lib import cros_test_lib
Ryan Cui686ec052013-02-12 16:39:41 -080021from chromite.lib import osutils
Erik Chen75a2f492020-08-06 19:15:11 -070022from chromite.lib import parallel_unittest
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070023from chromite.lib import partial_mock
Robert Flack1dc7ea82014-11-26 13:50:24 -050024from chromite.lib import remote_access
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070025from chromite.lib import remote_access_unittest
26from chromite.scripts import deploy_chrome
27
Ryan Cuief91e702013-02-04 12:06:36 -080028
Mike Frysinger6165cdc2020-02-21 02:38:07 -050029assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
30
31
Mike Frysinger27e21b72018-07-12 14:20:21 -040032# pylint: disable=protected-access
33
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070034
Ben Pastene0ff0fa42020-08-14 15:10:07 -070035_REGULAR_TO = ('--device', 'monkey')
Avery Musbach3edff0e2020-03-27 13:35:53 -070036_TARGET_BOARD = 'eve'
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070037_GS_PATH = 'gs://foon'
38
39
40def _ParseCommandLine(argv):
41 return deploy_chrome._ParseCommandLine(['--log-level', 'debug'] + argv)
42
43
44class InterfaceTest(cros_test_lib.OutputTestCase):
45 """Tests the commandline interface of the script."""
46
47 def testGsLocalPathUnSpecified(self):
48 """Test no chrome path specified."""
49 with self.OutputCapturer():
Avery Musbach3edff0e2020-03-27 13:35:53 -070050 self.assertRaises2(SystemExit, _ParseCommandLine,
51 list(_REGULAR_TO) + ['--board', _TARGET_BOARD],
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070052 check_attrs={'code': 2})
53
54 def testGsPathSpecified(self):
55 """Test case of GS path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070056 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070057 _ParseCommandLine(argv)
58
59 def testLocalPathSpecified(self):
60 """Test case of local path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070061 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--local-pkg-path',
62 '/path/to/chrome']
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070063 _ParseCommandLine(argv)
64
65 def testNoTarget(self):
66 """Test no target specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070067 argv = ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuief91e702013-02-04 12:06:36 -080068 self.assertParseError(argv)
69
Erik Chen75a2f492020-08-06 19:15:11 -070070 def testLacros(self):
71 """Test basic lacros invocation."""
72 argv = ['--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
Ben Pastene0ff0fa42020-08-14 15:10:07 -070073 '--device', 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070074 options = _ParseCommandLine(argv)
75 self.assertTrue(options.lacros)
76 self.assertEqual(options.target_dir, deploy_chrome.LACROS_DIR)
77
78 def testLacrosRequiresNostrip(self):
79 """Lacros requires --nostrip"""
Ben Pastene0ff0fa42020-08-14 15:10:07 -070080 argv = ['--lacros', '--build-dir', '/path/to/nowhere', '--device',
81 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070082 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
83 check_attrs={'code': 2})
84
Ryan Cuief91e702013-02-04 12:06:36 -080085 def assertParseError(self, argv):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070086 with self.OutputCapturer():
87 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
88 check_attrs={'code': 2})
89
Thiago Goncales12793312013-05-23 11:26:17 -070090 def testMountOptionSetsTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -070091 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
92 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -040093 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -070094 self.assertIsNot(options.target_dir, None)
95
96 def testMountOptionSetsMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -070097 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
98 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -040099 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700100 self.assertIsNot(options.mount_dir, None)
101
102 def testMountOptionDoesNotOverrideTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700103 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
104 '--mount', '--target-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400105 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700106 self.assertEqual(options.target_dir, '/foo/bar/cow')
107
108 def testMountOptionDoesNotOverrideMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700109 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
110 '--mount', '--mount-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400111 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700112 self.assertEqual(options.mount_dir, '/foo/bar/cow')
113
Adrian Eldera2c548a2017-11-07 19:01:29 -0500114 def testSshIdentityOptionSetsOption(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700115 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
116 '--private-key', '/foo/bar/key',
Bernie Thompson93b9ee62018-02-21 14:56:16 -0800117 '--build-dir', '/path/to/nowhere']
Adrian Eldera2c548a2017-11-07 19:01:29 -0500118 options = _ParseCommandLine(argv)
119 self.assertEqual(options.private_key, '/foo/bar/key')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700120
121class DeployChromeMock(partial_mock.PartialMock):
Steve Funge984a532013-11-25 17:09:25 -0800122 """Deploy Chrome Mock Class."""
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700123
124 TARGET = 'chromite.scripts.deploy_chrome.DeployChrome'
Erik Chen75a2f492020-08-06 19:15:11 -0700125 ATTRS = ('_KillAshChromeIfNeeded', '_DisableRootfsVerification')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700126
David James88e6f032013-03-02 08:13:20 -0800127 def __init__(self):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700128 partial_mock.PartialMock.__init__(self)
Robert Flack1dc7ea82014-11-26 13:50:24 -0500129 self.remote_device_mock = remote_access_unittest.RemoteDeviceMock()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700130 # Target starts off as having rootfs verification enabled.
Ryan Cuie18f24f2012-12-03 18:39:55 -0800131 self.rsh_mock = remote_access_unittest.RemoteShMock()
David James88e6f032013-03-02 08:13:20 -0800132 self.rsh_mock.SetDefaultCmdResult(0)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700133 self.MockMountCmd(1)
David Haddock3151d912017-10-24 03:50:32 +0000134 self.rsh_mock.AddCmdResult(
Anushruth8d797672019-10-17 12:22:31 -0700135 deploy_chrome.LSOF_COMMAND_CHROME % (deploy_chrome._CHROME_DIR,), 1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700136
137 def MockMountCmd(self, returnvalue):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700138 self.rsh_mock.AddCmdResult(deploy_chrome.MOUNT_RW_COMMAND,
David James88e6f032013-03-02 08:13:20 -0800139 returnvalue)
140
141 def _DisableRootfsVerification(self, inst):
142 with mock.patch.object(time, 'sleep'):
143 self.backup['_DisableRootfsVerification'](inst)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700144
Ryan Cui4d6fca92012-12-13 16:41:56 -0800145 def PreStart(self):
Robert Flack1dc7ea82014-11-26 13:50:24 -0500146 self.remote_device_mock.start()
Ryan Cui4d6fca92012-12-13 16:41:56 -0800147 self.rsh_mock.start()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700148
Ryan Cui4d6fca92012-12-13 16:41:56 -0800149 def PreStop(self):
150 self.rsh_mock.stop()
Robert Flack1dc7ea82014-11-26 13:50:24 -0500151 self.remote_device_mock.stop()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700152
Erik Chen75a2f492020-08-06 19:15:11 -0700153 def _KillAshChromeIfNeeded(self, _inst):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700154 # Fully stub out for now.
155 pass
156
157
Ryan Cuief91e702013-02-04 12:06:36 -0800158class DeployTest(cros_test_lib.MockTempDirTestCase):
Steve Funge984a532013-11-25 17:09:25 -0800159 """Setup a deploy object with a GS-path for use in tests."""
160
Ryan Cuief91e702013-02-04 12:06:36 -0800161 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400162 options = _ParseCommandLine(args)
Ryan Cuia56a71e2012-10-18 18:40:35 -0700163 return deploy_chrome.DeployChrome(
164 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700165
166 def setUp(self):
Ryan Cuif1416f32013-01-22 18:43:41 -0800167 self.deploy_mock = self.StartPatcher(DeployChromeMock())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700168 self.deploy = self._GetDeployChrome(list(_REGULAR_TO) +
169 ['--board', _TARGET_BOARD, '--gs-path',
170 _GS_PATH, '--force', '--mount'])
Mike Frysingerfcca49e2021-03-17 01:09:20 -0400171 self.remote_reboot_mock = self.PatchObject(
172 remote_access.RemoteAccess, 'RemoteReboot', return_value=True)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700173
Avery Musbach3edff0e2020-03-27 13:35:53 -0700174
175class TestCheckIfBoardMatches(DeployTest):
176 """Testing checking whether the DUT board matches the target board."""
177
178 def testMatchedBoard(self):
179 """Test the case where the DUT board matches the target board."""
180 self.PatchObject(remote_access.ChromiumOSDevice, 'board', _TARGET_BOARD)
181 self.assertTrue(self.deploy.options.force)
182 self.deploy._CheckBoard()
183 self.deploy.options.force = False
184 self.deploy._CheckBoard()
185
186 def testMismatchedBoard(self):
187 """Test the case where the DUT board does not match the target board."""
188 self.PatchObject(remote_access.ChromiumOSDevice, 'board', 'cedar')
189 self.assertTrue(self.deploy.options.force)
190 self.deploy._CheckBoard()
191 self.deploy.options.force = False
192 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=True)
193 self.deploy._CheckBoard()
194 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=False)
195 self.assertRaises(deploy_chrome.DeployFailure, self.deploy._CheckBoard)
196
197
David James88e6f032013-03-02 08:13:20 -0800198class TestDisableRootfsVerification(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700199 """Testing disabling of rootfs verification and RO mode."""
200
David James88e6f032013-03-02 08:13:20 -0800201 def testDisableRootfsVerificationSuccess(self):
202 """Test the working case, disabling rootfs verification."""
203 self.deploy_mock.MockMountCmd(0)
204 self.deploy._DisableRootfsVerification()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700205 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700206
207 def testDisableRootfsVerificationFailure(self):
208 """Test failure to disable rootfs verification."""
Mike Frysinger27e21b72018-07-12 14:20:21 -0400209 # pylint: disable=unused-argument
Shuqian Zhao14e61092017-11-17 00:02:16 +0000210 def RaiseRunCommandError(timeout_sec=None):
Mike Frysinger929f3ba2019-09-12 03:24:59 -0400211 raise cros_build_lib.RunCommandError('Mock RunCommandError')
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800212 self.remote_reboot_mock.side_effect = RaiseRunCommandError
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700213 self.assertRaises(cros_build_lib.RunCommandError,
David James88e6f032013-03-02 08:13:20 -0800214 self.deploy._DisableRootfsVerification)
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800215 self.remote_reboot_mock.side_effect = None
Steven Bennettsca73efa2018-07-10 13:36:56 -0700216 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800217
218
219class TestMount(DeployTest):
220 """Testing mount success and failure."""
221
222 def testSuccess(self):
223 """Test case where we are able to mount as writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700224 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800225 self.deploy_mock.MockMountCmd(0)
226 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700227 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800228
229 def testMountError(self):
230 """Test that mount failure doesn't raise an exception by default."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700231 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700232 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500233 return_value=False, autospec=True)
David James88e6f032013-03-02 08:13:20 -0800234 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700235 self.assertTrue(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700236
237 def testMountRwFailure(self):
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500238 """Test that mount failure raises an exception if check=True."""
David James88e6f032013-03-02 08:13:20 -0800239 self.assertRaises(cros_build_lib.RunCommandError,
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500240 self.deploy._MountRootfsAsWritable, check=True)
Steven Bennettsca73efa2018-07-10 13:36:56 -0700241 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Robert Flack1dc7ea82014-11-26 13:50:24 -0500242
243 def testMountTempDir(self):
244 """Test that mount succeeds if target dir is writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700245 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700246 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500247 return_value=True, autospec=True)
248 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700249 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700250
251
Anushruth8d797672019-10-17 12:22:31 -0700252class TestMountTarget(DeployTest):
Mike Frysingerdf1d0b02019-11-12 17:44:12 -0500253 """Testing mount and umount command handling."""
Anushruth8d797672019-10-17 12:22:31 -0700254
255 def testMountTargetUmountFailure(self):
256 """Test error being thrown if umount fails.
257
258 Test that 'lsof' is run on mount-dir and 'mount -rbind' command is not run
259 if 'umount' cmd fails.
260 """
261 mount_dir = self.deploy.options.mount_dir
262 target_dir = self.deploy.options.target_dir
263 self.deploy_mock.rsh_mock.AddCmdResult(
264 deploy_chrome._UMOUNT_DIR_IF_MOUNTPOINT_CMD %
265 {'dir': mount_dir}, returncode=errno.EBUSY, stderr='Target is Busy')
266 self.deploy_mock.rsh_mock.AddCmdResult(deploy_chrome.LSOF_COMMAND %
267 (mount_dir,), returncode=0,
268 stdout='process ' + mount_dir)
269 # Check for RunCommandError being thrown.
270 self.assertRaises(cros_build_lib.RunCommandError,
271 self.deploy._MountTarget)
272 # Check for the 'mount -rbind' command not run.
273 self.deploy_mock.rsh_mock.assertCommandContains(
274 (deploy_chrome._BIND_TO_FINAL_DIR_CMD % (target_dir, mount_dir)),
275 expected=False)
276 # Check for lsof command being called.
277 self.deploy_mock.rsh_mock.assertCommandContains(
278 (deploy_chrome.LSOF_COMMAND % (mount_dir,)))
279
280
Ryan Cuief91e702013-02-04 12:06:36 -0800281class TestUiJobStarted(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700282 """Test detection of a running 'ui' job."""
283
Ryan Cuif2d1a582013-02-19 14:08:13 -0800284 def MockStatusUiCmd(self, **kwargs):
David Haddock3151d912017-10-24 03:50:32 +0000285 self.deploy_mock.rsh_mock.AddCmdResult('status ui', **kwargs)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700286
287 def testUiJobStartedFalse(self):
288 """Correct results with a stopped job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800289 self.MockStatusUiCmd(output='ui stop/waiting')
290 self.assertFalse(self.deploy._CheckUiJobStarted())
291
292 def testNoUiJob(self):
293 """Correct results when the job doesn't exist."""
294 self.MockStatusUiCmd(error='start: Unknown job: ui', returncode=1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700295 self.assertFalse(self.deploy._CheckUiJobStarted())
296
297 def testCheckRootfsWriteableTrue(self):
298 """Correct results with a running job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800299 self.MockStatusUiCmd(output='ui start/running, process 297')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700300 self.assertTrue(self.deploy._CheckUiJobStarted())
301
302
Ryan Cuief91e702013-02-04 12:06:36 -0800303class StagingTest(cros_test_lib.MockTempDirTestCase):
304 """Test user-mode and ebuild-mode staging functionality."""
305
306 def setUp(self):
Ryan Cuief91e702013-02-04 12:06:36 -0800307 self.staging_dir = os.path.join(self.tempdir, 'staging')
308 self.build_dir = os.path.join(self.tempdir, 'build_dir')
Avery Musbach3edff0e2020-03-27 13:35:53 -0700309 self.common_flags = ['--board', _TARGET_BOARD,
310 '--build-dir', self.build_dir, '--staging-only',
311 '--cache-dir', self.tempdir]
Ryan Cuia0215a72013-02-14 16:20:45 -0800312 self.sdk_mock = self.StartPatcher(cros_chrome_sdk_unittest.SDKFetcherMock())
Ryan Cui686ec052013-02-12 16:39:41 -0800313 self.PatchObject(
314 osutils, 'SourceEnvironment', autospec=True,
315 return_value={'STRIP': 'x86_64-cros-linux-gnu-strip'})
Ryan Cuief91e702013-02-04 12:06:36 -0800316
David Jamesa6e08892013-03-01 13:34:11 -0800317 def testSingleFileDeployFailure(self):
318 """Default staging enforces that mandatory files are copied"""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400319 options = _ParseCommandLine(self.common_flags)
David Jamesa6e08892013-03-01 13:34:11 -0800320 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
321 self.assertRaises(
322 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700323 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
Ryan Cuief91e702013-02-04 12:06:36 -0800324
David Jamesa6e08892013-03-01 13:34:11 -0800325 def testSloppyDeployFailure(self):
326 """Sloppy staging enforces that at least one file is copied."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400327 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800328 self.assertRaises(
329 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700330 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800331
332 def testSloppyDeploySuccess(self):
333 """Sloppy staging - stage one file."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400334 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800335 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
Steve Funge984a532013-11-25 17:09:25 -0800336 deploy_chrome._PrepareStagingDir(options, self.tempdir, self.staging_dir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700337 chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800338
Steve Funge984a532013-11-25 17:09:25 -0800339
340class DeployTestBuildDir(cros_test_lib.MockTempDirTestCase):
Daniel Erat1ae46382014-08-14 10:23:39 -0700341 """Set up a deploy object with a build-dir for use in deployment type tests"""
Steve Funge984a532013-11-25 17:09:25 -0800342
343 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400344 options = _ParseCommandLine(args)
Steve Funge984a532013-11-25 17:09:25 -0800345 return deploy_chrome.DeployChrome(
346 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
347
348 def setUp(self):
349 self.staging_dir = os.path.join(self.tempdir, 'staging')
350 self.build_dir = os.path.join(self.tempdir, 'build_dir')
351 self.deploy_mock = self.StartPatcher(DeployChromeMock())
352 self.deploy = self._GetDeployChrome(
Avery Musbach3edff0e2020-03-27 13:35:53 -0700353 list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
354 '--build-dir', self.build_dir, '--staging-only',
355 '--cache-dir', self.tempdir, '--sloppy'])
Steve Funge984a532013-11-25 17:09:25 -0800356
Daniel Erat1ae46382014-08-14 10:23:39 -0700357 def getCopyPath(self, source_path):
358 """Return a chrome_util.Path or None if not present."""
359 paths = [p for p in self.deploy.copy_paths if p.src == source_path]
360 return paths[0] if paths else None
Steve Funge984a532013-11-25 17:09:25 -0800361
Daniel Erat1ae46382014-08-14 10:23:39 -0700362class TestDeploymentType(DeployTestBuildDir):
Steve Funge984a532013-11-25 17:09:25 -0800363 """Test detection of deployment type using build dir."""
364
Daniel Erat1ae46382014-08-14 10:23:39 -0700365 def testAppShellDetection(self):
366 """Check for an app_shell deployment"""
367 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Funge984a532013-11-25 17:09:25 -0800368 makedirs=True)
369 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700370 self.assertTrue(self.getCopyPath('app_shell'))
371 self.assertFalse(self.getCopyPath('chrome'))
Steve Funge984a532013-11-25 17:09:25 -0800372
Daniel Erat1ae46382014-08-14 10:23:39 -0700373 def testChromeAndAppShellDetection(self):
Daniel Eratf53bd3a2016-12-02 11:28:36 -0700374 """Check for a chrome deployment when app_shell also exists."""
Steve Fung63d705d2014-03-16 03:14:03 -0700375 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
376 makedirs=True)
Daniel Erat1ae46382014-08-14 10:23:39 -0700377 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Fung63d705d2014-03-16 03:14:03 -0700378 makedirs=True)
379 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700380 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700381 self.assertFalse(self.getCopyPath('app_shell'))
Steve Fung63d705d2014-03-16 03:14:03 -0700382
Steve Funge984a532013-11-25 17:09:25 -0800383 def testChromeDetection(self):
384 """Check for a regular chrome deployment"""
385 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
386 makedirs=True)
387 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700388 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700389 self.assertFalse(self.getCopyPath('app_shell'))
Ben Pastenee484b342020-06-30 18:29:27 -0700390
391
392class TestDeployTestBinaries(cros_test_lib.RunCommandTempDirTestCase):
393 """Tests _DeployTestBinaries()."""
394
395 def setUp(self):
396 options = _ParseCommandLine(list(_REGULAR_TO) + [
397 '--board', _TARGET_BOARD, '--force', '--mount',
398 '--build-dir', os.path.join(self.tempdir, 'build_dir'),
399 '--nostrip'])
400 self.deploy = deploy_chrome.DeployChrome(
401 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
402
Brian Sheedy86f12342020-10-29 15:30:02 -0700403 def _SimulateBinaries(self):
404 # Ensure the staging dir contains the right binaries to copy over.
Ben Pastenee484b342020-06-30 18:29:27 -0700405 test_binaries = [
406 'run_a_tests',
407 'run_b_tests',
408 'run_c_tests',
409 ]
410 # Simulate having the binaries both on the device and in our local build
411 # dir.
412 self.rc.AddCmdResult(
413 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD),
414 stdout='\n'.join(test_binaries))
415 for binary in test_binaries:
416 osutils.Touch(os.path.join(self.deploy.options.build_dir, binary),
417 makedirs=True, mode=0o700)
Brian Sheedy86f12342020-10-29 15:30:02 -0700418 return test_binaries
Ben Pastenee484b342020-06-30 18:29:27 -0700419
Brian Sheedy86f12342020-10-29 15:30:02 -0700420 def _AssertBinariesInStagingDir(self, test_binaries):
Ben Pastenee484b342020-06-30 18:29:27 -0700421 # Ensure the binaries were placed in the staging dir used to copy them over.
422 staging_dir = os.path.join(
423 self.tempdir, os.path.basename(deploy_chrome._CHROME_TEST_BIN_DIR))
424 for binary in test_binaries:
425 self.assertIn(binary, os.listdir(staging_dir))
Erik Chen75a2f492020-08-06 19:15:11 -0700426
Brian Sheedy86f12342020-10-29 15:30:02 -0700427 def testFindError(self):
428 """Ensure an error is thrown if we can't inspect the device."""
429 self.rc.AddCmdResult(
430 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD), 1)
431 self.assertRaises(
432 deploy_chrome.DeployFailure, self.deploy._DeployTestBinaries)
433
434 def testSuccess(self):
435 """Ensure that the happy path succeeds as expected."""
436 test_binaries = self._SimulateBinaries()
437 self.deploy._DeployTestBinaries()
438 self._AssertBinariesInStagingDir(test_binaries)
439
440 def testRetrySuccess(self):
441 """Ensure that a transient exception still results in success."""
442 # Raises a RunCommandError on its first invocation, but passes on subsequent
443 # calls.
444 def SideEffect(*args, **kwargs):
Yuke Liaobe6bac32020-12-26 22:16:49 -0800445 # pylint: disable=unused-argument
Brian Sheedy86f12342020-10-29 15:30:02 -0700446 if not SideEffect.called:
447 SideEffect.called = True
448 raise cros_build_lib.RunCommandError('fail')
449 SideEffect.called = False
450
451 test_binaries = self._SimulateBinaries()
452 with mock.patch.object(
453 remote_access.ChromiumOSDevice, 'CopyToDevice',
454 side_effect=SideEffect) as copy_mock:
455 self.deploy._DeployTestBinaries()
456 self.assertEqual(copy_mock.call_count, 2)
457 self._AssertBinariesInStagingDir(test_binaries)
458
459 def testRetryFailure(self):
460 """Ensure that consistent exceptions result in failure."""
461 self._SimulateBinaries()
462 with self.assertRaises(cros_build_lib.RunCommandError):
463 with mock.patch.object(
464 remote_access.ChromiumOSDevice, 'CopyToDevice',
465 side_effect=cros_build_lib.RunCommandError('fail')):
466 self.deploy._DeployTestBinaries()
467
Erik Chen75a2f492020-08-06 19:15:11 -0700468
469class LacrosPerformTest(cros_test_lib.RunCommandTempDirTestCase):
470 """Line coverage for Perform() method with --lacros option."""
471
472 def setUp(self):
Yuke Liao24fc60c2020-12-26 22:16:49 -0800473 self.deploy = None
474 self._ran_start_command = False
475 self.StartPatcher(parallel_unittest.ParallelMock())
476
477 def start_ui_side_effect(*args, **kwargs):
478 # pylint: disable=unused-argument
479 self._ran_start_command = True
480
481 self.rc.AddCmdResult(partial_mock.In('start ui'),
482 side_effect=start_ui_side_effect)
483
484 def prepareDeploy(self, options=None):
485 if not options:
486 options = _ParseCommandLine([
487 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
488 '--device', 'monkey'
489 ])
Erik Chen75a2f492020-08-06 19:15:11 -0700490 self.deploy = deploy_chrome.DeployChrome(
491 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
492
493 # These methods being mocked are all side effects expected for a --lacros
494 # deploy.
495 self.deploy._EnsureTargetDir = mock.Mock()
496 self.deploy._GetDeviceInfo = mock.Mock()
497 self.deploy._CheckConnection = mock.Mock()
498 self.deploy._MountRootfsAsWritable = mock.Mock()
499 self.deploy._PrepareStagingDir = mock.Mock()
500 self.deploy._CheckDeviceFreeSpace = mock.Mock()
Yuke Liaobe6bac32020-12-26 22:16:49 -0800501 self.deploy._KillAshChromeIfNeeded = mock.Mock()
Erik Chen75a2f492020-08-06 19:15:11 -0700502
503 def testConfNotModified(self):
504 """When the conf file is not modified we don't restart chrome ."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800505 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700506 self.deploy.Perform()
507 self.deploy._KillAshChromeIfNeeded.assert_not_called()
508 self.assertFalse(self._ran_start_command)
509
510 def testConfModified(self):
511 """When the conf file is modified we restart chrome."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800512 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700513
514 # We intentionally add '\n' to MODIFIED_CONF_FILE to simulate echo adding a
515 # newline when invoked in the shell.
516 self.rc.AddCmdResult(
517 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
518 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
519
520 self.deploy.Perform()
521 self.deploy._KillAshChromeIfNeeded.assert_called()
522 self.assertTrue(self._ran_start_command)
Yuke Liao24fc60c2020-12-26 22:16:49 -0800523
524 def testSkipModifyingConf(self):
525 """SKip modifying the config file when the argument is specified."""
526 self.prepareDeploy(
527 _ParseCommandLine([
528 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
529 '--device', 'monkey', '--skip-modifying-config-file'
530 ]))
531
532 self.rc.AddCmdResult(
533 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
534 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
535
536 self.deploy.Perform()
537 self.deploy._KillAshChromeIfNeeded.assert_not_called()
538 self.assertFalse(self._ran_start_command)