blob: 4f283d9b106c275541867ea221655eef79f20765 [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
Ben Pastene3bd3e5e2020-08-10 14:40:43 -070070 def testToAndDevice(self):
71 """Test no target specified."""
72 argv = ['--board', _TARGET_BOARD, '--build-dir', '/path/to/nowhere',
73 '--to', 'localhost', '--device', 'localhost']
74 self.assertParseError(argv)
75
Erik Chen75a2f492020-08-06 19:15:11 -070076 def testLacros(self):
77 """Test basic lacros invocation."""
78 argv = ['--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
Ben Pastene0ff0fa42020-08-14 15:10:07 -070079 '--device', 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070080 options = _ParseCommandLine(argv)
81 self.assertTrue(options.lacros)
82 self.assertEqual(options.target_dir, deploy_chrome.LACROS_DIR)
83
84 def testLacrosRequiresNostrip(self):
85 """Lacros requires --nostrip"""
Ben Pastene0ff0fa42020-08-14 15:10:07 -070086 argv = ['--lacros', '--build-dir', '/path/to/nowhere', '--device',
87 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070088 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
89 check_attrs={'code': 2})
90
Ryan Cuief91e702013-02-04 12:06:36 -080091 def assertParseError(self, argv):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070092 with self.OutputCapturer():
93 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
94 check_attrs={'code': 2})
95
Thiago Goncales12793312013-05-23 11:26:17 -070096 def testMountOptionSetsTargetDir(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.target_dir, None)
101
102 def testMountOptionSetsMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700103 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
104 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400105 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700106 self.assertIsNot(options.mount_dir, None)
107
108 def testMountOptionDoesNotOverrideTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700109 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
110 '--mount', '--target-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.target_dir, '/foo/bar/cow')
113
114 def testMountOptionDoesNotOverrideMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700115 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
116 '--mount', '--mount-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400117 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700118 self.assertEqual(options.mount_dir, '/foo/bar/cow')
119
Adrian Eldera2c548a2017-11-07 19:01:29 -0500120 def testSshIdentityOptionSetsOption(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700121 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
122 '--private-key', '/foo/bar/key',
Bernie Thompson93b9ee62018-02-21 14:56:16 -0800123 '--build-dir', '/path/to/nowhere']
Adrian Eldera2c548a2017-11-07 19:01:29 -0500124 options = _ParseCommandLine(argv)
125 self.assertEqual(options.private_key, '/foo/bar/key')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700126
127class DeployChromeMock(partial_mock.PartialMock):
Steve Funge984a532013-11-25 17:09:25 -0800128 """Deploy Chrome Mock Class."""
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700129
130 TARGET = 'chromite.scripts.deploy_chrome.DeployChrome'
Erik Chen75a2f492020-08-06 19:15:11 -0700131 ATTRS = ('_KillAshChromeIfNeeded', '_DisableRootfsVerification')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700132
David James88e6f032013-03-02 08:13:20 -0800133 def __init__(self):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700134 partial_mock.PartialMock.__init__(self)
Robert Flack1dc7ea82014-11-26 13:50:24 -0500135 self.remote_device_mock = remote_access_unittest.RemoteDeviceMock()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700136 # Target starts off as having rootfs verification enabled.
Ryan Cuie18f24f2012-12-03 18:39:55 -0800137 self.rsh_mock = remote_access_unittest.RemoteShMock()
David James88e6f032013-03-02 08:13:20 -0800138 self.rsh_mock.SetDefaultCmdResult(0)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700139 self.MockMountCmd(1)
David Haddock3151d912017-10-24 03:50:32 +0000140 self.rsh_mock.AddCmdResult(
Anushruth8d797672019-10-17 12:22:31 -0700141 deploy_chrome.LSOF_COMMAND_CHROME % (deploy_chrome._CHROME_DIR,), 1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700142
143 def MockMountCmd(self, returnvalue):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700144 self.rsh_mock.AddCmdResult(deploy_chrome.MOUNT_RW_COMMAND,
David James88e6f032013-03-02 08:13:20 -0800145 returnvalue)
146
147 def _DisableRootfsVerification(self, inst):
148 with mock.patch.object(time, 'sleep'):
149 self.backup['_DisableRootfsVerification'](inst)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700150
Ryan Cui4d6fca92012-12-13 16:41:56 -0800151 def PreStart(self):
Robert Flack1dc7ea82014-11-26 13:50:24 -0500152 self.remote_device_mock.start()
Ryan Cui4d6fca92012-12-13 16:41:56 -0800153 self.rsh_mock.start()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700154
Ryan Cui4d6fca92012-12-13 16:41:56 -0800155 def PreStop(self):
156 self.rsh_mock.stop()
Robert Flack1dc7ea82014-11-26 13:50:24 -0500157 self.remote_device_mock.stop()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700158
Erik Chen75a2f492020-08-06 19:15:11 -0700159 def _KillAshChromeIfNeeded(self, _inst):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700160 # Fully stub out for now.
161 pass
162
163
Ryan Cuief91e702013-02-04 12:06:36 -0800164class DeployTest(cros_test_lib.MockTempDirTestCase):
Steve Funge984a532013-11-25 17:09:25 -0800165 """Setup a deploy object with a GS-path for use in tests."""
166
Ryan Cuief91e702013-02-04 12:06:36 -0800167 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400168 options = _ParseCommandLine(args)
Ryan Cuia56a71e2012-10-18 18:40:35 -0700169 return deploy_chrome.DeployChrome(
170 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700171
172 def setUp(self):
Ryan Cuif1416f32013-01-22 18:43:41 -0800173 self.deploy_mock = self.StartPatcher(DeployChromeMock())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700174 self.deploy = self._GetDeployChrome(list(_REGULAR_TO) +
175 ['--board', _TARGET_BOARD, '--gs-path',
176 _GS_PATH, '--force', '--mount'])
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800177 self.remote_reboot_mock = \
178 self.PatchObject(remote_access.RemoteAccess, 'RemoteReboot',
179 return_value=True)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700180
Avery Musbach3edff0e2020-03-27 13:35:53 -0700181
182class TestCheckIfBoardMatches(DeployTest):
183 """Testing checking whether the DUT board matches the target board."""
184
185 def testMatchedBoard(self):
186 """Test the case where the DUT board matches the target board."""
187 self.PatchObject(remote_access.ChromiumOSDevice, 'board', _TARGET_BOARD)
188 self.assertTrue(self.deploy.options.force)
189 self.deploy._CheckBoard()
190 self.deploy.options.force = False
191 self.deploy._CheckBoard()
192
193 def testMismatchedBoard(self):
194 """Test the case where the DUT board does not match the target board."""
195 self.PatchObject(remote_access.ChromiumOSDevice, 'board', 'cedar')
196 self.assertTrue(self.deploy.options.force)
197 self.deploy._CheckBoard()
198 self.deploy.options.force = False
199 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=True)
200 self.deploy._CheckBoard()
201 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=False)
202 self.assertRaises(deploy_chrome.DeployFailure, self.deploy._CheckBoard)
203
204
David James88e6f032013-03-02 08:13:20 -0800205class TestDisableRootfsVerification(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700206 """Testing disabling of rootfs verification and RO mode."""
207
David James88e6f032013-03-02 08:13:20 -0800208 def testDisableRootfsVerificationSuccess(self):
209 """Test the working case, disabling rootfs verification."""
210 self.deploy_mock.MockMountCmd(0)
211 self.deploy._DisableRootfsVerification()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700212 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700213
214 def testDisableRootfsVerificationFailure(self):
215 """Test failure to disable rootfs verification."""
Mike Frysinger27e21b72018-07-12 14:20:21 -0400216 # pylint: disable=unused-argument
Shuqian Zhao14e61092017-11-17 00:02:16 +0000217 def RaiseRunCommandError(timeout_sec=None):
Mike Frysinger929f3ba2019-09-12 03:24:59 -0400218 raise cros_build_lib.RunCommandError('Mock RunCommandError')
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800219 self.remote_reboot_mock.side_effect = RaiseRunCommandError
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700220 self.assertRaises(cros_build_lib.RunCommandError,
David James88e6f032013-03-02 08:13:20 -0800221 self.deploy._DisableRootfsVerification)
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800222 self.remote_reboot_mock.side_effect = None
Steven Bennettsca73efa2018-07-10 13:36:56 -0700223 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800224
225
226class TestMount(DeployTest):
227 """Testing mount success and failure."""
228
229 def testSuccess(self):
230 """Test case where we are able to mount as writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700231 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800232 self.deploy_mock.MockMountCmd(0)
233 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700234 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800235
236 def testMountError(self):
237 """Test that mount failure doesn't raise an exception by default."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700238 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700239 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500240 return_value=False, autospec=True)
David James88e6f032013-03-02 08:13:20 -0800241 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700242 self.assertTrue(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700243
244 def testMountRwFailure(self):
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500245 """Test that mount failure raises an exception if check=True."""
David James88e6f032013-03-02 08:13:20 -0800246 self.assertRaises(cros_build_lib.RunCommandError,
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500247 self.deploy._MountRootfsAsWritable, check=True)
Steven Bennettsca73efa2018-07-10 13:36:56 -0700248 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Robert Flack1dc7ea82014-11-26 13:50:24 -0500249
250 def testMountTempDir(self):
251 """Test that mount succeeds if target dir is writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700252 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700253 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500254 return_value=True, autospec=True)
255 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700256 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700257
258
Anushruth8d797672019-10-17 12:22:31 -0700259class TestMountTarget(DeployTest):
Mike Frysingerdf1d0b02019-11-12 17:44:12 -0500260 """Testing mount and umount command handling."""
Anushruth8d797672019-10-17 12:22:31 -0700261
262 def testMountTargetUmountFailure(self):
263 """Test error being thrown if umount fails.
264
265 Test that 'lsof' is run on mount-dir and 'mount -rbind' command is not run
266 if 'umount' cmd fails.
267 """
268 mount_dir = self.deploy.options.mount_dir
269 target_dir = self.deploy.options.target_dir
270 self.deploy_mock.rsh_mock.AddCmdResult(
271 deploy_chrome._UMOUNT_DIR_IF_MOUNTPOINT_CMD %
272 {'dir': mount_dir}, returncode=errno.EBUSY, stderr='Target is Busy')
273 self.deploy_mock.rsh_mock.AddCmdResult(deploy_chrome.LSOF_COMMAND %
274 (mount_dir,), returncode=0,
275 stdout='process ' + mount_dir)
276 # Check for RunCommandError being thrown.
277 self.assertRaises(cros_build_lib.RunCommandError,
278 self.deploy._MountTarget)
279 # Check for the 'mount -rbind' command not run.
280 self.deploy_mock.rsh_mock.assertCommandContains(
281 (deploy_chrome._BIND_TO_FINAL_DIR_CMD % (target_dir, mount_dir)),
282 expected=False)
283 # Check for lsof command being called.
284 self.deploy_mock.rsh_mock.assertCommandContains(
285 (deploy_chrome.LSOF_COMMAND % (mount_dir,)))
286
287
Ryan Cuief91e702013-02-04 12:06:36 -0800288class TestUiJobStarted(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700289 """Test detection of a running 'ui' job."""
290
Ryan Cuif2d1a582013-02-19 14:08:13 -0800291 def MockStatusUiCmd(self, **kwargs):
David Haddock3151d912017-10-24 03:50:32 +0000292 self.deploy_mock.rsh_mock.AddCmdResult('status ui', **kwargs)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700293
294 def testUiJobStartedFalse(self):
295 """Correct results with a stopped job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800296 self.MockStatusUiCmd(output='ui stop/waiting')
297 self.assertFalse(self.deploy._CheckUiJobStarted())
298
299 def testNoUiJob(self):
300 """Correct results when the job doesn't exist."""
301 self.MockStatusUiCmd(error='start: Unknown job: ui', returncode=1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700302 self.assertFalse(self.deploy._CheckUiJobStarted())
303
304 def testCheckRootfsWriteableTrue(self):
305 """Correct results with a running job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800306 self.MockStatusUiCmd(output='ui start/running, process 297')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700307 self.assertTrue(self.deploy._CheckUiJobStarted())
308
309
Ryan Cuief91e702013-02-04 12:06:36 -0800310class StagingTest(cros_test_lib.MockTempDirTestCase):
311 """Test user-mode and ebuild-mode staging functionality."""
312
313 def setUp(self):
Ryan Cuief91e702013-02-04 12:06:36 -0800314 self.staging_dir = os.path.join(self.tempdir, 'staging')
315 self.build_dir = os.path.join(self.tempdir, 'build_dir')
Avery Musbach3edff0e2020-03-27 13:35:53 -0700316 self.common_flags = ['--board', _TARGET_BOARD,
317 '--build-dir', self.build_dir, '--staging-only',
318 '--cache-dir', self.tempdir]
Ryan Cuia0215a72013-02-14 16:20:45 -0800319 self.sdk_mock = self.StartPatcher(cros_chrome_sdk_unittest.SDKFetcherMock())
Ryan Cui686ec052013-02-12 16:39:41 -0800320 self.PatchObject(
321 osutils, 'SourceEnvironment', autospec=True,
322 return_value={'STRIP': 'x86_64-cros-linux-gnu-strip'})
Ryan Cuief91e702013-02-04 12:06:36 -0800323
David Jamesa6e08892013-03-01 13:34:11 -0800324 def testSingleFileDeployFailure(self):
325 """Default staging enforces that mandatory files are copied"""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400326 options = _ParseCommandLine(self.common_flags)
David Jamesa6e08892013-03-01 13:34:11 -0800327 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
328 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)
Ryan Cuief91e702013-02-04 12:06:36 -0800331
David Jamesa6e08892013-03-01 13:34:11 -0800332 def testSloppyDeployFailure(self):
333 """Sloppy staging enforces that at least one file is copied."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400334 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800335 self.assertRaises(
336 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700337 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800338
339 def testSloppyDeploySuccess(self):
340 """Sloppy staging - stage one file."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400341 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800342 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
Steve Funge984a532013-11-25 17:09:25 -0800343 deploy_chrome._PrepareStagingDir(options, self.tempdir, self.staging_dir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700344 chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800345
Steve Funge984a532013-11-25 17:09:25 -0800346
347class DeployTestBuildDir(cros_test_lib.MockTempDirTestCase):
Daniel Erat1ae46382014-08-14 10:23:39 -0700348 """Set up a deploy object with a build-dir for use in deployment type tests"""
Steve Funge984a532013-11-25 17:09:25 -0800349
350 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400351 options = _ParseCommandLine(args)
Steve Funge984a532013-11-25 17:09:25 -0800352 return deploy_chrome.DeployChrome(
353 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
354
355 def setUp(self):
356 self.staging_dir = os.path.join(self.tempdir, 'staging')
357 self.build_dir = os.path.join(self.tempdir, 'build_dir')
358 self.deploy_mock = self.StartPatcher(DeployChromeMock())
359 self.deploy = self._GetDeployChrome(
Avery Musbach3edff0e2020-03-27 13:35:53 -0700360 list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
361 '--build-dir', self.build_dir, '--staging-only',
362 '--cache-dir', self.tempdir, '--sloppy'])
Steve Funge984a532013-11-25 17:09:25 -0800363
Daniel Erat1ae46382014-08-14 10:23:39 -0700364 def getCopyPath(self, source_path):
365 """Return a chrome_util.Path or None if not present."""
366 paths = [p for p in self.deploy.copy_paths if p.src == source_path]
367 return paths[0] if paths else None
Steve Funge984a532013-11-25 17:09:25 -0800368
Daniel Erat1ae46382014-08-14 10:23:39 -0700369class TestDeploymentType(DeployTestBuildDir):
Steve Funge984a532013-11-25 17:09:25 -0800370 """Test detection of deployment type using build dir."""
371
Daniel Erat1ae46382014-08-14 10:23:39 -0700372 def testAppShellDetection(self):
373 """Check for an app_shell deployment"""
374 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Funge984a532013-11-25 17:09:25 -0800375 makedirs=True)
376 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700377 self.assertTrue(self.getCopyPath('app_shell'))
378 self.assertFalse(self.getCopyPath('chrome'))
Steve Funge984a532013-11-25 17:09:25 -0800379
Daniel Erat1ae46382014-08-14 10:23:39 -0700380 def testChromeAndAppShellDetection(self):
Daniel Eratf53bd3a2016-12-02 11:28:36 -0700381 """Check for a chrome deployment when app_shell also exists."""
Steve Fung63d705d2014-03-16 03:14:03 -0700382 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
383 makedirs=True)
Daniel Erat1ae46382014-08-14 10:23:39 -0700384 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Fung63d705d2014-03-16 03:14:03 -0700385 makedirs=True)
386 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700387 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700388 self.assertFalse(self.getCopyPath('app_shell'))
Steve Fung63d705d2014-03-16 03:14:03 -0700389
Steve Funge984a532013-11-25 17:09:25 -0800390 def testChromeDetection(self):
391 """Check for a regular chrome deployment"""
392 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
393 makedirs=True)
394 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700395 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700396 self.assertFalse(self.getCopyPath('app_shell'))
Ben Pastenee484b342020-06-30 18:29:27 -0700397
398
399class TestDeployTestBinaries(cros_test_lib.RunCommandTempDirTestCase):
400 """Tests _DeployTestBinaries()."""
401
402 def setUp(self):
403 options = _ParseCommandLine(list(_REGULAR_TO) + [
404 '--board', _TARGET_BOARD, '--force', '--mount',
405 '--build-dir', os.path.join(self.tempdir, 'build_dir'),
406 '--nostrip'])
407 self.deploy = deploy_chrome.DeployChrome(
408 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
409
Brian Sheedy86f12342020-10-29 15:30:02 -0700410 def _SimulateBinaries(self):
411 # Ensure the staging dir contains the right binaries to copy over.
Ben Pastenee484b342020-06-30 18:29:27 -0700412 test_binaries = [
413 'run_a_tests',
414 'run_b_tests',
415 'run_c_tests',
416 ]
417 # Simulate having the binaries both on the device and in our local build
418 # dir.
419 self.rc.AddCmdResult(
420 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD),
421 stdout='\n'.join(test_binaries))
422 for binary in test_binaries:
423 osutils.Touch(os.path.join(self.deploy.options.build_dir, binary),
424 makedirs=True, mode=0o700)
Brian Sheedy86f12342020-10-29 15:30:02 -0700425 return test_binaries
Ben Pastenee484b342020-06-30 18:29:27 -0700426
Brian Sheedy86f12342020-10-29 15:30:02 -0700427 def _AssertBinariesInStagingDir(self, test_binaries):
Ben Pastenee484b342020-06-30 18:29:27 -0700428 # Ensure the binaries were placed in the staging dir used to copy them over.
429 staging_dir = os.path.join(
430 self.tempdir, os.path.basename(deploy_chrome._CHROME_TEST_BIN_DIR))
431 for binary in test_binaries:
432 self.assertIn(binary, os.listdir(staging_dir))
Erik Chen75a2f492020-08-06 19:15:11 -0700433
Brian Sheedy86f12342020-10-29 15:30:02 -0700434 def testFindError(self):
435 """Ensure an error is thrown if we can't inspect the device."""
436 self.rc.AddCmdResult(
437 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD), 1)
438 self.assertRaises(
439 deploy_chrome.DeployFailure, self.deploy._DeployTestBinaries)
440
441 def testSuccess(self):
442 """Ensure that the happy path succeeds as expected."""
443 test_binaries = self._SimulateBinaries()
444 self.deploy._DeployTestBinaries()
445 self._AssertBinariesInStagingDir(test_binaries)
446
447 def testRetrySuccess(self):
448 """Ensure that a transient exception still results in success."""
449 # Raises a RunCommandError on its first invocation, but passes on subsequent
450 # calls.
451 def SideEffect(*args, **kwargs):
Yuke Liaobe6bac32020-12-26 22:16:49 -0800452 # pylint: disable=unused-argument
Brian Sheedy86f12342020-10-29 15:30:02 -0700453 if not SideEffect.called:
454 SideEffect.called = True
455 raise cros_build_lib.RunCommandError('fail')
456 SideEffect.called = False
457
458 test_binaries = self._SimulateBinaries()
459 with mock.patch.object(
460 remote_access.ChromiumOSDevice, 'CopyToDevice',
461 side_effect=SideEffect) as copy_mock:
462 self.deploy._DeployTestBinaries()
463 self.assertEqual(copy_mock.call_count, 2)
464 self._AssertBinariesInStagingDir(test_binaries)
465
466 def testRetryFailure(self):
467 """Ensure that consistent exceptions result in failure."""
468 self._SimulateBinaries()
469 with self.assertRaises(cros_build_lib.RunCommandError):
470 with mock.patch.object(
471 remote_access.ChromiumOSDevice, 'CopyToDevice',
472 side_effect=cros_build_lib.RunCommandError('fail')):
473 self.deploy._DeployTestBinaries()
474
Erik Chen75a2f492020-08-06 19:15:11 -0700475
476class LacrosPerformTest(cros_test_lib.RunCommandTempDirTestCase):
477 """Line coverage for Perform() method with --lacros option."""
478
479 def setUp(self):
Yuke Liao24fc60c2020-12-26 22:16:49 -0800480 self.deploy = None
481 self._ran_start_command = False
482 self.StartPatcher(parallel_unittest.ParallelMock())
483
484 def start_ui_side_effect(*args, **kwargs):
485 # pylint: disable=unused-argument
486 self._ran_start_command = True
487
488 self.rc.AddCmdResult(partial_mock.In('start ui'),
489 side_effect=start_ui_side_effect)
490
491 def prepareDeploy(self, options=None):
492 if not options:
493 options = _ParseCommandLine([
494 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
495 '--device', 'monkey'
496 ])
Erik Chen75a2f492020-08-06 19:15:11 -0700497 self.deploy = deploy_chrome.DeployChrome(
498 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
499
500 # These methods being mocked are all side effects expected for a --lacros
501 # deploy.
502 self.deploy._EnsureTargetDir = mock.Mock()
503 self.deploy._GetDeviceInfo = mock.Mock()
504 self.deploy._CheckConnection = mock.Mock()
505 self.deploy._MountRootfsAsWritable = mock.Mock()
506 self.deploy._PrepareStagingDir = mock.Mock()
507 self.deploy._CheckDeviceFreeSpace = mock.Mock()
Yuke Liaobe6bac32020-12-26 22:16:49 -0800508 self.deploy._KillAshChromeIfNeeded = mock.Mock()
Erik Chen75a2f492020-08-06 19:15:11 -0700509
510 def testConfNotModified(self):
511 """When the conf file is not modified we don't restart chrome ."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800512 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700513 self.deploy.Perform()
514 self.deploy._KillAshChromeIfNeeded.assert_not_called()
515 self.assertFalse(self._ran_start_command)
516
517 def testConfModified(self):
518 """When the conf file is modified we restart chrome."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800519 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700520
521 # We intentionally add '\n' to MODIFIED_CONF_FILE to simulate echo adding a
522 # newline when invoked in the shell.
523 self.rc.AddCmdResult(
524 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
525 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
526
527 self.deploy.Perform()
528 self.deploy._KillAshChromeIfNeeded.assert_called()
529 self.assertTrue(self._ran_start_command)
Yuke Liao24fc60c2020-12-26 22:16:49 -0800530
531 def testSkipModifyingConf(self):
532 """SKip modifying the config file when the argument is specified."""
533 self.prepareDeploy(
534 _ParseCommandLine([
535 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
536 '--device', 'monkey', '--skip-modifying-config-file'
537 ]))
538
539 self.rc.AddCmdResult(
540 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
541 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
542
543 self.deploy.Perform()
544 self.deploy._KillAshChromeIfNeeded.assert_not_called()
545 self.assertFalse(self._ran_start_command)