blob: cfae62d3c2790b77732261fe019f995163a1d07f [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.
251 self.portage_dir = os.path.join(self.sysroot, 'tmp', 'portage', 'logs')
252 osutils.SafeMakedirs(self.portage_dir)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700253
254 def _InputProto(self, build_target=None, sysroot_path=None,
255 compile_source=False):
Alex Kleind4e1e422019-03-18 16:00:41 -0600256 """Helper to build an input proto instance."""
Alex Kleinda35fcf2019-03-07 16:01:15 -0700257 proto = sysroot_pb2.InstallToolchainRequest()
258 if build_target:
259 proto.sysroot.build_target.name = build_target
260 if sysroot_path:
261 proto.sysroot.path = sysroot_path
262 if compile_source:
263 proto.flags.compile_source = compile_source
264
265 return proto
266
267 def _OutputProto(self):
268 """Helper to build output proto instance."""
269 return sysroot_pb2.InstallToolchainResponse()
270
Lizzy Presland7e23a612021-11-09 21:49:42 +0000271 def _CreatePortageLogFile(self, root, pkg_info, timestamp):
272 """Creates a log file for testing for individual packages built by Portage.
273
274 Args:
275 root (pathlike): the sysroot path
276 pkg_info (PackageInfo): name components for log file.
277 timestamp (datetime): timestamp used to name the file.
278 """
279 path = os.path.join(root, 'tmp', 'portage', 'logs',
280 f'{pkg_info.category}:{pkg_info.package}:' \
281 f'{timestamp.strftime("%Y%m%d-%H%M%S")}.log')
282 osutils.WriteFile(path,
283 f'Test log file for package {pkg_info.category}/'
284 f'{pkg_info.package} written to {path}')
285 return path
286
Alex Klein231d2da2019-07-22 16:44:45 -0600287 def testValidateOnly(self):
288 """Sanity check that a validate only call does not execute any logic."""
289 patch = self.PatchObject(sysroot_service, 'InstallToolchain')
290
291 in_proto = self._InputProto(build_target=self.board,
292 sysroot_path=self.sysroot)
293 sysroot_controller.InstallToolchain(in_proto, self._OutputProto(),
294 self.validate_only_config)
295 patch.assert_not_called()
296
Alex Klein076841b2019-08-29 15:19:39 -0600297 def testMockCall(self):
298 """Sanity check that a mock call does not execute any logic."""
299 patch = self.PatchObject(sysroot_service, 'InstallToolchain')
300 request = self._InputProto()
301 response = self._OutputProto()
302
303 rc = sysroot_controller.InstallToolchain(request, response,
304 self.mock_call_config)
305
306 patch.assert_not_called()
307 self.assertEqual(controller.RETURN_CODE_SUCCESS, rc)
308
309 def testMockError(self):
310 """Sanity check that a mock error does not execute any logic."""
311 patch = self.PatchObject(sysroot_service, 'InstallToolchain')
312 request = self._InputProto()
313 response = self._OutputProto()
314
315 rc = sysroot_controller.InstallToolchain(request, response,
316 self.mock_error_config)
317
318 patch.assert_not_called()
319 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
320 self.assertTrue(response.failed_packages)
321
Alex Kleinda35fcf2019-03-07 16:01:15 -0700322 def testArgumentValidation(self):
323 """Test the argument validation."""
324 # Test errors on missing inputs.
325 out_proto = self._OutputProto()
326 # Both missing.
327 in_proto = self._InputProto()
328 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600329 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700330
331 # Sysroot path missing.
332 in_proto = self._InputProto(build_target=self.board)
333 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600334 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700335
336 # Build target name missing.
337 in_proto = self._InputProto(sysroot_path=self.sysroot)
338 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600339 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700340
341 # Both provided, but invalid sysroot path.
342 in_proto = self._InputProto(build_target=self.board,
343 sysroot_path=self.invalid_sysroot)
344 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600345 sysroot_controller.InstallToolchain(in_proto, out_proto, self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700346
347 def testSuccessOutputHandling(self):
348 """Test the output is processed and recorded correctly."""
349 self.PatchObject(sysroot_service, 'InstallToolchain')
350 out_proto = self._OutputProto()
351 in_proto = self._InputProto(build_target=self.board,
352 sysroot_path=self.sysroot)
353
Alex Klein231d2da2019-07-22 16:44:45 -0600354 rc = sysroot_controller.InstallToolchain(in_proto, out_proto,
355 self.api_config)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700356 self.assertFalse(rc)
357 self.assertFalse(out_proto.failed_packages)
358
359
360 def testErrorOutputHandling(self):
361 """Test the error output is processed and recorded correctly."""
362 out_proto = self._OutputProto()
363 in_proto = self._InputProto(build_target=self.board,
364 sysroot_path=self.sysroot)
365
366 err_pkgs = ['cat/pkg', 'cat2/pkg2']
Alex Kleinea0c89e2021-09-09 15:17:35 -0600367 err_cpvs = [package_info.parse(pkg) for pkg in err_pkgs]
Alex Kleinda35fcf2019-03-07 16:01:15 -0700368 expected = [('cat', 'pkg'), ('cat2', 'pkg2')]
Lizzy Presland7e23a612021-11-09 21:49:42 +0000369
370 new_logs = {}
371 for i, pkg in enumerate(err_pkgs):
372 self._CreatePortageLogFile(self.sysroot, err_cpvs[i],
373 datetime.datetime(2021, 6, 9, 13, 37, 0))
374 new_logs[pkg] = self._CreatePortageLogFile(self.sysroot, err_cpvs[i],
375 datetime.datetime(2021, 6, 9,
376 16, 20, 0)
377 )
378
Alex Kleinda35fcf2019-03-07 16:01:15 -0700379 err = sysroot_lib.ToolchainInstallError('Error',
380 cros_build_lib.CommandResult(),
381 tc_info=err_cpvs)
382 self.PatchObject(sysroot_service, 'InstallToolchain', side_effect=err)
383
Alex Klein231d2da2019-07-22 16:44:45 -0600384 rc = sysroot_controller.InstallToolchain(in_proto, out_proto,
385 self.api_config)
Alex Klein8cb365a2019-05-15 16:24:53 -0600386 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
Alex Kleinda35fcf2019-03-07 16:01:15 -0700387 self.assertTrue(out_proto.failed_packages)
Lizzy Presland7e23a612021-11-09 21:49:42 +0000388 self.assertTrue(out_proto.failed_package_data)
389 # This needs to return 2 to indicate the available error response.
390 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
391 for data in out_proto.failed_package_data:
392 package = controller_util.deserialize_package_info(data.name)
393 cat_pkg = (data.name.category, data.name.package_name)
394 self.assertIn(cat_pkg, expected)
395 self.assertEqual(data.log_path.path, new_logs[package.atom])
396
397 # TODO(b/206514844): remove when field is deleted
Alex Kleinda35fcf2019-03-07 16:01:15 -0700398 for package in out_proto.failed_packages:
399 cat_pkg = (package.category, package.package_name)
400 self.assertIn(cat_pkg, expected)
Alex Kleind4e1e422019-03-18 16:00:41 -0600401
402
Alex Klein231d2da2019-07-22 16:44:45 -0600403class InstallPackagesTest(cros_test_lib.MockTempDirTestCase,
404 api_config.ApiConfigMixin):
Alex Kleind4e1e422019-03-18 16:00:41 -0600405 """InstallPackages tests."""
406
407 def setUp(self):
408 self.PatchObject(cros_build_lib, 'IsInsideChroot', return_value=True)
Alex Kleina9d64602019-05-17 14:55:37 -0600409 # Avoid running the portageq command.
410 self.PatchObject(sysroot_controller, '_LogBinhost')
Alex Kleind4e1e422019-03-18 16:00:41 -0600411 self.build_target = 'board'
412 self.sysroot = os.path.join(self.tempdir, 'build', 'board')
413 osutils.SafeMakedirs(self.sysroot)
Lizzy Presland7e23a612021-11-09 21:49:42 +0000414 # Set up portage log directory.
415 self.portage_dir = os.path.join(self.sysroot, 'tmp', 'portage', 'logs')
416 osutils.SafeMakedirs(self.portage_dir)
Michael Mortensen798ee192020-01-17 13:04:43 -0700417 # Set up goma directories.
418 self.goma_dir = os.path.join(self.tempdir, 'goma_dir')
419 osutils.SafeMakedirs(self.goma_dir)
420 self.goma_out_dir = os.path.join(self.tempdir, 'goma_out_dir')
421 osutils.SafeMakedirs(self.goma_out_dir)
Michael Mortensen4ccfb082020-01-22 16:24:03 -0700422 os.environ['GLOG_log_dir'] = self.goma_dir
Alex Kleind4e1e422019-03-18 16:00:41 -0600423
424 def _InputProto(self, build_target=None, sysroot_path=None,
Michael Mortensen798ee192020-01-17 13:04:43 -0700425 build_source=False, goma_dir=None, goma_log_dir=None,
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600426 goma_stats_file=None, goma_counterz_file=None,
Alex Kleinca572ee2020-09-03 10:47:14 -0600427 package_indexes=None, packages=None):
Alex Kleind4e1e422019-03-18 16:00:41 -0600428 """Helper to build an input proto instance."""
429 instance = sysroot_pb2.InstallPackagesRequest()
430
431 if build_target:
432 instance.sysroot.build_target.name = build_target
433 if sysroot_path:
434 instance.sysroot.path = sysroot_path
435 if build_source:
436 instance.flags.build_source = build_source
Michael Mortensen798ee192020-01-17 13:04:43 -0700437 if goma_dir:
438 instance.goma_config.goma_dir = goma_dir
439 if goma_log_dir:
440 instance.goma_config.log_dir.dir = goma_log_dir
441 if goma_stats_file:
442 instance.goma_config.stats_file = goma_stats_file
443 if goma_counterz_file:
444 instance.goma_config.counterz_file = goma_counterz_file
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600445 if package_indexes:
446 instance.package_indexes.extend(package_indexes)
Alex Kleinca572ee2020-09-03 10:47:14 -0600447 if packages:
448 for pkg in packages:
Alex Kleinb397b792021-09-09 15:55:45 -0600449 pkg_info = package_info.parse(pkg)
450 pkg_info_msg = instance.packages.add()
451 controller_util.serialize_package_info(pkg_info, pkg_info_msg)
Alex Kleind4e1e422019-03-18 16:00:41 -0600452 return instance
453
454 def _OutputProto(self):
455 """Helper to build an empty output proto instance."""
456 return sysroot_pb2.InstallPackagesResponse()
457
Michael Mortensen798ee192020-01-17 13:04:43 -0700458 def _CreateGomaLogFile(self, goma_log_dir, name, timestamp):
459 """Creates a log file for testing.
460
461 Args:
462 goma_log_dir (str): Directory where the file will be created.
463 name (str): Log file 'base' name that is combined with the timestamp.
464 timestamp (datetime): timestamp that is written to the file.
465 """
466 path = os.path.join(
467 goma_log_dir,
468 '%s.host.log.INFO.%s' % (name, timestamp.strftime('%Y%m%d-%H%M%S.%f')))
469 osutils.WriteFile(
470 path,
471 timestamp.strftime('Goma log file created at: %Y/%m/%d %H:%M:%S'))
472
Lizzy Presland7e23a612021-11-09 21:49:42 +0000473 def _CreatePortageLogFile(self, root, pkg_info, timestamp):
474 """Creates a log file for testing for individual packages built by Portage.
475
476 Args:
477 root (pathlike): the root path, taken from a BuildTarget object.
478 pkg_info (PackageInfo): name components for log file.
479 timestamp (datetime): timestamp used to name the file.
480 """
481 path = os.path.join(root, 'tmp', 'portage', 'logs',
482 f'{pkg_info.category}:{pkg_info.package}:' \
483 f'{timestamp.strftime("%Y%m%d-%H%M%S")}.log')
484 osutils.WriteFile(path, f'Test log file for package {pkg_info.category}/'
485 f'{pkg_info.package} written to {path}')
486 return path
487
Alex Klein231d2da2019-07-22 16:44:45 -0600488 def testValidateOnly(self):
489 """Sanity check that a validate only call does not execute any logic."""
490 patch = self.PatchObject(sysroot_service, 'BuildPackages')
491
492 in_proto = self._InputProto(build_target=self.build_target,
493 sysroot_path=self.sysroot)
494 sysroot_controller.InstallPackages(in_proto, self._OutputProto(),
495 self.validate_only_config)
496 patch.assert_not_called()
497
Alex Klein076841b2019-08-29 15:19:39 -0600498 def testMockCall(self):
499 """Sanity check that a mock call does not execute any logic."""
500 patch = self.PatchObject(sysroot_service, 'BuildPackages')
501 request = self._InputProto()
502 response = self._OutputProto()
503
504 rc = sysroot_controller.InstallPackages(request, response,
505 self.mock_call_config)
506
507 patch.assert_not_called()
508 self.assertEqual(controller.RETURN_CODE_SUCCESS, rc)
509
510 def testMockError(self):
511 """Sanity check that a mock error does not execute any logic."""
512 patch = self.PatchObject(sysroot_service, 'BuildPackages')
513 request = self._InputProto()
514 response = self._OutputProto()
515
516 rc = sysroot_controller.InstallPackages(request, response,
517 self.mock_error_config)
518
519 patch.assert_not_called()
520 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
521 self.assertTrue(response.failed_packages)
522
Alex Kleind4e1e422019-03-18 16:00:41 -0600523 def testArgumentValidationAllMissing(self):
524 """Test missing all arguments."""
525 out_proto = self._OutputProto()
526 in_proto = self._InputProto()
527 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600528 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600529
530 def testArgumentValidationNoSysroot(self):
531 """Test missing sysroot path."""
532 out_proto = self._OutputProto()
533 in_proto = self._InputProto(build_target=self.build_target)
534 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600535 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600536
537 def testArgumentValidationNoBuildTarget(self):
538 """Test missing build target name."""
539 out_proto = self._OutputProto()
540 in_proto = self._InputProto(sysroot_path=self.sysroot)
541 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600542 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600543
544 def testArgumentValidationInvalidSysroot(self):
545 """Test sysroot that hasn't had the toolchain installed."""
546 out_proto = self._OutputProto()
547 in_proto = self._InputProto(build_target=self.build_target,
548 sysroot_path=self.sysroot)
549 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
550 return_value=False)
551 with self.assertRaises(cros_build_lib.DieSystemExit):
Alex Klein231d2da2019-07-22 16:44:45 -0600552 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600553
Alex Kleinca572ee2020-09-03 10:47:14 -0600554 def testArgumentValidationInvalidPackage(self):
555 out_proto = self._OutputProto()
556 in_proto = self._InputProto(build_target=self.build_target,
557 sysroot_path=self.sysroot,
558 packages=['package-1.0.0-r2'])
559 with self.assertRaises(cros_build_lib.DieSystemExit):
560 sysroot_controller.InstallPackages(in_proto, out_proto, self.api_config)
561
Alex Kleind4e1e422019-03-18 16:00:41 -0600562 def testSuccessOutputHandling(self):
563 """Test successful call output handling."""
564 # Prevent argument validation error.
565 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
566 return_value=True)
567
568 in_proto = self._InputProto(build_target=self.build_target,
569 sysroot_path=self.sysroot)
570 out_proto = self._OutputProto()
571 self.PatchObject(sysroot_service, 'BuildPackages')
572
Alex Klein231d2da2019-07-22 16:44:45 -0600573 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
574 self.api_config)
Alex Kleind4e1e422019-03-18 16:00:41 -0600575 self.assertFalse(rc)
576 self.assertFalse(out_proto.failed_packages)
577
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600578 def testSuccessPackageIndexes(self):
579 """Test successful call with package_indexes."""
580 # Prevent argument validation error.
581 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
582 return_value=True)
583 package_indexes = [
584 common_pb2.PackageIndexInfo(
585 snapshot_sha='SHA', snapshot_number=5,
586 build_target=common_pb2.BuildTarget(name='board'),
587 location='LOCATION', profile=common_pb2.Profile(name='profile')),
588 common_pb2.PackageIndexInfo(
589 snapshot_sha='SHA2', snapshot_number=4,
590 build_target=common_pb2.BuildTarget(name='board'),
591 location='LOCATION2', profile=common_pb2.Profile(name='profile'))]
592
593 in_proto = self._InputProto(build_target=self.build_target,
594 sysroot_path=self.sysroot,
595 package_indexes=package_indexes)
596
597 out_proto = self._OutputProto()
598 rc_patch = self.PatchObject(sysroot_service, 'BuildPackagesRunConfig')
599 self.PatchObject(sysroot_service, 'BuildPackages')
600
601 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
602 self.api_config)
603 self.assertFalse(rc)
Alex Kleineb76da72021-03-19 10:43:09 -0600604 rc_patch.assert_called_with(
605 usepkg=True,
606 install_debug_symbols=True,
607 packages=[],
608 package_indexes=[
609 binpkg.PackageIndexInfo.from_protobuf(x) for x in package_indexes
610 ],
611 use_flags=[],
612 use_goma=False,
613 incremental_build=False,
Navil Perez5766d1b2021-05-26 17:38:15 +0000614 setup_board=False,
615 dryrun=False)
LaMont Jonesc0343fa2020-08-12 18:58:31 -0600616
Michael Mortensen798ee192020-01-17 13:04:43 -0700617 def testSuccessWithGomaLogs(self):
618 """Test successful call with goma."""
619 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy',
620 datetime.datetime(2018, 9, 21, 12, 0, 0))
621 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy-subproc',
622 datetime.datetime(2018, 9, 21, 12, 1, 0))
623 self._CreateGomaLogFile(self.goma_dir, 'gomacc',
624 datetime.datetime(2018, 9, 21, 12, 2, 0))
625
626 # Prevent argument validation error.
627 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
628 return_value=True)
629
630 in_proto = self._InputProto(build_target=self.build_target,
631 sysroot_path=self.sysroot,
632 goma_dir=self.goma_dir,
633 goma_log_dir=self.goma_out_dir)
634
635 out_proto = self._OutputProto()
636 self.PatchObject(sysroot_service, 'BuildPackages')
637
638 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
639 self.api_config)
640 self.assertFalse(rc)
641 self.assertFalse(out_proto.failed_packages)
642 self.assertCountEqual(out_proto.goma_artifacts.log_files, [
643 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
644 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
645 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
646
647 def testSuccessWithGomaLogsAndStatsCounterzFiles(self):
648 """Test successful call with goma including stats and counterz files."""
649 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy',
650 datetime.datetime(2018, 9, 21, 12, 0, 0))
651 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy-subproc',
652 datetime.datetime(2018, 9, 21, 12, 1, 0))
653 self._CreateGomaLogFile(self.goma_dir, 'gomacc',
654 datetime.datetime(2018, 9, 21, 12, 2, 0))
655 # Create stats and counterz files.
656 osutils.WriteFile(os.path.join(self.goma_dir, 'stats.binaryproto'),
657 'File: stats.binaryproto')
658 osutils.WriteFile(os.path.join(self.goma_dir, 'counterz.binaryproto'),
659 'File: counterz.binaryproto')
660
661 # Prevent argument validation error.
662 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
663 return_value=True)
664
665 in_proto = self._InputProto(build_target=self.build_target,
666 sysroot_path=self.sysroot,
667 goma_dir=self.goma_dir,
668 goma_log_dir=self.goma_out_dir,
669 goma_stats_file='stats.binaryproto',
670 goma_counterz_file='counterz.binaryproto')
671
672 out_proto = self._OutputProto()
673 self.PatchObject(sysroot_service, 'BuildPackages')
674
675 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
676 self.api_config)
677 self.assertFalse(rc)
678 self.assertFalse(out_proto.failed_packages)
679 self.assertCountEqual(out_proto.goma_artifacts.log_files, [
680 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
681 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
682 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
683 # Verify that the output dir has 5 files -- since there should be 3 log
684 # files, the stats file, and the counterz file.
685 output_files = os.listdir(self.goma_out_dir)
686 self.assertCountEqual(output_files, [
687 'stats.binaryproto',
688 'counterz.binaryproto',
689 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
690 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
691 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
Michael Mortensen1c7439c2020-01-24 14:43:19 -0700692 self.assertEqual(out_proto.goma_artifacts.counterz_file,
693 'counterz.binaryproto')
694 self.assertEqual(out_proto.goma_artifacts.stats_file,
695 'stats.binaryproto')
Michael Mortensen798ee192020-01-17 13:04:43 -0700696
697 def testFailureMissingGomaStatsCounterzFiles(self):
698 """Test successful call with goma including stats and counterz files."""
699 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy',
700 datetime.datetime(2018, 9, 21, 12, 0, 0))
701 self._CreateGomaLogFile(self.goma_dir, 'compiler_proxy-subproc',
702 datetime.datetime(2018, 9, 21, 12, 1, 0))
703 self._CreateGomaLogFile(self.goma_dir, 'gomacc',
704 datetime.datetime(2018, 9, 21, 12, 2, 0))
705 # Note that stats and counterz files are not created, but are specified in
706 # the proto below.
707
708 # Prevent argument validation error.
709 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
710 return_value=True)
711
712 in_proto = self._InputProto(build_target=self.build_target,
713 sysroot_path=self.sysroot,
714 goma_dir=self.goma_dir,
715 goma_log_dir=self.goma_out_dir,
716 goma_stats_file='stats.binaryproto',
717 goma_counterz_file='counterz.binaryproto')
718
719 out_proto = self._OutputProto()
720 self.PatchObject(sysroot_service, 'BuildPackages')
721
Michael Mortensen1d6d5b02020-01-22 07:33:50 -0700722 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
723 self.api_config)
724 self.assertFalse(rc)
725 self.assertFalse(out_proto.failed_packages)
726 self.assertCountEqual(out_proto.goma_artifacts.log_files, [
727 'compiler_proxy-subproc.host.log.INFO.20180921-120100.000000.gz',
728 'compiler_proxy.host.log.INFO.20180921-120000.000000.gz',
729 'gomacc.host.log.INFO.20180921-120200.000000.tar.gz'])
730 self.assertFalse(out_proto.goma_artifacts.counterz_file)
731 self.assertFalse(out_proto.goma_artifacts.stats_file)
Michael Mortensen798ee192020-01-17 13:04:43 -0700732
Alex Kleind4e1e422019-03-18 16:00:41 -0600733 def testFailureOutputHandling(self):
734 """Test failed package handling."""
735 # Prevent argument validation error.
736 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
737 return_value=True)
738
739 in_proto = self._InputProto(build_target=self.build_target,
740 sysroot_path=self.sysroot)
741 out_proto = self._OutputProto()
742
743 # Failed package info and expected list for verification.
744 err_pkgs = ['cat/pkg', 'cat2/pkg2']
Lizzy Presland7e23a612021-11-09 21:49:42 +0000745 err_cpvs = [package_info.parse(cpv) for cpv in err_pkgs]
Alex Kleind4e1e422019-03-18 16:00:41 -0600746 expected = [('cat', 'pkg'), ('cat2', 'pkg2')]
747
Lizzy Presland7e23a612021-11-09 21:49:42 +0000748 new_logs = {}
749 for i, pkg in enumerate(err_pkgs):
750 self._CreatePortageLogFile(self.sysroot, err_cpvs[i],
751 datetime.datetime(2021, 6, 9, 13, 37, 0))
752 new_logs[pkg] = self._CreatePortageLogFile(self.sysroot, err_cpvs[i],
753 datetime.datetime(2021, 6, 9,
754 16, 20, 0)
755 )
Alex Kleind4e1e422019-03-18 16:00:41 -0600756 # Force error to be raised with the packages.
757 error = sysroot_lib.PackageInstallError('Error',
758 cros_build_lib.CommandResult(),
759 packages=err_cpvs)
760 self.PatchObject(sysroot_service, 'BuildPackages', side_effect=error)
761
Alex Klein231d2da2019-07-22 16:44:45 -0600762 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
763 self.api_config)
Alex Klein2557b4f2019-07-11 14:34:00 -0600764 # This needs to return 2 to indicate the available error response.
765 self.assertEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE, rc)
Lizzy Presland7e23a612021-11-09 21:49:42 +0000766 for data in out_proto.failed_package_data:
767 package = controller_util.deserialize_package_info(data.name)
768 cat_pkg = (data.name.category, data.name.package_name)
769 self.assertIn(cat_pkg, expected)
770 self.assertEqual(data.log_path.path, new_logs[package.atom])
771
772 # TODO(b/206514844): remove when field is deleted
Alex Kleind4e1e422019-03-18 16:00:41 -0600773 for package in out_proto.failed_packages:
774 cat_pkg = (package.category, package.package_name)
775 self.assertIn(cat_pkg, expected)
Alex Klein2557b4f2019-07-11 14:34:00 -0600776
777 def testNoPackageFailureOutputHandling(self):
778 """Test failure handling without packages to report."""
779 # Prevent argument validation error.
780 self.PatchObject(sysroot_lib.Sysroot, 'IsToolchainInstalled',
781 return_value=True)
782
783 in_proto = self._InputProto(build_target=self.build_target,
784 sysroot_path=self.sysroot)
785 out_proto = self._OutputProto()
786
787 # Force error to be raised with no packages.
788 error = sysroot_lib.PackageInstallError('Error',
789 cros_build_lib.CommandResult(),
790 packages=[])
791 self.PatchObject(sysroot_service, 'BuildPackages', side_effect=error)
792
Alex Klein231d2da2019-07-22 16:44:45 -0600793 rc = sysroot_controller.InstallPackages(in_proto, out_proto,
794 self.api_config)
Alex Klein2557b4f2019-07-11 14:34:00 -0600795 # All we really care about is it's not 0 or 2 (response available), so
796 # test for that rather than a specific return code.
797 self.assertTrue(rc)
798 self.assertNotEqual(controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE,
799 rc)