blob: fba510e6d6ba508330d6fe86265e1307f7ebabcf [file] [log] [blame]
Alex Kleinda35fcf2019-03-07 16:01:15 -07001# Copyright 2019 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Sysroot controller tests."""
6
Michael Mortensen798ee192020-01-17 13:04:43 -07007import datetime
Alex Kleinda35fcf2019-03-07 16:01:15 -07008import os
9
Alex Klein231d2da2019-07-22 16:44:45 -060010from chromite.api import api_config
Alex Klein8cb365a2019-05-15 16:24:53 -060011from chromite.api import controller
Alex Kleinca572ee2020-09-03 10:47:14 -060012from chromite.api.controller import controller_util
Alex Kleinda35fcf2019-03-07 16:01:15 -070013from chromite.api.controller import sysroot as sysroot_controller
14from chromite.api.gen.chromite.api import sysroot_pb2
Michael Mortensen3f6b4bd2020-02-07 14:16:43 -070015from chromite.api.gen.chromiumos import common_pb2
LaMont Jonesc0343fa2020-08-12 18:58:31 -060016from chromite.lib import binpkg
Alex Kleinda35fcf2019-03-07 16:01:15 -070017from chromite.lib import cros_build_lib
18from chromite.lib import cros_test_lib
19from chromite.lib import osutils
Alex Kleinda35fcf2019-03-07 16:01:15 -070020from chromite.lib import sysroot_lib
Alex Klein18a60af2020-06-11 12:08:47 -060021from chromite.lib.parser import package_info
Alex Kleinda35fcf2019-03-07 16:01:15 -070022from chromite.service import sysroot as sysroot_service
23
24
Alex Klein231d2da2019-07-22 16:44:45 -060025class CreateTest(cros_test_lib.MockTestCase, api_config.ApiConfigMixin):
Alex Kleinda35fcf2019-03-07 16:01:15 -070026 """Create function tests."""
27
28 def _InputProto(self, build_target=None, profile=None, replace=False,
LaMont Jonesc0343fa2020-08-12 18:58:31 -060029 current=False, package_indexes=None):
Alex Kleinda35fcf2019-03-07 16:01:15 -070030 """Helper to build and input proto instance."""
31 proto = sysroot_pb2.SysrootCreateRequest()
32 if build_target:
33 proto.build_target.name = build_target
34 if profile:
35 proto.profile.name = profile
36 if replace:
37 proto.flags.replace = replace
38 if current:
39 proto.flags.chroot_current = current
LaMont Jonesc0343fa2020-08-12 18:58:31 -060040 if package_indexes:
41 proto.package_indexes.extend(package_indexes)
Alex Kleinda35fcf2019-03-07 16:01:15 -070042
43 return proto
44
45 def _OutputProto(self):
46 """Helper to build output proto instance."""
47 return sysroot_pb2.SysrootCreateResponse()
48
Alex Klein231d2da2019-07-22 16:44:45 -060049 def testValidateOnly(self):
50 """Sanity check that a validate only call does not execute any logic."""
51 patch = self.PatchObject(sysroot_service, 'Create')
52
53 board = 'board'
54 profile = None
55 force = False
56 upgrade_chroot = True
57 in_proto = self._InputProto(build_target=board, profile=profile,
58 replace=force, current=not upgrade_chroot)
59 sysroot_controller.Create(in_proto, self._OutputProto(),
60 self.validate_only_config)
61 patch.assert_not_called()
62
Alex Klein076841b2019-08-29 15:19:39 -060063 def testMockCall(self):
64 """Sanity check that a mock call does not execute any logic."""
65 patch = self.PatchObject(sysroot_service, 'Create')
66 request = self._InputProto()
67 response = self._OutputProto()
68
69 rc = sysroot_controller.Create(request, response, self.mock_call_config)
70
71 patch.assert_not_called()
72 self.assertEqual(controller.RETURN_CODE_SUCCESS, rc)
73
74 def testMockError(self):
75 """Sanity check that a mock error does not execute any logic."""
76 patch = self.PatchObject(sysroot_service, 'Create')
77 request = self._InputProto()
78 response = self._OutputProto()
79
80 rc = sysroot_controller.Create(request, response, self.mock_error_config)
81
82 patch.assert_not_called()
83 self.assertEqual(controller.RETURN_CODE_UNRECOVERABLE, rc)
84
Alex Kleinda35fcf2019-03-07 16:01:15 -070085 def testArgumentValidation(self):
86 """Test the input argument validation."""
87 # Error when no name provided.
88 in_proto = self._InputProto()
89 out_proto = self._OutputProto()
90 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -060091 sysroot_controller.Create(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -070092
93 # Valid when board passed.
94 result = sysroot_lib.Sysroot('/sysroot/path')
95 patch = self.PatchObject(sysroot_service, 'Create', return_value=result)
96 in_proto = self._InputProto('board')
97 out_proto = self._OutputProto()
Alex Klein231d2da2019-07-22 16:44:45 -060098 sysroot_controller.Create(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -070099 patch.assert_called_once()
100
101 def testArgumentHandling(self):
102 """Test the arguments get processed and passed correctly."""
103 sysroot_path = '/sysroot/path'
104
105 sysroot = sysroot_lib.Sysroot(sysroot_path)
106 create_patch = self.PatchObject(sysroot_service, 'Create',
107 return_value=sysroot)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700108 rc_patch = self.PatchObject(sysroot_service, 'SetupBoardRunConfig')
109
110 # Default values.
111 board = 'board'
112 profile = None
113 force = False
114 upgrade_chroot = True
115 in_proto = self._InputProto(build_target=board, profile=profile,
116 replace=force, current=not upgrade_chroot)
117 out_proto = self._OutputProto()
Alex Klein231d2da2019-07-22 16:44:45 -0600118 sysroot_controller.Create(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700119
120 # Default value checks.
LaMont Jonesfeffd1b2020-08-05 18:24:59 -0600121 rc_patch.assert_called_with(force=force, upgrade_chroot=upgrade_chroot,
122 package_indexes=[])
Alex Kleinda35fcf2019-03-07 16:01:15 -0700123 self.assertEqual(board, out_proto.sysroot.build_target.name)
124 self.assertEqual(sysroot_path, out_proto.sysroot.path)
125
126 # Not default values.
127 create_patch.reset_mock()
128 board = 'board'
129 profile = 'profile'
130 force = True
131 upgrade_chroot = False
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600132 package_indexes = [
133 common_pb2.PackageIndexInfo(
134 snapshot_sha='SHA', snapshot_number=5,
135 build_target=common_pb2.BuildTarget(name=board),
136 location='LOCATION', profile=common_pb2.Profile(name=profile)),
137 common_pb2.PackageIndexInfo(
138 snapshot_sha='SHA2', snapshot_number=4,
139 build_target=common_pb2.BuildTarget(name=board),
140 location='LOCATION2', profile=common_pb2.Profile(name=profile))]
141
Alex Kleinda35fcf2019-03-07 16:01:15 -0700142 in_proto = self._InputProto(build_target=board, profile=profile,
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600143 replace=force, current=not upgrade_chroot,
144 package_indexes=package_indexes)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700145 out_proto = self._OutputProto()
Alex Klein231d2da2019-07-22 16:44:45 -0600146 sysroot_controller.Create(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700147
148 # Not default value checks.
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600149 rc_patch.assert_called_with(
150 force=force, package_indexes=[
151 binpkg.PackageIndexInfo.from_protobuf(x)
152 for x in package_indexes
153 ], upgrade_chroot=upgrade_chroot)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700154 self.assertEqual(board, out_proto.sysroot.build_target.name)
155 self.assertEqual(sysroot_path, out_proto.sysroot.path)
156
157
Michael Mortensen3f6b4bd2020-02-07 14:16:43 -0700158class GenerateArchiveTest(cros_test_lib.MockTempDirTestCase,
159 api_config.ApiConfigMixin):
160 """GenerateArchive function tests."""
161
162 def setUp(self):
163 self.chroot_path = '/path/to/chroot'
164 self.board = 'board'
165
166 def _InputProto(self, build_target=None, chroot_path=None, pkg_list=None):
167 """Helper to build and input proto instance."""
168 # pkg_list will be a list of category/package strings such as
169 # ['virtual/target-fuzzers'].
170 if pkg_list:
171 package_list = []
172 for pkg in pkg_list:
173 pkg_string_parts = pkg.split('/')
Alex Klein18a60af2020-06-11 12:08:47 -0600174 package_info_msg = common_pb2.PackageInfo(
Michael Mortensen3f6b4bd2020-02-07 14:16:43 -0700175 category=pkg_string_parts[0],
176 package_name=pkg_string_parts[1])
Alex Klein18a60af2020-06-11 12:08:47 -0600177 package_list.append(package_info_msg)
Michael Mortensen3f6b4bd2020-02-07 14:16:43 -0700178 else:
179 package_list = []
180
181 return sysroot_pb2.SysrootGenerateArchiveRequest(
182 build_target={'name': build_target},
183 chroot={'path': chroot_path},
184 packages=package_list)
185
186 def _OutputProto(self):
187 """Helper to build output proto instance."""
188 return sysroot_pb2.SysrootGenerateArchiveResponse()
189
190 def testValidateOnly(self):
191 """Sanity check that a validate only call does not execute any logic."""
192 patch = self.PatchObject(sysroot_service, 'GenerateArchive')
193
194 in_proto = self._InputProto(build_target=self.board,
195 chroot_path=self.chroot_path,
196 pkg_list=['virtual/target-fuzzers'])
197 sysroot_controller.GenerateArchive(in_proto, self._OutputProto(),
198 self.validate_only_config)
199 patch.assert_not_called()
200
201 def testMockCall(self):
202 """Sanity check that a mock call does not execute any logic."""
203 patch = self.PatchObject(sysroot_service, 'GenerateArchive')
204
205 in_proto = self._InputProto(build_target=self.board,
206 chroot_path=self.chroot_path,
207 pkg_list=['virtual/target-fuzzers'])
208 sysroot_controller.GenerateArchive(in_proto,
209 self._OutputProto(),
210 self.mock_call_config)
211 patch.assert_not_called()
212
213 def testArgumentValidation(self):
214 """Test the input argument validation."""
215 # Error when no build target provided.
216 in_proto = self._InputProto()
217 out_proto = self._OutputProto()
218 with self.assertRaises(cros_build_lib.DieSystemExit):
219 sysroot_controller.GenerateArchive(in_proto, out_proto, self.api_config)
220
221 # Error when packages is not specified.
222 in_proto = self._InputProto(build_target='board',
223 chroot_path=self.chroot_path)
224 with self.assertRaises(cros_build_lib.DieSystemExit):
225 sysroot_controller.GenerateArchive(in_proto, out_proto, self.api_config)
226
227 # Valid when board, chroot path, and package are specified.
228 patch = self.PatchObject(sysroot_service, 'GenerateArchive',
229 return_value='/path/to/sysroot/tar.bz')
230 in_proto = self._InputProto(build_target='board',
231 chroot_path=self.chroot_path,
232 pkg_list=['virtual/target-fuzzers'])
233 out_proto = self._OutputProto()
234 sysroot_controller.GenerateArchive(in_proto, out_proto, self.api_config)
235 patch.assert_called_once()
236
237
Alex Klein231d2da2019-07-22 16:44:45 -0600238class InstallToolchainTest(cros_test_lib.MockTempDirTestCase,
239 api_config.ApiConfigMixin):
Alex Kleinda35fcf2019-03-07 16:01:15 -0700240 """Install toolchain function tests."""
241
242 def setUp(self):
243 self.PatchObject(cros_build_lib, 'IsInsideChroot', return_value=True)
Alex Kleina9d64602019-05-17 14:55:37 -0600244 # Avoid running the portageq command.
245 self.PatchObject(sysroot_controller, '_LogBinhost')
Alex Kleinda35fcf2019-03-07 16:01:15 -0700246 self.board = 'board'
247 self.sysroot = os.path.join(self.tempdir, 'board')
248 self.invalid_sysroot = os.path.join(self.tempdir, 'invalid', 'sysroot')
249 osutils.SafeMakedirs(self.sysroot)
Lizzy Presland7e23a612021-11-09 21:49:42 +0000250 # Set up portage log directory.
Lizzy Presland4c279832021-11-19 20:27:43 +0000251 self.target_sysroot = sysroot_lib.Sysroot(self.sysroot)
252 self.portage_dir = self.target_sysroot.portage_logdir
Lizzy Presland7e23a612021-11-09 21:49:42 +0000253 osutils.SafeMakedirs(self.portage_dir)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700254
255 def _InputProto(self, build_target=None, sysroot_path=None,
256 compile_source=False):
Alex Kleind4e1e422019-03-18 16:00:41 -0600257 """Helper to build an input proto instance."""
Alex Kleinda35fcf2019-03-07 16:01:15 -0700258 proto = sysroot_pb2.InstallToolchainRequest()
259 if build_target:
260 proto.sysroot.build_target.name = build_target
261 if sysroot_path:
262 proto.sysroot.path = sysroot_path
263 if compile_source:
264 proto.flags.compile_source = compile_source
265
266 return proto
267
268 def _OutputProto(self):
269 """Helper to build output proto instance."""
270 return sysroot_pb2.InstallToolchainResponse()
271
Lizzy Presland4c279832021-11-19 20:27:43 +0000272 def _CreatePortageLogFile(self, log_path, pkg_info, timestamp):
Lizzy Presland7e23a612021-11-09 21:49:42 +0000273 """Creates a log file for testing for individual packages built by Portage.
274
275 Args:
Lizzy Presland4c279832021-11-19 20:27:43 +0000276 log_path (pathlike): the PORTAGE_LOGDIR path
Lizzy Presland7e23a612021-11-09 21:49:42 +0000277 pkg_info (PackageInfo): name components for log file.
278 timestamp (datetime): timestamp used to name the file.
279 """
Lizzy Presland4c279832021-11-19 20:27:43 +0000280 path = os.path.join(log_path,
Lizzy Presland7e23a612021-11-09 21:49:42 +0000281 f'{pkg_info.category}:{pkg_info.package}:' \
282 f'{timestamp.strftime("%Y%m%d-%H%M%S")}.log')
283 osutils.WriteFile(path,
284 f'Test log file for package {pkg_info.category}/'
285 f'{pkg_info.package} written to {path}')
286 return path
287
Alex Klein231d2da2019-07-22 16:44:45 -0600288 def testValidateOnly(self):
289 """Sanity check that a validate only call does not execute any logic."""
290 patch = self.PatchObject(sysroot_service, 'InstallToolchain')
291
292 in_proto = self._InputProto(build_target=self.board,
293 sysroot_path=self.sysroot)
294 sysroot_controller.InstallToolchain(in_proto, self._OutputProto(),
295 self.validate_only_config)
296 patch.assert_not_called()
297
Alex Klein076841b2019-08-29 15:19:39 -0600298 def testMockCall(self):
299 """Sanity check that a mock call does not execute any logic."""
300 patch = self.PatchObject(sysroot_service, 'InstallToolchain')
301 request = self._InputProto()
302 response = self._OutputProto()
303
304 rc = sysroot_controller.InstallToolchain(request, response,
305 self.mock_call_config)
306
307 patch.assert_not_called()
308 self.assertEqual(controller.RETURN_CODE_SUCCESS, rc)
309
310 def testMockError(self):
311 """Sanity check that a mock error does not execute any logic."""
312 patch = self.PatchObject(sysroot_service, 'InstallToolchain')
313 request = self._InputProto()
314 response = self._OutputProto()
315
316 rc = sysroot_controller.InstallToolchain(request, response,
317 self.mock_error_config)
318
319 patch.assert_not_called()
320 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
321 self.assertTrue(response.failed_packages)
322
Alex Kleinda35fcf2019-03-07 16:01:15 -0700323 def testArgumentValidation(self):
324 """Test the argument validation."""
325 # Test errors on missing inputs.
326 out_proto = self._OutputProto()
327 # Both missing.
328 in_proto = self._InputProto()
329 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600330 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700331
332 # Sysroot path missing.
333 in_proto = self._InputProto(build_target=self.board)
334 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600335 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700336
337 # Build target name missing.
338 in_proto = self._InputProto(sysroot_path=self.sysroot)
339 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600340 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700341
342 # Both provided, but invalid sysroot path.
343 in_proto = self._InputProto(build_target=self.board,
344 sysroot_path=self.invalid_sysroot)
345 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600346 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700347
348 def testSuccessOutputHandling(self):
349 """Test the output is processed and recorded correctly."""
350 self.PatchObject(sysroot_service, 'InstallToolchain')
351 out_proto = self._OutputProto()
352 in_proto = self._InputProto(build_target=self.board,
353 sysroot_path=self.sysroot)
354
Alex Klein231d2da2019-07-22 16:44:45 -0600355 rc = sysroot_controller.InstallToolchain(in_proto, out_proto,
356 self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700357 self.assertFalse(rc)
358 self.assertFalse(out_proto.failed_packages)
359
360
361 def testErrorOutputHandling(self):
362 """Test the error output is processed and recorded correctly."""
363 out_proto = self._OutputProto()
364 in_proto = self._InputProto(build_target=self.board,
365 sysroot_path=self.sysroot)
366
367 err_pkgs = ['cat/pkg', 'cat2/pkg2']
Alex Kleinea0c89e2021-09-09 15:17:35 -0600368 err_cpvs = [package_info.parse(pkg) for pkg in err_pkgs]
Alex Kleinda35fcf2019-03-07 16:01:15 -0700369 expected = [('cat', 'pkg'), ('cat2', 'pkg2')]
Lizzy Presland7e23a612021-11-09 21:49:42 +0000370
371 new_logs = {}
372 for i, pkg in enumerate(err_pkgs):
Lizzy Presland4c279832021-11-19 20:27:43 +0000373 self._CreatePortageLogFile(self.portage_dir, err_cpvs[i],
Lizzy Presland7e23a612021-11-09 21:49:42 +0000374 datetime.datetime(2021, 6, 9, 13, 37, 0))
Lizzy Presland4c279832021-11-19 20:27:43 +0000375 new_logs[pkg] = self._CreatePortageLogFile(self.portage_dir, err_cpvs[i],
Lizzy Presland7e23a612021-11-09 21:49:42 +0000376 datetime.datetime(2021, 6, 9,
377 16, 20, 0)
378 )
379
Alex Kleinda35fcf2019-03-07 16:01:15 -0700380 err = sysroot_lib.ToolchainInstallError('Error',
381 cros_build_lib.CommandResult(),
382 tc_info=err_cpvs)
383 self.PatchObject(sysroot_service, 'InstallToolchain', side_effect=err)
384
Alex Klein231d2da2019-07-22 16:44:45 -0600385 rc = sysroot_controller.InstallToolchain(in_proto, out_proto,
386 self.api_config)
Alex Klein8cb365a2019-05-15 16:24:53 -0600387 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700388 self.assertTrue(out_proto.failed_packages)
Lizzy Presland7e23a612021-11-09 21:49:42 +0000389 self.assertTrue(out_proto.failed_package_data)
390 # This needs to return 2 to indicate the available error response.
391 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
392 for data in out_proto.failed_package_data:
393 package = controller_util.deserialize_package_info(data.name)
394 cat_pkg = (data.name.category, data.name.package_name)
395 self.assertIn(cat_pkg, expected)
396 self.assertEqual(data.log_path.path, new_logs[package.atom])
397
398 # TODO(b/206514844): remove when field is deleted
Alex Kleinda35fcf2019-03-07 16:01:15 -0700399 for package in out_proto.failed_packages:
400 cat_pkg = (package.category, package.package_name)
401 self.assertIn(cat_pkg, expected)
Alex Kleind4e1e422019-03-18 16:00:41 -0600402
403
Alex Klein231d2da2019-07-22 16:44:45 -0600404class InstallPackagesTest(cros_test_lib.MockTempDirTestCase,
405 api_config.ApiConfigMixin):
Alex Kleind4e1e422019-03-18 16:00:41 -0600406 """InstallPackages tests."""
407
408 def setUp(self):
409 self.PatchObject(cros_build_lib, 'IsInsideChroot', return_value=True)
Alex Kleina9d64602019-05-17 14:55:37 -0600410 # Avoid running the portageq command.
411 self.PatchObject(sysroot_controller, '_LogBinhost')
Alex Kleind4e1e422019-03-18 16:00:41 -0600412 self.build_target = 'board'
413 self.sysroot = os.path.join(self.tempdir, 'build', 'board')
414 osutils.SafeMakedirs(self.sysroot)
Lizzy Presland7e23a612021-11-09 21:49:42 +0000415 # Set up portage log directory.
Lizzy Presland4c279832021-11-19 20:27:43 +0000416 self.target_sysroot = sysroot_lib.Sysroot(self.sysroot)
417 self.portage_dir = self.target_sysroot.portage_logdir
Lizzy Presland7e23a612021-11-09 21:49:42 +0000418 osutils.SafeMakedirs(self.portage_dir)
Michael Mortensen798ee192020-01-17 13:04:43 -0700419 # Set up goma directories.
420 self.goma_dir = os.path.join(self.tempdir, 'goma_dir')
421 osutils.SafeMakedirs(self.goma_dir)
422 self.goma_out_dir = os.path.join(self.tempdir, 'goma_out_dir')
423 osutils.SafeMakedirs(self.goma_out_dir)
Michael Mortensen4ccfb082020-01-22 16:24:03 -0700424 os.environ['GLOG_log_dir'] = self.goma_dir
Alex Kleind4e1e422019-03-18 16:00:41 -0600425
426 def _InputProto(self, build_target=None, sysroot_path=None,
Michael Mortensen798ee192020-01-17 13:04:43 -0700427 build_source=False, goma_dir=None, goma_log_dir=None,
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600428 goma_stats_file=None, goma_counterz_file=None,
Alex Kleinca572ee2020-09-03 10:47:14 -0600429 package_indexes=None, packages=None):
Alex Kleind4e1e422019-03-18 16:00:41 -0600430 """Helper to build an input proto instance."""
431 instance = sysroot_pb2.InstallPackagesRequest()
432
433 if build_target:
434 instance.sysroot.build_target.name = build_target
435 if sysroot_path:
436 instance.sysroot.path = sysroot_path
437 if build_source:
438 instance.flags.build_source = build_source
Michael Mortensen798ee192020-01-17 13:04:43 -0700439 if goma_dir:
440 instance.goma_config.goma_dir = goma_dir
441 if goma_log_dir:
442 instance.goma_config.log_dir.dir = goma_log_dir
443 if goma_stats_file:
444 instance.goma_config.stats_file = goma_stats_file
445 if goma_counterz_file:
446 instance.goma_config.counterz_file = goma_counterz_file
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600447 if package_indexes:
448 instance.package_indexes.extend(package_indexes)
Alex Kleinca572ee2020-09-03 10:47:14 -0600449 if packages:
450 for pkg in packages:
Alex Kleinb397b792021-09-09 15:55:45 -0600451 pkg_info = package_info.parse(pkg)
452 pkg_info_msg = instance.packages.add()
453 controller_util.serialize_package_info(pkg_info, pkg_info_msg)
Alex Kleind4e1e422019-03-18 16:00:41 -0600454 return instance
455
456 def _OutputProto(self):
457 """Helper to build an empty output proto instance."""
458 return sysroot_pb2.InstallPackagesResponse()
459
Michael Mortensen798ee192020-01-17 13:04:43 -0700460 def _CreateGomaLogFile(self, goma_log_dir, name, timestamp):
461 """Creates a log file for testing.
462
463 Args:
464 goma_log_dir (str): Directory where the file will be created.
465 name (str): Log file 'base' name that is combined with the timestamp.
466 timestamp (datetime): timestamp that is written to the file.
467 """
468 path = os.path.join(
469 goma_log_dir,
470 '%s.host.log.INFO.%s' % (name, timestamp.strftime('%Y%m%d-%H%M%S.%f')))
471 osutils.WriteFile(
472 path,
473 timestamp.strftime('Goma log file created at: %Y/%m/%d %H:%M:%S'))
474
Lizzy Presland4c279832021-11-19 20:27:43 +0000475 def _CreatePortageLogFile(self, log_path, pkg_info, timestamp):
Lizzy Presland7e23a612021-11-09 21:49:42 +0000476 """Creates a log file for testing for individual packages built by Portage.
477
478 Args:
Lizzy Presland4c279832021-11-19 20:27:43 +0000479 log_path (pathlike): the PORTAGE_LOGDIR path
Lizzy Presland7e23a612021-11-09 21:49:42 +0000480 pkg_info (PackageInfo): name components for log file.
481 timestamp (datetime): timestamp used to name the file.
482 """
Lizzy Presland4c279832021-11-19 20:27:43 +0000483 path = os.path.join(log_path,
Lizzy Presland7e23a612021-11-09 21:49:42 +0000484 f'{pkg_info.category}:{pkg_info.package}:' \
485 f'{timestamp.strftime("%Y%m%d-%H%M%S")}.log')
486 osutils.WriteFile(path, f'Test log file for package {pkg_info.category}/'
487 f'{pkg_info.package} written to {path}')
488 return path
489
Alex Klein231d2da2019-07-22 16:44:45 -0600490 def testValidateOnly(self):
491 """Sanity check that a validate only call does not execute any logic."""
492 patch = self.PatchObject(sysroot_service, 'BuildPackages')
493
494 in_proto = self._InputProto(build_target=self.build_target,
495 sysroot_path=self.sysroot)
496 sysroot_controller.InstallPackages(in_proto, self._OutputProto(),
497 self.validate_only_config)
498 patch.assert_not_called()
499
Alex Klein076841b2019-08-29 15:19:39 -0600500 def testMockCall(self):
501 """Sanity check that a mock call does not execute any logic."""
502 patch = self.PatchObject(sysroot_service, 'BuildPackages')
503 request = self._InputProto()
504 response = self._OutputProto()
505
506 rc = sysroot_controller.InstallPackages(request, response,
507 self.mock_call_config)
508
509 patch.assert_not_called()
510 self.assertEqual(controller.RETURN_CODE_SUCCESS, rc)
511
512 def testMockError(self):
513 """Sanity check that a mock error does not execute any logic."""
514 patch = self.PatchObject(sysroot_service, 'BuildPackages')
515 request = self._InputProto()
516 response = self._OutputProto()
517
518 rc = sysroot_controller.InstallPackages(request, response,
519 self.mock_error_config)
520
521 patch.assert_not_called()
522 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
523 self.assertTrue(response.failed_packages)
524
Alex Kleind4e1e422019-03-18 16:00:41 -0600525 def testArgumentValidationAllMissing(self):
526 """Test missing all arguments."""
527 out_proto = self._OutputProto()
528 in_proto = self._InputProto()
529 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600530 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600531
532 def testArgumentValidationNoSysroot(self):
533 """Test missing sysroot path."""
534 out_proto = self._OutputProto()
535 in_proto = self._InputProto(build_target=self.build_target)
536 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600537 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600538
539 def testArgumentValidationNoBuildTarget(self):
540 """Test missing build target name."""
541 out_proto = self._OutputProto()
542 in_proto = self._InputProto(sysroot_path=self.sysroot)
543 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600544 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600545
546 def testArgumentValidationInvalidSysroot(self):
547 """Test sysroot that hasn't had the toolchain installed."""
548 out_proto = self._OutputProto()
549 in_proto = self._InputProto(build_target=self.build_target,
550 sysroot_path=self.sysroot)
551 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
552 return_value=False)
553 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600554 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600555
Alex Kleinca572ee2020-09-03 10:47:14 -0600556 def testArgumentValidationInvalidPackage(self):
557 out_proto = self._OutputProto()
558 in_proto = self._InputProto(build_target=self.build_target,
559 sysroot_path=self.sysroot,
560 packages=['package-1.0.0-r2'])
561 with self.assertRaises(cros_build_lib.DieSystemExit):
562 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
563
Alex Kleind4e1e422019-03-18 16:00:41 -0600564 def testSuccessOutputHandling(self):
565 """Test successful call output handling."""
566 # Prevent argument validation error.
567 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
568 return_value=True)
569
570 in_proto = self._InputProto(build_target=self.build_target,
571 sysroot_path=self.sysroot)
572 out_proto = self._OutputProto()
573 self.PatchObject(sysroot_service, 'BuildPackages')
574
Alex Klein231d2da2019-07-22 16:44:45 -0600575 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
576 self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600577 self.assertFalse(rc)
578 self.assertFalse(out_proto.failed_packages)
579
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600580 def testSuccessPackageIndexes(self):
581 """Test successful call with package_indexes."""
582 # Prevent argument validation error.
583 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
584 return_value=True)
585 package_indexes = [
586 common_pb2.PackageIndexInfo(
587 snapshot_sha='SHA', snapshot_number=5,
588 build_target=common_pb2.BuildTarget(name='board'),
589 location='LOCATION', profile=common_pb2.Profile(name='profile')),
590 common_pb2.PackageIndexInfo(
591 snapshot_sha='SHA2', snapshot_number=4,
592 build_target=common_pb2.BuildTarget(name='board'),
593 location='LOCATION2', profile=common_pb2.Profile(name='profile'))]
594
595 in_proto = self._InputProto(build_target=self.build_target,
596 sysroot_path=self.sysroot,
597 package_indexes=package_indexes)
598
599 out_proto = self._OutputProto()
600 rc_patch = self.PatchObject(sysroot_service, 'BuildPackagesRunConfig')
601 self.PatchObject(sysroot_service, 'BuildPackages')
602
603 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
604 self.api_config)
605 self.assertFalse(rc)
Alex Kleineb76da72021-03-19 10:43:09 -0600606 rc_patch.assert_called_with(
607 usepkg=True,
608 install_debug_symbols=True,
609 packages=[],
610 package_indexes=[
611 binpkg.PackageIndexInfo.from_protobuf(x) for x in package_indexes
612 ],
613 use_flags=[],
614 use_goma=False,
Joanna Wang1ec0c812021-11-17 17:41:27 -0800615 use_remoteexec=False,
Alex Kleineb76da72021-03-19 10:43:09 -0600616 incremental_build=False,
Navil Perez5766d1b2021-05-26 17:38:15 +0000617 setup_board=False,
618 dryrun=False)
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600619
Michael Mortensen798ee192020-01-17 13:04:43 -0700620 def testSuccessWithGomaLogs(self):
621 """Test successful call with goma."""
622 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy',
623 datetime.datetime(2018, 9, 21, 12, 0, 0))
624 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy-subproc',
625 datetime.datetime(2018, 9, 21, 12, 1, 0))
626 self._CreateGomaLogFile(self.goma_dir, 'gomacc',
627 datetime.datetime(2018, 9, 21, 12, 2, 0))
628
629 # Prevent argument validation error.
630 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
631 return_value=True)
632
633 in_proto = self._InputProto(build_target=self.build_target,
634 sysroot_path=self.sysroot,
635 goma_dir=self.goma_dir,
636 goma_log_dir=self.goma_out_dir)
637
638 out_proto = self._OutputProto()
639 self.PatchObject(sysroot_service, 'BuildPackages')
640
641 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
642 self.api_config)
643 self.assertFalse(rc)
644 self.assertFalse(out_proto.failed_packages)
645 self.assertCountEqual(out_proto.goma_artifacts.log_files, [
646 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
647 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
648 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
649
650 def testSuccessWithGomaLogsAndStatsCounterzFiles(self):
651 """Test successful call with goma including stats and counterz files."""
652 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy',
653 datetime.datetime(2018, 9, 21, 12, 0, 0))
654 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy-subproc',
655 datetime.datetime(2018, 9, 21, 12, 1, 0))
656 self._CreateGomaLogFile(self.goma_dir, 'gomacc',
657 datetime.datetime(2018, 9, 21, 12, 2, 0))
658 # Create stats and counterz files.
659 osutils.WriteFile(os.path.join(self.goma_dir, 'stats.binaryproto'),
660 'File: stats.binaryproto')
661 osutils.WriteFile(os.path.join(self.goma_dir, 'counterz.binaryproto'),
662 'File: counterz.binaryproto')
663
664 # Prevent argument validation error.
665 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
666 return_value=True)
667
668 in_proto = self._InputProto(build_target=self.build_target,
669 sysroot_path=self.sysroot,
670 goma_dir=self.goma_dir,
671 goma_log_dir=self.goma_out_dir,
672 goma_stats_file='stats.binaryproto',
673 goma_counterz_file='counterz.binaryproto')
674
675 out_proto = self._OutputProto()
676 self.PatchObject(sysroot_service, 'BuildPackages')
677
678 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
679 self.api_config)
680 self.assertFalse(rc)
681 self.assertFalse(out_proto.failed_packages)
682 self.assertCountEqual(out_proto.goma_artifacts.log_files, [
683 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
684 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
685 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
686 # Verify that the output dir has 5 files -- since there should be 3 log
687 # files, the stats file, and the counterz file.
688 output_files = os.listdir(self.goma_out_dir)
689 self.assertCountEqual(output_files, [
690 'stats.binaryproto',
691 'counterz.binaryproto',
692 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
693 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
694 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
Michael Mortensen1c7439c2020-01-24 14:43:19 -0700695 self.assertEqual(out_proto.goma_artifacts.counterz_file,
696 'counterz.binaryproto')
697 self.assertEqual(out_proto.goma_artifacts.stats_file,
698 'stats.binaryproto')
Michael Mortensen798ee192020-01-17 13:04:43 -0700699
700 def testFailureMissingGomaStatsCounterzFiles(self):
701 """Test successful call with goma including stats and counterz files."""
702 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy',
703 datetime.datetime(2018, 9, 21, 12, 0, 0))
704 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy-subproc',
705 datetime.datetime(2018, 9, 21, 12, 1, 0))
706 self._CreateGomaLogFile(self.goma_dir, 'gomacc',
707 datetime.datetime(2018, 9, 21, 12, 2, 0))
708 # Note that stats and counterz files are not created, but are specified in
709 # the proto below.
710
711 # Prevent argument validation error.
712 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
713 return_value=True)
714
715 in_proto = self._InputProto(build_target=self.build_target,
716 sysroot_path=self.sysroot,
717 goma_dir=self.goma_dir,
718 goma_log_dir=self.goma_out_dir,
719 goma_stats_file='stats.binaryproto',
720 goma_counterz_file='counterz.binaryproto')
721
722 out_proto = self._OutputProto()
723 self.PatchObject(sysroot_service, 'BuildPackages')
724
Michael Mortensen1d6d5b02020-01-22 07:33:50 -0700725 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
726 self.api_config)
727 self.assertFalse(rc)
728 self.assertFalse(out_proto.failed_packages)
729 self.assertCountEqual(out_proto.goma_artifacts.log_files, [
730 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
731 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
732 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
733 self.assertFalse(out_proto.goma_artifacts.counterz_file)
734 self.assertFalse(out_proto.goma_artifacts.stats_file)
Michael Mortensen798ee192020-01-17 13:04:43 -0700735
Alex Kleind4e1e422019-03-18 16:00:41 -0600736 def testFailureOutputHandling(self):
737 """Test failed package handling."""
738 # Prevent argument validation error.
739 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
740 return_value=True)
741
742 in_proto = self._InputProto(build_target=self.build_target,
743 sysroot_path=self.sysroot)
744 out_proto = self._OutputProto()
745
746 # Failed package info and expected list for verification.
747 err_pkgs = ['cat/pkg', 'cat2/pkg2']
Lizzy Presland7e23a612021-11-09 21:49:42 +0000748 err_cpvs = [package_info.parse(cpv) for cpv in err_pkgs]
Alex Kleind4e1e422019-03-18 16:00:41 -0600749 expected = [('cat', 'pkg'), ('cat2', 'pkg2')]
750
Lizzy Presland7e23a612021-11-09 21:49:42 +0000751 new_logs = {}
752 for i, pkg in enumerate(err_pkgs):
Lizzy Presland4c279832021-11-19 20:27:43 +0000753 self._CreatePortageLogFile(self.portage_dir, err_cpvs[i],
Lizzy Presland7e23a612021-11-09 21:49:42 +0000754 datetime.datetime(2021, 6, 9, 13, 37, 0))
Lizzy Presland4c279832021-11-19 20:27:43 +0000755 new_logs[pkg] = self._CreatePortageLogFile(self.portage_dir, err_cpvs[i],
Lizzy Presland7e23a612021-11-09 21:49:42 +0000756 datetime.datetime(2021, 6, 9,
757 16, 20, 0)
758 )
Alex Kleind4e1e422019-03-18 16:00:41 -0600759 # Force error to be raised with the packages.
760 error = sysroot_lib.PackageInstallError('Error',
761 cros_build_lib.CommandResult(),
762 packages=err_cpvs)
763 self.PatchObject(sysroot_service, 'BuildPackages', side_effect=error)
764
Alex Klein231d2da2019-07-22 16:44:45 -0600765 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
766 self.api_config)
Alex Klein2557b4f2019-07-11 14:34:00 -0600767 # This needs to return 2 to indicate the available error response.
768 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
Lizzy Presland7e23a612021-11-09 21:49:42 +0000769 for data in out_proto.failed_package_data:
770 package = controller_util.deserialize_package_info(data.name)
771 cat_pkg = (data.name.category, data.name.package_name)
772 self.assertIn(cat_pkg, expected)
773 self.assertEqual(data.log_path.path, new_logs[package.atom])
774
775 # TODO(b/206514844): remove when field is deleted
Alex Kleind4e1e422019-03-18 16:00:41 -0600776 for package in out_proto.failed_packages:
777 cat_pkg = (package.category, package.package_name)
778 self.assertIn(cat_pkg, expected)
Alex Klein2557b4f2019-07-11 14:34:00 -0600779
780 def testNoPackageFailureOutputHandling(self):
781 """Test failure handling without packages to report."""
782 # Prevent argument validation error.
783 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
784 return_value=True)
785
786 in_proto = self._InputProto(build_target=self.build_target,
787 sysroot_path=self.sysroot)
788 out_proto = self._OutputProto()
789
790 # Force error to be raised with no packages.
791 error = sysroot_lib.PackageInstallError('Error',
792 cros_build_lib.CommandResult(),
793 packages=[])
794 self.PatchObject(sysroot_service, 'BuildPackages', side_effect=error)
795
Alex Klein231d2da2019-07-22 16:44:45 -0600796 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
797 self.api_config)
Alex Klein2557b4f2019-07-11 14:34:00 -0600798 # All we really care about is it's not 0 or 2 (response available), so
799 # test for that rather than a specific return code.
800 self.assertTrue(rc)
801 self.assertNotEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE,
802 rc)