blob: a81ac8cd2fdf3e3e1741d48328001704a3f06ce2 [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'])
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800171 self.remote_reboot_mock = \
172 self.PatchObject(remote_access.RemoteAccess, 'RemoteReboot',
173 return_value=True)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700174
Avery Musbach3edff0e2020-03-27 13:35:53 -0700175
176class TestCheckIfBoardMatches(DeployTest):
177 """Testing checking whether the DUT board matches the target board."""
178
179 def testMatchedBoard(self):
180 """Test the case where the DUT board matches the target board."""
181 self.PatchObject(remote_access.ChromiumOSDevice, 'board', _TARGET_BOARD)
182 self.assertTrue(self.deploy.options.force)
183 self.deploy._CheckBoard()
184 self.deploy.options.force = False
185 self.deploy._CheckBoard()
186
187 def testMismatchedBoard(self):
188 """Test the case where the DUT board does not match the target board."""
189 self.PatchObject(remote_access.ChromiumOSDevice, 'board', 'cedar')
190 self.assertTrue(self.deploy.options.force)
191 self.deploy._CheckBoard()
192 self.deploy.options.force = False
193 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=True)
194 self.deploy._CheckBoard()
195 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=False)
196 self.assertRaises(deploy_chrome.DeployFailure, self.deploy._CheckBoard)
197
198
David James88e6f032013-03-02 08:13:20 -0800199class TestDisableRootfsVerification(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700200 """Testing disabling of rootfs verification and RO mode."""
201
David James88e6f032013-03-02 08:13:20 -0800202 def testDisableRootfsVerificationSuccess(self):
203 """Test the working case, disabling rootfs verification."""
204 self.deploy_mock.MockMountCmd(0)
205 self.deploy._DisableRootfsVerification()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700206 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700207
208 def testDisableRootfsVerificationFailure(self):
209 """Test failure to disable rootfs verification."""
Mike Frysinger27e21b72018-07-12 14:20:21 -0400210 # pylint: disable=unused-argument
Shuqian Zhao14e61092017-11-17 00:02:16 +0000211 def RaiseRunCommandError(timeout_sec=None):
Mike Frysinger929f3ba2019-09-12 03:24:59 -0400212 raise cros_build_lib.RunCommandError('Mock RunCommandError')
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800213 self.remote_reboot_mock.side_effect = RaiseRunCommandError
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700214 self.assertRaises(cros_build_lib.RunCommandError,
David James88e6f032013-03-02 08:13:20 -0800215 self.deploy._DisableRootfsVerification)
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800216 self.remote_reboot_mock.side_effect = None
Steven Bennettsca73efa2018-07-10 13:36:56 -0700217 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800218
219
220class TestMount(DeployTest):
221 """Testing mount success and failure."""
222
223 def testSuccess(self):
224 """Test case where we are able to mount as writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700225 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800226 self.deploy_mock.MockMountCmd(0)
227 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700228 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800229
230 def testMountError(self):
231 """Test that mount failure doesn't raise an exception by default."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700232 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700233 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500234 return_value=False, autospec=True)
David James88e6f032013-03-02 08:13:20 -0800235 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700236 self.assertTrue(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700237
238 def testMountRwFailure(self):
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500239 """Test that mount failure raises an exception if check=True."""
David James88e6f032013-03-02 08:13:20 -0800240 self.assertRaises(cros_build_lib.RunCommandError,
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500241 self.deploy._MountRootfsAsWritable, check=True)
Steven Bennettsca73efa2018-07-10 13:36:56 -0700242 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Robert Flack1dc7ea82014-11-26 13:50:24 -0500243
244 def testMountTempDir(self):
245 """Test that mount succeeds if target dir is writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700246 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700247 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500248 return_value=True, autospec=True)
249 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700250 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700251
252
Anushruth8d797672019-10-17 12:22:31 -0700253class TestMountTarget(DeployTest):
Mike Frysingerdf1d0b02019-11-12 17:44:12 -0500254 """Testing mount and umount command handling."""
Anushruth8d797672019-10-17 12:22:31 -0700255
256 def testMountTargetUmountFailure(self):
257 """Test error being thrown if umount fails.
258
259 Test that 'lsof' is run on mount-dir and 'mount -rbind' command is not run
260 if 'umount' cmd fails.
261 """
262 mount_dir = self.deploy.options.mount_dir
263 target_dir = self.deploy.options.target_dir
264 self.deploy_mock.rsh_mock.AddCmdResult(
265 deploy_chrome._UMOUNT_DIR_IF_MOUNTPOINT_CMD %
266 {'dir': mount_dir}, returncode=errno.EBUSY, stderr='Target is Busy')
267 self.deploy_mock.rsh_mock.AddCmdResult(deploy_chrome.LSOF_COMMAND %
268 (mount_dir,), returncode=0,
269 stdout='process ' + mount_dir)
270 # Check for RunCommandError being thrown.
271 self.assertRaises(cros_build_lib.RunCommandError,
272 self.deploy._MountTarget)
273 # Check for the 'mount -rbind' command not run.
274 self.deploy_mock.rsh_mock.assertCommandContains(
275 (deploy_chrome._BIND_TO_FINAL_DIR_CMD % (target_dir, mount_dir)),
276 expected=False)
277 # Check for lsof command being called.
278 self.deploy_mock.rsh_mock.assertCommandContains(
279 (deploy_chrome.LSOF_COMMAND % (mount_dir,)))
280
281
Ryan Cuief91e702013-02-04 12:06:36 -0800282class TestUiJobStarted(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700283 """Test detection of a running 'ui' job."""
284
Ryan Cuif2d1a582013-02-19 14:08:13 -0800285 def MockStatusUiCmd(self, **kwargs):
David Haddock3151d912017-10-24 03:50:32 +0000286 self.deploy_mock.rsh_mock.AddCmdResult('status ui', **kwargs)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700287
288 def testUiJobStartedFalse(self):
289 """Correct results with a stopped job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800290 self.MockStatusUiCmd(output='ui stop/waiting')
291 self.assertFalse(self.deploy._CheckUiJobStarted())
292
293 def testNoUiJob(self):
294 """Correct results when the job doesn't exist."""
295 self.MockStatusUiCmd(error='start: Unknown job: ui', returncode=1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700296 self.assertFalse(self.deploy._CheckUiJobStarted())
297
298 def testCheckRootfsWriteableTrue(self):
299 """Correct results with a running job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800300 self.MockStatusUiCmd(output='ui start/running, process 297')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700301 self.assertTrue(self.deploy._CheckUiJobStarted())
302
303
Ryan Cuief91e702013-02-04 12:06:36 -0800304class StagingTest(cros_test_lib.MockTempDirTestCase):
305 """Test user-mode and ebuild-mode staging functionality."""
306
307 def setUp(self):
Ryan Cuief91e702013-02-04 12:06:36 -0800308 self.staging_dir = os.path.join(self.tempdir, 'staging')
309 self.build_dir = os.path.join(self.tempdir, 'build_dir')
Avery Musbach3edff0e2020-03-27 13:35:53 -0700310 self.common_flags = ['--board', _TARGET_BOARD,
311 '--build-dir', self.build_dir, '--staging-only',
312 '--cache-dir', self.tempdir]
Ryan Cuia0215a72013-02-14 16:20:45 -0800313 self.sdk_mock = self.StartPatcher(cros_chrome_sdk_unittest.SDKFetcherMock())
Ryan Cui686ec052013-02-12 16:39:41 -0800314 self.PatchObject(
315 osutils, 'SourceEnvironment', autospec=True,
316 return_value={'STRIP': 'x86_64-cros-linux-gnu-strip'})
Ryan Cuief91e702013-02-04 12:06:36 -0800317
David Jamesa6e08892013-03-01 13:34:11 -0800318 def testSingleFileDeployFailure(self):
319 """Default staging enforces that mandatory files are copied"""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400320 options = _ParseCommandLine(self.common_flags)
David Jamesa6e08892013-03-01 13:34:11 -0800321 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
322 self.assertRaises(
323 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700324 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
Ryan Cuief91e702013-02-04 12:06:36 -0800325
David Jamesa6e08892013-03-01 13:34:11 -0800326 def testSloppyDeployFailure(self):
327 """Sloppy staging enforces that at least one file is copied."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400328 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800329 self.assertRaises(
330 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700331 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800332
333 def testSloppyDeploySuccess(self):
334 """Sloppy staging - stage one file."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400335 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800336 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
Steve Funge984a532013-11-25 17:09:25 -0800337 deploy_chrome._PrepareStagingDir(options, self.tempdir, self.staging_dir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700338 chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800339
Steve Funge984a532013-11-25 17:09:25 -0800340
341class DeployTestBuildDir(cros_test_lib.MockTempDirTestCase):
Daniel Erat1ae46382014-08-14 10:23:39 -0700342 """Set up a deploy object with a build-dir for use in deployment type tests"""
Steve Funge984a532013-11-25 17:09:25 -0800343
344 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400345 options = _ParseCommandLine(args)
Steve Funge984a532013-11-25 17:09:25 -0800346 return deploy_chrome.DeployChrome(
347 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
348
349 def setUp(self):
350 self.staging_dir = os.path.join(self.tempdir, 'staging')
351 self.build_dir = os.path.join(self.tempdir, 'build_dir')
352 self.deploy_mock = self.StartPatcher(DeployChromeMock())
353 self.deploy = self._GetDeployChrome(
Avery Musbach3edff0e2020-03-27 13:35:53 -0700354 list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
355 '--build-dir', self.build_dir, '--staging-only',
356 '--cache-dir', self.tempdir, '--sloppy'])
Steve Funge984a532013-11-25 17:09:25 -0800357
Daniel Erat1ae46382014-08-14 10:23:39 -0700358 def getCopyPath(self, source_path):
359 """Return a chrome_util.Path or None if not present."""
360 paths = [p for p in self.deploy.copy_paths if p.src == source_path]
361 return paths[0] if paths else None
Steve Funge984a532013-11-25 17:09:25 -0800362
Daniel Erat1ae46382014-08-14 10:23:39 -0700363class TestDeploymentType(DeployTestBuildDir):
Steve Funge984a532013-11-25 17:09:25 -0800364 """Test detection of deployment type using build dir."""
365
Daniel Erat1ae46382014-08-14 10:23:39 -0700366 def testAppShellDetection(self):
367 """Check for an app_shell deployment"""
368 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Funge984a532013-11-25 17:09:25 -0800369 makedirs=True)
370 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700371 self.assertTrue(self.getCopyPath('app_shell'))
372 self.assertFalse(self.getCopyPath('chrome'))
Steve Funge984a532013-11-25 17:09:25 -0800373
Daniel Erat1ae46382014-08-14 10:23:39 -0700374 def testChromeAndAppShellDetection(self):
Daniel Eratf53bd3a2016-12-02 11:28:36 -0700375 """Check for a chrome deployment when app_shell also exists."""
Steve Fung63d705d2014-03-16 03:14:03 -0700376 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
377 makedirs=True)
Daniel Erat1ae46382014-08-14 10:23:39 -0700378 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Fung63d705d2014-03-16 03:14:03 -0700379 makedirs=True)
380 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700381 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700382 self.assertFalse(self.getCopyPath('app_shell'))
Steve Fung63d705d2014-03-16 03:14:03 -0700383
Steve Funge984a532013-11-25 17:09:25 -0800384 def testChromeDetection(self):
385 """Check for a regular chrome deployment"""
386 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
387 makedirs=True)
388 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700389 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700390 self.assertFalse(self.getCopyPath('app_shell'))
Ben Pastenee484b342020-06-30 18:29:27 -0700391
392
393class TestDeployTestBinaries(cros_test_lib.RunCommandTempDirTestCase):
394 """Tests _DeployTestBinaries()."""
395
396 def setUp(self):
397 options = _ParseCommandLine(list(_REGULAR_TO) + [
398 '--board', _TARGET_BOARD, '--force', '--mount',
399 '--build-dir', os.path.join(self.tempdir, 'build_dir'),
400 '--nostrip'])
401 self.deploy = deploy_chrome.DeployChrome(
402 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
403
Brian Sheedy86f12342020-10-29 15:30:02 -0700404 def _SimulateBinaries(self):
405 # Ensure the staging dir contains the right binaries to copy over.
Ben Pastenee484b342020-06-30 18:29:27 -0700406 test_binaries = [
407 'run_a_tests',
408 'run_b_tests',
409 'run_c_tests',
410 ]
411 # Simulate having the binaries both on the device and in our local build
412 # dir.
413 self.rc.AddCmdResult(
414 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD),
415 stdout='\n'.join(test_binaries))
416 for binary in test_binaries:
417 osutils.Touch(os.path.join(self.deploy.options.build_dir, binary),
418 makedirs=True, mode=0o700)
Brian Sheedy86f12342020-10-29 15:30:02 -0700419 return test_binaries
Ben Pastenee484b342020-06-30 18:29:27 -0700420
Brian Sheedy86f12342020-10-29 15:30:02 -0700421 def _AssertBinariesInStagingDir(self, test_binaries):
Ben Pastenee484b342020-06-30 18:29:27 -0700422 # Ensure the binaries were placed in the staging dir used to copy them over.
423 staging_dir = os.path.join(
424 self.tempdir, os.path.basename(deploy_chrome._CHROME_TEST_BIN_DIR))
425 for binary in test_binaries:
426 self.assertIn(binary, os.listdir(staging_dir))
Erik Chen75a2f492020-08-06 19:15:11 -0700427
Brian Sheedy86f12342020-10-29 15:30:02 -0700428 def testFindError(self):
429 """Ensure an error is thrown if we can't inspect the device."""
430 self.rc.AddCmdResult(
431 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD), 1)
432 self.assertRaises(
433 deploy_chrome.DeployFailure, self.deploy._DeployTestBinaries)
434
435 def testSuccess(self):
436 """Ensure that the happy path succeeds as expected."""
437 test_binaries = self._SimulateBinaries()
438 self.deploy._DeployTestBinaries()
439 self._AssertBinariesInStagingDir(test_binaries)
440
441 def testRetrySuccess(self):
442 """Ensure that a transient exception still results in success."""
443 # Raises a RunCommandError on its first invocation, but passes on subsequent
444 # calls.
445 def SideEffect(*args, **kwargs):
Yuke Liaobe6bac32020-12-26 22:16:49 -0800446 # pylint: disable=unused-argument
Brian Sheedy86f12342020-10-29 15:30:02 -0700447 if not SideEffect.called:
448 SideEffect.called = True
449 raise cros_build_lib.RunCommandError('fail')
450 SideEffect.called = False
451
452 test_binaries = self._SimulateBinaries()
453 with mock.patch.object(
454 remote_access.ChromiumOSDevice, 'CopyToDevice',
455 side_effect=SideEffect) as copy_mock:
456 self.deploy._DeployTestBinaries()
457 self.assertEqual(copy_mock.call_count, 2)
458 self._AssertBinariesInStagingDir(test_binaries)
459
460 def testRetryFailure(self):
461 """Ensure that consistent exceptions result in failure."""
462 self._SimulateBinaries()
463 with self.assertRaises(cros_build_lib.RunCommandError):
464 with mock.patch.object(
465 remote_access.ChromiumOSDevice, 'CopyToDevice',
466 side_effect=cros_build_lib.RunCommandError('fail')):
467 self.deploy._DeployTestBinaries()
468
Erik Chen75a2f492020-08-06 19:15:11 -0700469
470class LacrosPerformTest(cros_test_lib.RunCommandTempDirTestCase):
471 """Line coverage for Perform() method with --lacros option."""
472
473 def setUp(self):
Yuke Liao24fc60c2020-12-26 22:16:49 -0800474 self.deploy = None
475 self._ran_start_command = False
476 self.StartPatcher(parallel_unittest.ParallelMock())
477
478 def start_ui_side_effect(*args, **kwargs):
479 # pylint: disable=unused-argument
480 self._ran_start_command = True
481
482 self.rc.AddCmdResult(partial_mock.In('start ui'),
483 side_effect=start_ui_side_effect)
484
485 def prepareDeploy(self, options=None):
486 if not options:
487 options = _ParseCommandLine([
488 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
489 '--device', 'monkey'
490 ])
Erik Chen75a2f492020-08-06 19:15:11 -0700491 self.deploy = deploy_chrome.DeployChrome(
492 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
493
494 # These methods being mocked are all side effects expected for a --lacros
495 # deploy.
496 self.deploy._EnsureTargetDir = mock.Mock()
497 self.deploy._GetDeviceInfo = mock.Mock()
498 self.deploy._CheckConnection = mock.Mock()
499 self.deploy._MountRootfsAsWritable = mock.Mock()
500 self.deploy._PrepareStagingDir = mock.Mock()
501 self.deploy._CheckDeviceFreeSpace = mock.Mock()
Yuke Liaobe6bac32020-12-26 22:16:49 -0800502 self.deploy._KillAshChromeIfNeeded = mock.Mock()
Erik Chen75a2f492020-08-06 19:15:11 -0700503
504 def testConfNotModified(self):
505 """When the conf file is not modified we don't restart chrome ."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800506 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700507 self.deploy.Perform()
508 self.deploy._KillAshChromeIfNeeded.assert_not_called()
509 self.assertFalse(self._ran_start_command)
510
511 def testConfModified(self):
512 """When the conf file is modified we restart chrome."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800513 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700514
515 # We intentionally add '\n' to MODIFIED_CONF_FILE to simulate echo adding a
516 # newline when invoked in the shell.
517 self.rc.AddCmdResult(
518 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
519 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
520
521 self.deploy.Perform()
522 self.deploy._KillAshChromeIfNeeded.assert_called()
523 self.assertTrue(self._ran_start_command)
Yuke Liao24fc60c2020-12-26 22:16:49 -0800524
525 def testSkipModifyingConf(self):
526 """SKip modifying the config file when the argument is specified."""
527 self.prepareDeploy(
528 _ParseCommandLine([
529 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
530 '--device', 'monkey', '--skip-modifying-config-file'
531 ]))
532
533 self.rc.AddCmdResult(
534 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
535 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
536
537 self.deploy.Perform()
538 self.deploy._KillAshChromeIfNeeded.assert_not_called()
539 self.assertFalse(self._ran_start_command)