blob: 7db5f004746d148fbf78ee2a74b4c26653751f0e [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
Ryo Hashimoto77f8eca2021-04-16 16:43:37 +090054 def testBuildDirSpecified(self):
55 """Test case of build dir specified."""
56 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--build-dir',
57 '/path/to/chrome']
58 _ParseCommandLine(argv)
59
60 def testBuildDirSpecifiedWithoutBoard(self):
61 """Test case of build dir specified without --board."""
62 argv = list(_REGULAR_TO) + [
63 '--build-dir', '/path/to/chrome/out_' + _TARGET_BOARD + '/Release']
64 options = _ParseCommandLine(argv)
65 self.assertEqual(options.board, _TARGET_BOARD)
66
67 def testBuildDirSpecifiedWithoutBoardError(self):
68 """Test case of irregular build dir specified without --board."""
69 argv = list(_REGULAR_TO) + ['--build-dir', '/path/to/chrome/foo/bar']
70 self.assertParseError(argv)
71
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070072 def testGsPathSpecified(self):
73 """Test case of GS path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070074 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070075 _ParseCommandLine(argv)
76
77 def testLocalPathSpecified(self):
78 """Test case of local path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070079 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--local-pkg-path',
80 '/path/to/chrome']
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070081 _ParseCommandLine(argv)
82
Ryo Hashimoto77f8eca2021-04-16 16:43:37 +090083 def testNoBoard(self):
84 """Test no board specified."""
85 argv = list(_REGULAR_TO) + ['--gs-path', _GS_PATH]
86 self.assertParseError(argv)
87
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070088 def testNoTarget(self):
89 """Test no target specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070090 argv = ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuief91e702013-02-04 12:06:36 -080091 self.assertParseError(argv)
92
Erik Chen75a2f492020-08-06 19:15:11 -070093 def testLacros(self):
94 """Test basic lacros invocation."""
95 argv = ['--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
Ben Pastene0ff0fa42020-08-14 15:10:07 -070096 '--device', 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070097 options = _ParseCommandLine(argv)
98 self.assertTrue(options.lacros)
99 self.assertEqual(options.target_dir, deploy_chrome.LACROS_DIR)
100
101 def testLacrosRequiresNostrip(self):
102 """Lacros requires --nostrip"""
Ben Pastene0ff0fa42020-08-14 15:10:07 -0700103 argv = ['--lacros', '--build-dir', '/path/to/nowhere', '--device',
104 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -0700105 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
106 check_attrs={'code': 2})
107
Ryan Cuief91e702013-02-04 12:06:36 -0800108 def assertParseError(self, argv):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700109 with self.OutputCapturer():
110 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
111 check_attrs={'code': 2})
112
Thiago Goncales12793312013-05-23 11:26:17 -0700113 def testMountOptionSetsTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700114 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
115 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400116 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700117 self.assertIsNot(options.target_dir, None)
118
119 def testMountOptionSetsMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700120 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
121 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400122 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700123 self.assertIsNot(options.mount_dir, None)
124
125 def testMountOptionDoesNotOverrideTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700126 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
127 '--mount', '--target-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400128 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700129 self.assertEqual(options.target_dir, '/foo/bar/cow')
130
131 def testMountOptionDoesNotOverrideMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700132 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
133 '--mount', '--mount-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400134 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700135 self.assertEqual(options.mount_dir, '/foo/bar/cow')
136
Adrian Eldera2c548a2017-11-07 19:01:29 -0500137 def testSshIdentityOptionSetsOption(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700138 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
139 '--private-key', '/foo/bar/key',
Bernie Thompson93b9ee62018-02-21 14:56:16 -0800140 '--build-dir', '/path/to/nowhere']
Adrian Eldera2c548a2017-11-07 19:01:29 -0500141 options = _ParseCommandLine(argv)
142 self.assertEqual(options.private_key, '/foo/bar/key')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700143
144class DeployChromeMock(partial_mock.PartialMock):
Steve Funge984a532013-11-25 17:09:25 -0800145 """Deploy Chrome Mock Class."""
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700146
147 TARGET = 'chromite.scripts.deploy_chrome.DeployChrome'
Erik Chen75a2f492020-08-06 19:15:11 -0700148 ATTRS = ('_KillAshChromeIfNeeded', '_DisableRootfsVerification')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700149
David James88e6f032013-03-02 08:13:20 -0800150 def __init__(self):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700151 partial_mock.PartialMock.__init__(self)
Robert Flack1dc7ea82014-11-26 13:50:24 -0500152 self.remote_device_mock = remote_access_unittest.RemoteDeviceMock()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700153 # Target starts off as having rootfs verification enabled.
Ryan Cuie18f24f2012-12-03 18:39:55 -0800154 self.rsh_mock = remote_access_unittest.RemoteShMock()
David James88e6f032013-03-02 08:13:20 -0800155 self.rsh_mock.SetDefaultCmdResult(0)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700156 self.MockMountCmd(1)
David Haddock3151d912017-10-24 03:50:32 +0000157 self.rsh_mock.AddCmdResult(
Anushruth8d797672019-10-17 12:22:31 -0700158 deploy_chrome.LSOF_COMMAND_CHROME % (deploy_chrome._CHROME_DIR,), 1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700159
160 def MockMountCmd(self, returnvalue):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700161 self.rsh_mock.AddCmdResult(deploy_chrome.MOUNT_RW_COMMAND,
David James88e6f032013-03-02 08:13:20 -0800162 returnvalue)
163
164 def _DisableRootfsVerification(self, inst):
165 with mock.patch.object(time, 'sleep'):
166 self.backup['_DisableRootfsVerification'](inst)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700167
Ryan Cui4d6fca92012-12-13 16:41:56 -0800168 def PreStart(self):
Robert Flack1dc7ea82014-11-26 13:50:24 -0500169 self.remote_device_mock.start()
Ryan Cui4d6fca92012-12-13 16:41:56 -0800170 self.rsh_mock.start()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700171
Ryan Cui4d6fca92012-12-13 16:41:56 -0800172 def PreStop(self):
173 self.rsh_mock.stop()
Robert Flack1dc7ea82014-11-26 13:50:24 -0500174 self.remote_device_mock.stop()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700175
Erik Chen75a2f492020-08-06 19:15:11 -0700176 def _KillAshChromeIfNeeded(self, _inst):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700177 # Fully stub out for now.
178 pass
179
180
Ryan Cuief91e702013-02-04 12:06:36 -0800181class DeployTest(cros_test_lib.MockTempDirTestCase):
Steve Funge984a532013-11-25 17:09:25 -0800182 """Setup a deploy object with a GS-path for use in tests."""
183
Ryan Cuief91e702013-02-04 12:06:36 -0800184 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400185 options = _ParseCommandLine(args)
Ryan Cuia56a71e2012-10-18 18:40:35 -0700186 return deploy_chrome.DeployChrome(
187 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700188
189 def setUp(self):
Ryan Cuif1416f32013-01-22 18:43:41 -0800190 self.deploy_mock = self.StartPatcher(DeployChromeMock())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700191 self.deploy = self._GetDeployChrome(list(_REGULAR_TO) +
192 ['--board', _TARGET_BOARD, '--gs-path',
193 _GS_PATH, '--force', '--mount'])
Mike Frysingerfcca49e2021-03-17 01:09:20 -0400194 self.remote_reboot_mock = self.PatchObject(
195 remote_access.RemoteAccess, 'RemoteReboot', return_value=True)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700196
Avery Musbach3edff0e2020-03-27 13:35:53 -0700197
198class TestCheckIfBoardMatches(DeployTest):
199 """Testing checking whether the DUT board matches the target board."""
200
201 def testMatchedBoard(self):
202 """Test the case where the DUT board matches the target board."""
203 self.PatchObject(remote_access.ChromiumOSDevice, 'board', _TARGET_BOARD)
204 self.assertTrue(self.deploy.options.force)
205 self.deploy._CheckBoard()
206 self.deploy.options.force = False
207 self.deploy._CheckBoard()
208
209 def testMismatchedBoard(self):
210 """Test the case where the DUT board does not match the target board."""
211 self.PatchObject(remote_access.ChromiumOSDevice, 'board', 'cedar')
212 self.assertTrue(self.deploy.options.force)
213 self.deploy._CheckBoard()
214 self.deploy.options.force = False
215 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=True)
216 self.deploy._CheckBoard()
217 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=False)
218 self.assertRaises(deploy_chrome.DeployFailure, self.deploy._CheckBoard)
219
220
David James88e6f032013-03-02 08:13:20 -0800221class TestDisableRootfsVerification(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700222 """Testing disabling of rootfs verification and RO mode."""
223
David James88e6f032013-03-02 08:13:20 -0800224 def testDisableRootfsVerificationSuccess(self):
225 """Test the working case, disabling rootfs verification."""
226 self.deploy_mock.MockMountCmd(0)
227 self.deploy._DisableRootfsVerification()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700228 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700229
230 def testDisableRootfsVerificationFailure(self):
231 """Test failure to disable rootfs verification."""
Mike Frysinger27e21b72018-07-12 14:20:21 -0400232 # pylint: disable=unused-argument
Shuqian Zhao14e61092017-11-17 00:02:16 +0000233 def RaiseRunCommandError(timeout_sec=None):
Mike Frysinger929f3ba2019-09-12 03:24:59 -0400234 raise cros_build_lib.RunCommandError('Mock RunCommandError')
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800235 self.remote_reboot_mock.side_effect = RaiseRunCommandError
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700236 self.assertRaises(cros_build_lib.RunCommandError,
David James88e6f032013-03-02 08:13:20 -0800237 self.deploy._DisableRootfsVerification)
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800238 self.remote_reboot_mock.side_effect = None
Steven Bennettsca73efa2018-07-10 13:36:56 -0700239 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800240
241
242class TestMount(DeployTest):
243 """Testing mount success and failure."""
244
245 def testSuccess(self):
246 """Test case where we are able to mount as writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700247 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800248 self.deploy_mock.MockMountCmd(0)
249 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700250 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800251
252 def testMountError(self):
253 """Test that mount failure doesn't raise an exception by default."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700254 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700255 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500256 return_value=False, autospec=True)
David James88e6f032013-03-02 08:13:20 -0800257 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700258 self.assertTrue(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700259
260 def testMountRwFailure(self):
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500261 """Test that mount failure raises an exception if check=True."""
David James88e6f032013-03-02 08:13:20 -0800262 self.assertRaises(cros_build_lib.RunCommandError,
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500263 self.deploy._MountRootfsAsWritable, check=True)
Steven Bennettsca73efa2018-07-10 13:36:56 -0700264 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Robert Flack1dc7ea82014-11-26 13:50:24 -0500265
266 def testMountTempDir(self):
267 """Test that mount succeeds if target dir is writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700268 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700269 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500270 return_value=True, autospec=True)
271 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700272 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700273
274
Anushruth8d797672019-10-17 12:22:31 -0700275class TestMountTarget(DeployTest):
Mike Frysingerdf1d0b02019-11-12 17:44:12 -0500276 """Testing mount and umount command handling."""
Anushruth8d797672019-10-17 12:22:31 -0700277
278 def testMountTargetUmountFailure(self):
279 """Test error being thrown if umount fails.
280
281 Test that 'lsof' is run on mount-dir and 'mount -rbind' command is not run
282 if 'umount' cmd fails.
283 """
284 mount_dir = self.deploy.options.mount_dir
285 target_dir = self.deploy.options.target_dir
286 self.deploy_mock.rsh_mock.AddCmdResult(
287 deploy_chrome._UMOUNT_DIR_IF_MOUNTPOINT_CMD %
288 {'dir': mount_dir}, returncode=errno.EBUSY, stderr='Target is Busy')
289 self.deploy_mock.rsh_mock.AddCmdResult(deploy_chrome.LSOF_COMMAND %
290 (mount_dir,), returncode=0,
291 stdout='process ' + mount_dir)
292 # Check for RunCommandError being thrown.
293 self.assertRaises(cros_build_lib.RunCommandError,
294 self.deploy._MountTarget)
295 # Check for the 'mount -rbind' command not run.
296 self.deploy_mock.rsh_mock.assertCommandContains(
297 (deploy_chrome._BIND_TO_FINAL_DIR_CMD % (target_dir, mount_dir)),
298 expected=False)
299 # Check for lsof command being called.
300 self.deploy_mock.rsh_mock.assertCommandContains(
301 (deploy_chrome.LSOF_COMMAND % (mount_dir,)))
302
303
Ryan Cuief91e702013-02-04 12:06:36 -0800304class TestUiJobStarted(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700305 """Test detection of a running 'ui' job."""
306
Ryan Cuif2d1a582013-02-19 14:08:13 -0800307 def MockStatusUiCmd(self, **kwargs):
David Haddock3151d912017-10-24 03:50:32 +0000308 self.deploy_mock.rsh_mock.AddCmdResult('status ui', **kwargs)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700309
310 def testUiJobStartedFalse(self):
311 """Correct results with a stopped job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800312 self.MockStatusUiCmd(output='ui stop/waiting')
313 self.assertFalse(self.deploy._CheckUiJobStarted())
314
315 def testNoUiJob(self):
316 """Correct results when the job doesn't exist."""
317 self.MockStatusUiCmd(error='start: Unknown job: ui', returncode=1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700318 self.assertFalse(self.deploy._CheckUiJobStarted())
319
320 def testCheckRootfsWriteableTrue(self):
321 """Correct results with a running job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800322 self.MockStatusUiCmd(output='ui start/running, process 297')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700323 self.assertTrue(self.deploy._CheckUiJobStarted())
324
325
Ryan Cuief91e702013-02-04 12:06:36 -0800326class StagingTest(cros_test_lib.MockTempDirTestCase):
327 """Test user-mode and ebuild-mode staging functionality."""
328
329 def setUp(self):
Ryan Cuief91e702013-02-04 12:06:36 -0800330 self.staging_dir = os.path.join(self.tempdir, 'staging')
331 self.build_dir = os.path.join(self.tempdir, 'build_dir')
Avery Musbach3edff0e2020-03-27 13:35:53 -0700332 self.common_flags = ['--board', _TARGET_BOARD,
333 '--build-dir', self.build_dir, '--staging-only',
334 '--cache-dir', self.tempdir]
Ryan Cuia0215a72013-02-14 16:20:45 -0800335 self.sdk_mock = self.StartPatcher(cros_chrome_sdk_unittest.SDKFetcherMock())
Ryan Cui686ec052013-02-12 16:39:41 -0800336 self.PatchObject(
337 osutils, 'SourceEnvironment', autospec=True,
338 return_value={'STRIP': 'x86_64-cros-linux-gnu-strip'})
Ryan Cuief91e702013-02-04 12:06:36 -0800339
David Jamesa6e08892013-03-01 13:34:11 -0800340 def testSingleFileDeployFailure(self):
341 """Default staging enforces that mandatory files are copied"""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400342 options = _ParseCommandLine(self.common_flags)
David Jamesa6e08892013-03-01 13:34:11 -0800343 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
344 self.assertRaises(
345 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700346 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
Ryan Cuief91e702013-02-04 12:06:36 -0800347
David Jamesa6e08892013-03-01 13:34:11 -0800348 def testSloppyDeployFailure(self):
349 """Sloppy staging enforces that at least one file is copied."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400350 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800351 self.assertRaises(
352 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700353 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800354
355 def testSloppyDeploySuccess(self):
356 """Sloppy staging - stage one file."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400357 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800358 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
Steve Funge984a532013-11-25 17:09:25 -0800359 deploy_chrome._PrepareStagingDir(options, self.tempdir, self.staging_dir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700360 chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800361
Steve Funge984a532013-11-25 17:09:25 -0800362
363class DeployTestBuildDir(cros_test_lib.MockTempDirTestCase):
Daniel Erat1ae46382014-08-14 10:23:39 -0700364 """Set up a deploy object with a build-dir for use in deployment type tests"""
Steve Funge984a532013-11-25 17:09:25 -0800365
366 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400367 options = _ParseCommandLine(args)
Steve Funge984a532013-11-25 17:09:25 -0800368 return deploy_chrome.DeployChrome(
369 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
370
371 def setUp(self):
372 self.staging_dir = os.path.join(self.tempdir, 'staging')
373 self.build_dir = os.path.join(self.tempdir, 'build_dir')
374 self.deploy_mock = self.StartPatcher(DeployChromeMock())
375 self.deploy = self._GetDeployChrome(
Avery Musbach3edff0e2020-03-27 13:35:53 -0700376 list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
377 '--build-dir', self.build_dir, '--staging-only',
378 '--cache-dir', self.tempdir, '--sloppy'])
Steve Funge984a532013-11-25 17:09:25 -0800379
Daniel Erat1ae46382014-08-14 10:23:39 -0700380 def getCopyPath(self, source_path):
381 """Return a chrome_util.Path or None if not present."""
382 paths = [p for p in self.deploy.copy_paths if p.src == source_path]
383 return paths[0] if paths else None
Steve Funge984a532013-11-25 17:09:25 -0800384
Daniel Erat1ae46382014-08-14 10:23:39 -0700385class TestDeploymentType(DeployTestBuildDir):
Steve Funge984a532013-11-25 17:09:25 -0800386 """Test detection of deployment type using build dir."""
387
Daniel Erat1ae46382014-08-14 10:23:39 -0700388 def testAppShellDetection(self):
389 """Check for an app_shell deployment"""
390 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Funge984a532013-11-25 17:09:25 -0800391 makedirs=True)
392 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700393 self.assertTrue(self.getCopyPath('app_shell'))
394 self.assertFalse(self.getCopyPath('chrome'))
Steve Funge984a532013-11-25 17:09:25 -0800395
Daniel Erat1ae46382014-08-14 10:23:39 -0700396 def testChromeAndAppShellDetection(self):
Daniel Eratf53bd3a2016-12-02 11:28:36 -0700397 """Check for a chrome deployment when app_shell also exists."""
Steve Fung63d705d2014-03-16 03:14:03 -0700398 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
399 makedirs=True)
Daniel Erat1ae46382014-08-14 10:23:39 -0700400 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Fung63d705d2014-03-16 03:14:03 -0700401 makedirs=True)
402 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700403 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700404 self.assertFalse(self.getCopyPath('app_shell'))
Steve Fung63d705d2014-03-16 03:14:03 -0700405
Steve Funge984a532013-11-25 17:09:25 -0800406 def testChromeDetection(self):
407 """Check for a regular chrome deployment"""
408 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
409 makedirs=True)
410 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700411 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700412 self.assertFalse(self.getCopyPath('app_shell'))
Ben Pastenee484b342020-06-30 18:29:27 -0700413
414
415class TestDeployTestBinaries(cros_test_lib.RunCommandTempDirTestCase):
416 """Tests _DeployTestBinaries()."""
417
418 def setUp(self):
419 options = _ParseCommandLine(list(_REGULAR_TO) + [
420 '--board', _TARGET_BOARD, '--force', '--mount',
421 '--build-dir', os.path.join(self.tempdir, 'build_dir'),
422 '--nostrip'])
423 self.deploy = deploy_chrome.DeployChrome(
424 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
425
Brian Sheedy86f12342020-10-29 15:30:02 -0700426 def _SimulateBinaries(self):
427 # Ensure the staging dir contains the right binaries to copy over.
Ben Pastenee484b342020-06-30 18:29:27 -0700428 test_binaries = [
429 'run_a_tests',
430 'run_b_tests',
431 'run_c_tests',
432 ]
433 # Simulate having the binaries both on the device and in our local build
434 # dir.
435 self.rc.AddCmdResult(
436 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD),
437 stdout='\n'.join(test_binaries))
438 for binary in test_binaries:
439 osutils.Touch(os.path.join(self.deploy.options.build_dir, binary),
440 makedirs=True, mode=0o700)
Brian Sheedy86f12342020-10-29 15:30:02 -0700441 return test_binaries
Ben Pastenee484b342020-06-30 18:29:27 -0700442
Brian Sheedy86f12342020-10-29 15:30:02 -0700443 def _AssertBinariesInStagingDir(self, test_binaries):
Ben Pastenee484b342020-06-30 18:29:27 -0700444 # Ensure the binaries were placed in the staging dir used to copy them over.
445 staging_dir = os.path.join(
446 self.tempdir, os.path.basename(deploy_chrome._CHROME_TEST_BIN_DIR))
447 for binary in test_binaries:
448 self.assertIn(binary, os.listdir(staging_dir))
Erik Chen75a2f492020-08-06 19:15:11 -0700449
Brian Sheedy86f12342020-10-29 15:30:02 -0700450 def testFindError(self):
451 """Ensure an error is thrown if we can't inspect the device."""
452 self.rc.AddCmdResult(
453 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD), 1)
454 self.assertRaises(
455 deploy_chrome.DeployFailure, self.deploy._DeployTestBinaries)
456
457 def testSuccess(self):
458 """Ensure that the happy path succeeds as expected."""
459 test_binaries = self._SimulateBinaries()
460 self.deploy._DeployTestBinaries()
461 self._AssertBinariesInStagingDir(test_binaries)
462
463 def testRetrySuccess(self):
464 """Ensure that a transient exception still results in success."""
465 # Raises a RunCommandError on its first invocation, but passes on subsequent
466 # calls.
467 def SideEffect(*args, **kwargs):
Yuke Liaobe6bac32020-12-26 22:16:49 -0800468 # pylint: disable=unused-argument
Brian Sheedy86f12342020-10-29 15:30:02 -0700469 if not SideEffect.called:
470 SideEffect.called = True
471 raise cros_build_lib.RunCommandError('fail')
472 SideEffect.called = False
473
474 test_binaries = self._SimulateBinaries()
475 with mock.patch.object(
476 remote_access.ChromiumOSDevice, 'CopyToDevice',
477 side_effect=SideEffect) as copy_mock:
478 self.deploy._DeployTestBinaries()
479 self.assertEqual(copy_mock.call_count, 2)
480 self._AssertBinariesInStagingDir(test_binaries)
481
482 def testRetryFailure(self):
483 """Ensure that consistent exceptions result in failure."""
484 self._SimulateBinaries()
485 with self.assertRaises(cros_build_lib.RunCommandError):
486 with mock.patch.object(
487 remote_access.ChromiumOSDevice, 'CopyToDevice',
488 side_effect=cros_build_lib.RunCommandError('fail')):
489 self.deploy._DeployTestBinaries()
490
Erik Chen75a2f492020-08-06 19:15:11 -0700491
492class LacrosPerformTest(cros_test_lib.RunCommandTempDirTestCase):
493 """Line coverage for Perform() method with --lacros option."""
494
495 def setUp(self):
Yuke Liao24fc60c2020-12-26 22:16:49 -0800496 self.deploy = None
497 self._ran_start_command = False
498 self.StartPatcher(parallel_unittest.ParallelMock())
499
500 def start_ui_side_effect(*args, **kwargs):
501 # pylint: disable=unused-argument
502 self._ran_start_command = True
503
504 self.rc.AddCmdResult(partial_mock.In('start ui'),
505 side_effect=start_ui_side_effect)
506
507 def prepareDeploy(self, options=None):
508 if not options:
509 options = _ParseCommandLine([
510 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
511 '--device', 'monkey'
512 ])
Erik Chen75a2f492020-08-06 19:15:11 -0700513 self.deploy = deploy_chrome.DeployChrome(
514 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
515
516 # These methods being mocked are all side effects expected for a --lacros
517 # deploy.
518 self.deploy._EnsureTargetDir = mock.Mock()
519 self.deploy._GetDeviceInfo = mock.Mock()
520 self.deploy._CheckConnection = mock.Mock()
521 self.deploy._MountRootfsAsWritable = mock.Mock()
522 self.deploy._PrepareStagingDir = mock.Mock()
523 self.deploy._CheckDeviceFreeSpace = mock.Mock()
Yuke Liaobe6bac32020-12-26 22:16:49 -0800524 self.deploy._KillAshChromeIfNeeded = mock.Mock()
Erik Chen75a2f492020-08-06 19:15:11 -0700525
526 def testConfNotModified(self):
527 """When the conf file is not modified we don't restart chrome ."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800528 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700529 self.deploy.Perform()
530 self.deploy._KillAshChromeIfNeeded.assert_not_called()
531 self.assertFalse(self._ran_start_command)
532
533 def testConfModified(self):
534 """When the conf file is modified we restart chrome."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800535 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700536
537 # We intentionally add '\n' to MODIFIED_CONF_FILE to simulate echo adding a
538 # newline when invoked in the shell.
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_called()
545 self.assertTrue(self._ran_start_command)
Yuke Liao24fc60c2020-12-26 22:16:49 -0800546
547 def testSkipModifyingConf(self):
548 """SKip modifying the config file when the argument is specified."""
549 self.prepareDeploy(
550 _ParseCommandLine([
551 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
552 '--device', 'monkey', '--skip-modifying-config-file'
553 ]))
554
555 self.rc.AddCmdResult(
556 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
557 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
558
559 self.deploy.Perform()
560 self.deploy._KillAshChromeIfNeeded.assert_not_called()
561 self.assertFalse(self._ran_start_command)