blob: 50a14dbdf507d5c764e566df4e283e18e8428340 [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
David Pursellcfd58872015-03-19 09:15:48 -070015from chromite.cli.cros import cros_chrome_sdk_unittest
Ryan Cuief91e702013-02-04 12:06:36 -080016from chromite.lib import chrome_util
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070017from chromite.lib import cros_build_lib
18from chromite.lib import cros_test_lib
Ryan Cui686ec052013-02-12 16:39:41 -080019from chromite.lib import osutils
Erik Chen75a2f492020-08-06 19:15:11 -070020from chromite.lib import parallel_unittest
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070021from chromite.lib import partial_mock
Robert Flack1dc7ea82014-11-26 13:50:24 -050022from chromite.lib import remote_access
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070023from chromite.lib import remote_access_unittest
24from chromite.scripts import deploy_chrome
Mike Frysinger40ffb532021-02-12 07:36:08 -050025from chromite.third_party import mock
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070026
Ryan Cuief91e702013-02-04 12:06:36 -080027
Mike Frysinger6165cdc2020-02-21 02:38:07 -050028assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
29
30
Mike Frysinger27e21b72018-07-12 14:20:21 -040031# pylint: disable=protected-access
32
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070033
Ben Pastene0ff0fa42020-08-14 15:10:07 -070034_REGULAR_TO = ('--device', 'monkey')
Avery Musbach3edff0e2020-03-27 13:35:53 -070035_TARGET_BOARD = 'eve'
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070036_GS_PATH = 'gs://foon'
37
38
39def _ParseCommandLine(argv):
40 return deploy_chrome._ParseCommandLine(['--log-level', 'debug'] + argv)
41
42
43class InterfaceTest(cros_test_lib.OutputTestCase):
44 """Tests the commandline interface of the script."""
45
46 def testGsLocalPathUnSpecified(self):
47 """Test no chrome path specified."""
48 with self.OutputCapturer():
Avery Musbach3edff0e2020-03-27 13:35:53 -070049 self.assertRaises2(SystemExit, _ParseCommandLine,
50 list(_REGULAR_TO) + ['--board', _TARGET_BOARD],
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070051 check_attrs={'code': 2})
52
Ryo Hashimoto77f8eca2021-04-16 16:43:37 +090053 def testBuildDirSpecified(self):
54 """Test case of build dir specified."""
55 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--build-dir',
56 '/path/to/chrome']
57 _ParseCommandLine(argv)
58
59 def testBuildDirSpecifiedWithoutBoard(self):
60 """Test case of build dir specified without --board."""
61 argv = list(_REGULAR_TO) + [
62 '--build-dir', '/path/to/chrome/out_' + _TARGET_BOARD + '/Release']
63 options = _ParseCommandLine(argv)
64 self.assertEqual(options.board, _TARGET_BOARD)
65
66 def testBuildDirSpecifiedWithoutBoardError(self):
67 """Test case of irregular build dir specified without --board."""
68 argv = list(_REGULAR_TO) + ['--build-dir', '/path/to/chrome/foo/bar']
69 self.assertParseError(argv)
70
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070071 def testGsPathSpecified(self):
72 """Test case of GS path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070073 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070074 _ParseCommandLine(argv)
75
76 def testLocalPathSpecified(self):
77 """Test case of local path specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070078 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--local-pkg-path',
79 '/path/to/chrome']
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070080 _ParseCommandLine(argv)
81
Ryo Hashimoto77f8eca2021-04-16 16:43:37 +090082 def testNoBoard(self):
83 """Test no board specified."""
84 argv = list(_REGULAR_TO) + ['--gs-path', _GS_PATH]
85 self.assertParseError(argv)
86
Ryan Cuiafd6c5c2012-07-30 17:48:22 -070087 def testNoTarget(self):
88 """Test no target specified."""
Avery Musbach3edff0e2020-03-27 13:35:53 -070089 argv = ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH]
Ryan Cuief91e702013-02-04 12:06:36 -080090 self.assertParseError(argv)
91
Erik Chen75a2f492020-08-06 19:15:11 -070092 def testLacros(self):
93 """Test basic lacros invocation."""
94 argv = ['--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
Ben Pastene0ff0fa42020-08-14 15:10:07 -070095 '--device', 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -070096 options = _ParseCommandLine(argv)
97 self.assertTrue(options.lacros)
98 self.assertEqual(options.target_dir, deploy_chrome.LACROS_DIR)
99
100 def testLacrosRequiresNostrip(self):
101 """Lacros requires --nostrip"""
Ben Pastene0ff0fa42020-08-14 15:10:07 -0700102 argv = ['--lacros', '--build-dir', '/path/to/nowhere', '--device',
103 'monkey']
Erik Chen75a2f492020-08-06 19:15:11 -0700104 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
105 check_attrs={'code': 2})
106
Ryan Cuief91e702013-02-04 12:06:36 -0800107 def assertParseError(self, argv):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700108 with self.OutputCapturer():
109 self.assertRaises2(SystemExit, _ParseCommandLine, argv,
110 check_attrs={'code': 2})
111
Thiago Goncales12793312013-05-23 11:26:17 -0700112 def testMountOptionSetsTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700113 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
114 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400115 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700116 self.assertIsNot(options.target_dir, None)
117
118 def testMountOptionSetsMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700119 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
120 '--mount']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400121 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700122 self.assertIsNot(options.mount_dir, None)
123
124 def testMountOptionDoesNotOverrideTargetDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700125 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
126 '--mount', '--target-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400127 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700128 self.assertEqual(options.target_dir, '/foo/bar/cow')
129
130 def testMountOptionDoesNotOverrideMountDir(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700131 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD, '--gs-path', _GS_PATH,
132 '--mount', '--mount-dir', '/foo/bar/cow']
Mike Frysingerc3061a62015-06-04 04:16:18 -0400133 options = _ParseCommandLine(argv)
Thiago Goncales12793312013-05-23 11:26:17 -0700134 self.assertEqual(options.mount_dir, '/foo/bar/cow')
135
Adrian Eldera2c548a2017-11-07 19:01:29 -0500136 def testSshIdentityOptionSetsOption(self):
Avery Musbach3edff0e2020-03-27 13:35:53 -0700137 argv = list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
138 '--private-key', '/foo/bar/key',
Bernie Thompson93b9ee62018-02-21 14:56:16 -0800139 '--build-dir', '/path/to/nowhere']
Adrian Eldera2c548a2017-11-07 19:01:29 -0500140 options = _ParseCommandLine(argv)
141 self.assertEqual(options.private_key, '/foo/bar/key')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700142
143class DeployChromeMock(partial_mock.PartialMock):
Steve Funge984a532013-11-25 17:09:25 -0800144 """Deploy Chrome Mock Class."""
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700145
146 TARGET = 'chromite.scripts.deploy_chrome.DeployChrome'
Erik Chen75a2f492020-08-06 19:15:11 -0700147 ATTRS = ('_KillAshChromeIfNeeded', '_DisableRootfsVerification')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700148
David James88e6f032013-03-02 08:13:20 -0800149 def __init__(self):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700150 partial_mock.PartialMock.__init__(self)
Robert Flack1dc7ea82014-11-26 13:50:24 -0500151 self.remote_device_mock = remote_access_unittest.RemoteDeviceMock()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700152 # Target starts off as having rootfs verification enabled.
Ryan Cuie18f24f2012-12-03 18:39:55 -0800153 self.rsh_mock = remote_access_unittest.RemoteShMock()
David James88e6f032013-03-02 08:13:20 -0800154 self.rsh_mock.SetDefaultCmdResult(0)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700155 self.MockMountCmd(1)
David Haddock3151d912017-10-24 03:50:32 +0000156 self.rsh_mock.AddCmdResult(
Anushruth8d797672019-10-17 12:22:31 -0700157 deploy_chrome.LSOF_COMMAND_CHROME % (deploy_chrome._CHROME_DIR,), 1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700158
159 def MockMountCmd(self, returnvalue):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700160 self.rsh_mock.AddCmdResult(deploy_chrome.MOUNT_RW_COMMAND,
David James88e6f032013-03-02 08:13:20 -0800161 returnvalue)
162
163 def _DisableRootfsVerification(self, inst):
164 with mock.patch.object(time, 'sleep'):
165 self.backup['_DisableRootfsVerification'](inst)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700166
Ryan Cui4d6fca92012-12-13 16:41:56 -0800167 def PreStart(self):
Robert Flack1dc7ea82014-11-26 13:50:24 -0500168 self.remote_device_mock.start()
Ryan Cui4d6fca92012-12-13 16:41:56 -0800169 self.rsh_mock.start()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700170
Ryan Cui4d6fca92012-12-13 16:41:56 -0800171 def PreStop(self):
172 self.rsh_mock.stop()
Robert Flack1dc7ea82014-11-26 13:50:24 -0500173 self.remote_device_mock.stop()
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700174
Erik Chen75a2f492020-08-06 19:15:11 -0700175 def _KillAshChromeIfNeeded(self, _inst):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700176 # Fully stub out for now.
177 pass
178
179
Ryan Cuief91e702013-02-04 12:06:36 -0800180class DeployTest(cros_test_lib.MockTempDirTestCase):
Steve Funge984a532013-11-25 17:09:25 -0800181 """Setup a deploy object with a GS-path for use in tests."""
182
Ryan Cuief91e702013-02-04 12:06:36 -0800183 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400184 options = _ParseCommandLine(args)
Ryan Cuia56a71e2012-10-18 18:40:35 -0700185 return deploy_chrome.DeployChrome(
186 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700187
188 def setUp(self):
Ryan Cuif1416f32013-01-22 18:43:41 -0800189 self.deploy_mock = self.StartPatcher(DeployChromeMock())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700190 self.deploy = self._GetDeployChrome(list(_REGULAR_TO) +
191 ['--board', _TARGET_BOARD, '--gs-path',
192 _GS_PATH, '--force', '--mount'])
Mike Frysingerfcca49e2021-03-17 01:09:20 -0400193 self.remote_reboot_mock = self.PatchObject(
194 remote_access.RemoteAccess, 'RemoteReboot', return_value=True)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700195
Avery Musbach3edff0e2020-03-27 13:35:53 -0700196
197class TestCheckIfBoardMatches(DeployTest):
198 """Testing checking whether the DUT board matches the target board."""
199
200 def testMatchedBoard(self):
201 """Test the case where the DUT board matches the target board."""
202 self.PatchObject(remote_access.ChromiumOSDevice, 'board', _TARGET_BOARD)
203 self.assertTrue(self.deploy.options.force)
204 self.deploy._CheckBoard()
205 self.deploy.options.force = False
206 self.deploy._CheckBoard()
207
208 def testMismatchedBoard(self):
209 """Test the case where the DUT board does not match the target board."""
210 self.PatchObject(remote_access.ChromiumOSDevice, 'board', 'cedar')
211 self.assertTrue(self.deploy.options.force)
212 self.deploy._CheckBoard()
213 self.deploy.options.force = False
214 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=True)
215 self.deploy._CheckBoard()
216 self.PatchObject(cros_build_lib, 'BooleanPrompt', return_value=False)
217 self.assertRaises(deploy_chrome.DeployFailure, self.deploy._CheckBoard)
218
219
David James88e6f032013-03-02 08:13:20 -0800220class TestDisableRootfsVerification(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700221 """Testing disabling of rootfs verification and RO mode."""
222
David James88e6f032013-03-02 08:13:20 -0800223 def testDisableRootfsVerificationSuccess(self):
224 """Test the working case, disabling rootfs verification."""
225 self.deploy_mock.MockMountCmd(0)
226 self.deploy._DisableRootfsVerification()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700227 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700228
229 def testDisableRootfsVerificationFailure(self):
230 """Test failure to disable rootfs verification."""
Mike Frysinger27e21b72018-07-12 14:20:21 -0400231 # pylint: disable=unused-argument
Shuqian Zhao14e61092017-11-17 00:02:16 +0000232 def RaiseRunCommandError(timeout_sec=None):
Mike Frysinger929f3ba2019-09-12 03:24:59 -0400233 raise cros_build_lib.RunCommandError('Mock RunCommandError')
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800234 self.remote_reboot_mock.side_effect = RaiseRunCommandError
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700235 self.assertRaises(cros_build_lib.RunCommandError,
David James88e6f032013-03-02 08:13:20 -0800236 self.deploy._DisableRootfsVerification)
Luigi Semenzato1bc79b22016-11-22 16:32:17 -0800237 self.remote_reboot_mock.side_effect = None
Steven Bennettsca73efa2018-07-10 13:36:56 -0700238 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800239
240
241class TestMount(DeployTest):
242 """Testing mount success and failure."""
243
244 def testSuccess(self):
245 """Test case where we are able to mount as writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700246 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800247 self.deploy_mock.MockMountCmd(0)
248 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700249 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
David James88e6f032013-03-02 08:13:20 -0800250
251 def testMountError(self):
252 """Test that mount failure doesn't raise an exception by default."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700253 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700254 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500255 return_value=False, autospec=True)
David James88e6f032013-03-02 08:13:20 -0800256 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700257 self.assertTrue(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700258
259 def testMountRwFailure(self):
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500260 """Test that mount failure raises an exception if check=True."""
David James88e6f032013-03-02 08:13:20 -0800261 self.assertRaises(cros_build_lib.RunCommandError,
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500262 self.deploy._MountRootfsAsWritable, check=True)
Steven Bennettsca73efa2018-07-10 13:36:56 -0700263 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Robert Flack1dc7ea82014-11-26 13:50:24 -0500264
265 def testMountTempDir(self):
266 """Test that mount succeeds if target dir is writable."""
Steven Bennettsca73efa2018-07-10 13:36:56 -0700267 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Avery Musbach3edff0e2020-03-27 13:35:53 -0700268 self.PatchObject(remote_access.ChromiumOSDevice, 'IsDirWritable',
Robert Flack1dc7ea82014-11-26 13:50:24 -0500269 return_value=True, autospec=True)
270 self.deploy._MountRootfsAsWritable()
Steven Bennettsca73efa2018-07-10 13:36:56 -0700271 self.assertFalse(self.deploy._root_dir_is_still_readonly.is_set())
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700272
273
Anushruth8d797672019-10-17 12:22:31 -0700274class TestMountTarget(DeployTest):
Mike Frysingerdf1d0b02019-11-12 17:44:12 -0500275 """Testing mount and umount command handling."""
Anushruth8d797672019-10-17 12:22:31 -0700276
277 def testMountTargetUmountFailure(self):
278 """Test error being thrown if umount fails.
279
280 Test that 'lsof' is run on mount-dir and 'mount -rbind' command is not run
281 if 'umount' cmd fails.
282 """
283 mount_dir = self.deploy.options.mount_dir
284 target_dir = self.deploy.options.target_dir
285 self.deploy_mock.rsh_mock.AddCmdResult(
286 deploy_chrome._UMOUNT_DIR_IF_MOUNTPOINT_CMD %
287 {'dir': mount_dir}, returncode=errno.EBUSY, stderr='Target is Busy')
288 self.deploy_mock.rsh_mock.AddCmdResult(deploy_chrome.LSOF_COMMAND %
289 (mount_dir,), returncode=0,
290 stdout='process ' + mount_dir)
291 # Check for RunCommandError being thrown.
292 self.assertRaises(cros_build_lib.RunCommandError,
293 self.deploy._MountTarget)
294 # Check for the 'mount -rbind' command not run.
295 self.deploy_mock.rsh_mock.assertCommandContains(
296 (deploy_chrome._BIND_TO_FINAL_DIR_CMD % (target_dir, mount_dir)),
297 expected=False)
298 # Check for lsof command being called.
299 self.deploy_mock.rsh_mock.assertCommandContains(
300 (deploy_chrome.LSOF_COMMAND % (mount_dir,)))
301
302
Ryan Cuief91e702013-02-04 12:06:36 -0800303class TestUiJobStarted(DeployTest):
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700304 """Test detection of a running 'ui' job."""
305
Ryan Cuif2d1a582013-02-19 14:08:13 -0800306 def MockStatusUiCmd(self, **kwargs):
David Haddock3151d912017-10-24 03:50:32 +0000307 self.deploy_mock.rsh_mock.AddCmdResult('status ui', **kwargs)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700308
309 def testUiJobStartedFalse(self):
310 """Correct results with a stopped job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800311 self.MockStatusUiCmd(output='ui stop/waiting')
312 self.assertFalse(self.deploy._CheckUiJobStarted())
313
314 def testNoUiJob(self):
315 """Correct results when the job doesn't exist."""
316 self.MockStatusUiCmd(error='start: Unknown job: ui', returncode=1)
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700317 self.assertFalse(self.deploy._CheckUiJobStarted())
318
319 def testCheckRootfsWriteableTrue(self):
320 """Correct results with a running job."""
Ryan Cuif2d1a582013-02-19 14:08:13 -0800321 self.MockStatusUiCmd(output='ui start/running, process 297')
Ryan Cuiafd6c5c2012-07-30 17:48:22 -0700322 self.assertTrue(self.deploy._CheckUiJobStarted())
323
324
Ryan Cuief91e702013-02-04 12:06:36 -0800325class StagingTest(cros_test_lib.MockTempDirTestCase):
326 """Test user-mode and ebuild-mode staging functionality."""
327
328 def setUp(self):
Ryan Cuief91e702013-02-04 12:06:36 -0800329 self.staging_dir = os.path.join(self.tempdir, 'staging')
330 self.build_dir = os.path.join(self.tempdir, 'build_dir')
Avery Musbach3edff0e2020-03-27 13:35:53 -0700331 self.common_flags = ['--board', _TARGET_BOARD,
332 '--build-dir', self.build_dir, '--staging-only',
333 '--cache-dir', self.tempdir]
Ryan Cuia0215a72013-02-14 16:20:45 -0800334 self.sdk_mock = self.StartPatcher(cros_chrome_sdk_unittest.SDKFetcherMock())
Ryan Cui686ec052013-02-12 16:39:41 -0800335 self.PatchObject(
336 osutils, 'SourceEnvironment', autospec=True,
337 return_value={'STRIP': 'x86_64-cros-linux-gnu-strip'})
Ryan Cuief91e702013-02-04 12:06:36 -0800338
David Jamesa6e08892013-03-01 13:34:11 -0800339 def testSingleFileDeployFailure(self):
340 """Default staging enforces that mandatory files are copied"""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400341 options = _ParseCommandLine(self.common_flags)
David Jamesa6e08892013-03-01 13:34:11 -0800342 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
343 self.assertRaises(
344 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700345 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
Ryan Cuief91e702013-02-04 12:06:36 -0800346
David Jamesa6e08892013-03-01 13:34:11 -0800347 def testSloppyDeployFailure(self):
348 """Sloppy staging enforces that at least one file is copied."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400349 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800350 self.assertRaises(
351 chrome_util.MissingPathError, deploy_chrome._PrepareStagingDir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700352 options, self.tempdir, self.staging_dir, chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800353
354 def testSloppyDeploySuccess(self):
355 """Sloppy staging - stage one file."""
Mike Frysingerc3061a62015-06-04 04:16:18 -0400356 options = _ParseCommandLine(self.common_flags + ['--sloppy'])
David Jamesa6e08892013-03-01 13:34:11 -0800357 osutils.Touch(os.path.join(self.build_dir, 'chrome'), makedirs=True)
Steve Funge984a532013-11-25 17:09:25 -0800358 deploy_chrome._PrepareStagingDir(options, self.tempdir, self.staging_dir,
Daniel Eratc89829c2014-05-12 17:24:21 -0700359 chrome_util._COPY_PATHS_CHROME)
David Jamesa6e08892013-03-01 13:34:11 -0800360
Steve Funge984a532013-11-25 17:09:25 -0800361
362class DeployTestBuildDir(cros_test_lib.MockTempDirTestCase):
Daniel Erat1ae46382014-08-14 10:23:39 -0700363 """Set up a deploy object with a build-dir for use in deployment type tests"""
Steve Funge984a532013-11-25 17:09:25 -0800364
365 def _GetDeployChrome(self, args):
Mike Frysingerc3061a62015-06-04 04:16:18 -0400366 options = _ParseCommandLine(args)
Steve Funge984a532013-11-25 17:09:25 -0800367 return deploy_chrome.DeployChrome(
368 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
369
370 def setUp(self):
371 self.staging_dir = os.path.join(self.tempdir, 'staging')
372 self.build_dir = os.path.join(self.tempdir, 'build_dir')
373 self.deploy_mock = self.StartPatcher(DeployChromeMock())
374 self.deploy = self._GetDeployChrome(
Avery Musbach3edff0e2020-03-27 13:35:53 -0700375 list(_REGULAR_TO) + ['--board', _TARGET_BOARD,
376 '--build-dir', self.build_dir, '--staging-only',
377 '--cache-dir', self.tempdir, '--sloppy'])
Steve Funge984a532013-11-25 17:09:25 -0800378
Daniel Erat1ae46382014-08-14 10:23:39 -0700379 def getCopyPath(self, source_path):
380 """Return a chrome_util.Path or None if not present."""
381 paths = [p for p in self.deploy.copy_paths if p.src == source_path]
382 return paths[0] if paths else None
Steve Funge984a532013-11-25 17:09:25 -0800383
Daniel Erat1ae46382014-08-14 10:23:39 -0700384class TestDeploymentType(DeployTestBuildDir):
Steve Funge984a532013-11-25 17:09:25 -0800385 """Test detection of deployment type using build dir."""
386
Daniel Erat1ae46382014-08-14 10:23:39 -0700387 def testAppShellDetection(self):
388 """Check for an app_shell deployment"""
389 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Funge984a532013-11-25 17:09:25 -0800390 makedirs=True)
391 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700392 self.assertTrue(self.getCopyPath('app_shell'))
393 self.assertFalse(self.getCopyPath('chrome'))
Steve Funge984a532013-11-25 17:09:25 -0800394
Daniel Erat1ae46382014-08-14 10:23:39 -0700395 def testChromeAndAppShellDetection(self):
Daniel Eratf53bd3a2016-12-02 11:28:36 -0700396 """Check for a chrome deployment when app_shell also exists."""
Steve Fung63d705d2014-03-16 03:14:03 -0700397 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
398 makedirs=True)
Daniel Erat1ae46382014-08-14 10:23:39 -0700399 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'app_shell'),
Steve Fung63d705d2014-03-16 03:14:03 -0700400 makedirs=True)
401 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700402 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700403 self.assertFalse(self.getCopyPath('app_shell'))
Steve Fung63d705d2014-03-16 03:14:03 -0700404
Steve Funge984a532013-11-25 17:09:25 -0800405 def testChromeDetection(self):
406 """Check for a regular chrome deployment"""
407 osutils.Touch(os.path.join(self.deploy.options.build_dir, 'chrome'),
408 makedirs=True)
409 self.deploy._CheckDeployType()
Daniel Erat1ae46382014-08-14 10:23:39 -0700410 self.assertTrue(self.getCopyPath('chrome'))
Daniel Erat9813f0e2014-11-12 11:00:28 -0700411 self.assertFalse(self.getCopyPath('app_shell'))
Ben Pastenee484b342020-06-30 18:29:27 -0700412
413
414class TestDeployTestBinaries(cros_test_lib.RunCommandTempDirTestCase):
415 """Tests _DeployTestBinaries()."""
416
417 def setUp(self):
418 options = _ParseCommandLine(list(_REGULAR_TO) + [
419 '--board', _TARGET_BOARD, '--force', '--mount',
420 '--build-dir', os.path.join(self.tempdir, 'build_dir'),
421 '--nostrip'])
422 self.deploy = deploy_chrome.DeployChrome(
423 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
424
Brian Sheedy86f12342020-10-29 15:30:02 -0700425 def _SimulateBinaries(self):
426 # Ensure the staging dir contains the right binaries to copy over.
Ben Pastenee484b342020-06-30 18:29:27 -0700427 test_binaries = [
428 'run_a_tests',
429 'run_b_tests',
430 'run_c_tests',
431 ]
432 # Simulate having the binaries both on the device and in our local build
433 # dir.
434 self.rc.AddCmdResult(
435 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD),
436 stdout='\n'.join(test_binaries))
437 for binary in test_binaries:
438 osutils.Touch(os.path.join(self.deploy.options.build_dir, binary),
439 makedirs=True, mode=0o700)
Brian Sheedy86f12342020-10-29 15:30:02 -0700440 return test_binaries
Ben Pastenee484b342020-06-30 18:29:27 -0700441
Brian Sheedy86f12342020-10-29 15:30:02 -0700442 def _AssertBinariesInStagingDir(self, test_binaries):
Ben Pastenee484b342020-06-30 18:29:27 -0700443 # Ensure the binaries were placed in the staging dir used to copy them over.
444 staging_dir = os.path.join(
445 self.tempdir, os.path.basename(deploy_chrome._CHROME_TEST_BIN_DIR))
446 for binary in test_binaries:
447 self.assertIn(binary, os.listdir(staging_dir))
Erik Chen75a2f492020-08-06 19:15:11 -0700448
Brian Sheedy86f12342020-10-29 15:30:02 -0700449 def testFindError(self):
450 """Ensure an error is thrown if we can't inspect the device."""
451 self.rc.AddCmdResult(
452 partial_mock.In(deploy_chrome._FIND_TEST_BIN_CMD), 1)
453 self.assertRaises(
454 deploy_chrome.DeployFailure, self.deploy._DeployTestBinaries)
455
456 def testSuccess(self):
457 """Ensure that the happy path succeeds as expected."""
458 test_binaries = self._SimulateBinaries()
459 self.deploy._DeployTestBinaries()
460 self._AssertBinariesInStagingDir(test_binaries)
461
462 def testRetrySuccess(self):
463 """Ensure that a transient exception still results in success."""
464 # Raises a RunCommandError on its first invocation, but passes on subsequent
465 # calls.
466 def SideEffect(*args, **kwargs):
Yuke Liaobe6bac32020-12-26 22:16:49 -0800467 # pylint: disable=unused-argument
Brian Sheedy86f12342020-10-29 15:30:02 -0700468 if not SideEffect.called:
469 SideEffect.called = True
470 raise cros_build_lib.RunCommandError('fail')
471 SideEffect.called = False
472
473 test_binaries = self._SimulateBinaries()
474 with mock.patch.object(
475 remote_access.ChromiumOSDevice, 'CopyToDevice',
476 side_effect=SideEffect) as copy_mock:
477 self.deploy._DeployTestBinaries()
478 self.assertEqual(copy_mock.call_count, 2)
479 self._AssertBinariesInStagingDir(test_binaries)
480
481 def testRetryFailure(self):
482 """Ensure that consistent exceptions result in failure."""
483 self._SimulateBinaries()
484 with self.assertRaises(cros_build_lib.RunCommandError):
485 with mock.patch.object(
486 remote_access.ChromiumOSDevice, 'CopyToDevice',
487 side_effect=cros_build_lib.RunCommandError('fail')):
488 self.deploy._DeployTestBinaries()
489
Erik Chen75a2f492020-08-06 19:15:11 -0700490
491class LacrosPerformTest(cros_test_lib.RunCommandTempDirTestCase):
492 """Line coverage for Perform() method with --lacros option."""
493
494 def setUp(self):
Yuke Liao24fc60c2020-12-26 22:16:49 -0800495 self.deploy = None
496 self._ran_start_command = False
497 self.StartPatcher(parallel_unittest.ParallelMock())
498
499 def start_ui_side_effect(*args, **kwargs):
500 # pylint: disable=unused-argument
501 self._ran_start_command = True
502
503 self.rc.AddCmdResult(partial_mock.In('start ui'),
504 side_effect=start_ui_side_effect)
505
506 def prepareDeploy(self, options=None):
507 if not options:
508 options = _ParseCommandLine([
509 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
510 '--device', 'monkey'
511 ])
Erik Chen75a2f492020-08-06 19:15:11 -0700512 self.deploy = deploy_chrome.DeployChrome(
513 options, self.tempdir, os.path.join(self.tempdir, 'staging'))
514
515 # These methods being mocked are all side effects expected for a --lacros
516 # deploy.
517 self.deploy._EnsureTargetDir = mock.Mock()
518 self.deploy._GetDeviceInfo = mock.Mock()
519 self.deploy._CheckConnection = mock.Mock()
520 self.deploy._MountRootfsAsWritable = mock.Mock()
521 self.deploy._PrepareStagingDir = mock.Mock()
522 self.deploy._CheckDeviceFreeSpace = mock.Mock()
Yuke Liaobe6bac32020-12-26 22:16:49 -0800523 self.deploy._KillAshChromeIfNeeded = mock.Mock()
Erik Chen75a2f492020-08-06 19:15:11 -0700524
525 def testConfNotModified(self):
526 """When the conf file is not modified we don't restart chrome ."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800527 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700528 self.deploy.Perform()
529 self.deploy._KillAshChromeIfNeeded.assert_not_called()
530 self.assertFalse(self._ran_start_command)
531
532 def testConfModified(self):
533 """When the conf file is modified we restart chrome."""
Yuke Liao24fc60c2020-12-26 22:16:49 -0800534 self.prepareDeploy()
Erik Chen75a2f492020-08-06 19:15:11 -0700535
536 # We intentionally add '\n' to MODIFIED_CONF_FILE to simulate echo adding a
537 # newline when invoked in the shell.
538 self.rc.AddCmdResult(
539 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
540 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
541
542 self.deploy.Perform()
543 self.deploy._KillAshChromeIfNeeded.assert_called()
544 self.assertTrue(self._ran_start_command)
Yuke Liao24fc60c2020-12-26 22:16:49 -0800545
546 def testSkipModifyingConf(self):
547 """SKip modifying the config file when the argument is specified."""
548 self.prepareDeploy(
549 _ParseCommandLine([
550 '--lacros', '--nostrip', '--build-dir', '/path/to/nowhere',
551 '--device', 'monkey', '--skip-modifying-config-file'
552 ]))
553
554 self.rc.AddCmdResult(
555 partial_mock.In(deploy_chrome.ENABLE_LACROS_VIA_CONF_COMMAND),
556 stdout=deploy_chrome.MODIFIED_CONF_FILE + '\n')
557
558 self.deploy.Perform()
559 self.deploy._KillAshChromeIfNeeded.assert_not_called()
560 self.assertFalse(self._ran_start_command)