blob: 762b62e66414faebf20beb98c56b7745ea6341c3 [file] [log] [blame]
Luca Farsib9c54642024-08-13 17:16:33 -07001# Copyright 2024, The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Tests for optimized_targets.py"""
16
17import json
18import logging
19import os
20import pathlib
21import re
Luca Farsi64598e82024-08-28 13:39:25 -070022import subprocess
23import textwrap
Luca Farsib9c54642024-08-13 17:16:33 -070024import unittest
25from unittest import mock
Luca Farsib9c54642024-08-13 17:16:33 -070026from build_context import BuildContext
Luca Farsi64598e82024-08-28 13:39:25 -070027import optimized_targets
Luca Farsib9c54642024-08-13 17:16:33 -070028from pyfakefs import fake_filesystem_unittest
29
30
31class GeneralTestsOptimizerTest(fake_filesystem_unittest.TestCase):
32
33 def setUp(self):
34 self.setUpPyfakefs()
35
36 os_environ_patcher = mock.patch.dict('os.environ', {})
37 self.addCleanup(os_environ_patcher.stop)
38 self.mock_os_environ = os_environ_patcher.start()
39
40 self._setup_working_build_env()
41 self._write_change_info_file()
42 test_mapping_dir = pathlib.Path('/project/path/file/path')
43 test_mapping_dir.mkdir(parents=True)
44 self._write_test_mapping_file()
45
46 def _setup_working_build_env(self):
47 self.change_info_file = pathlib.Path('/tmp/change_info')
Luca Farsi64598e82024-08-28 13:39:25 -070048 self._write_soong_ui_file()
49 self._host_out_testcases = pathlib.Path('/tmp/top/host_out_testcases')
50 self._host_out_testcases.mkdir(parents=True)
51 self._target_out_testcases = pathlib.Path('/tmp/top/target_out_testcases')
52 self._target_out_testcases.mkdir(parents=True)
53 self._product_out = pathlib.Path('/tmp/top/product_out')
54 self._product_out.mkdir(parents=True)
55 self._soong_host_out = pathlib.Path('/tmp/top/soong_host_out')
56 self._soong_host_out.mkdir(parents=True)
57 self._host_out = pathlib.Path('/tmp/top/host_out')
58 self._host_out.mkdir(parents=True)
59
60 self._dist_dir = pathlib.Path('/tmp/top/out/dist')
61 self._dist_dir.mkdir(parents=True)
Luca Farsib9c54642024-08-13 17:16:33 -070062
63 self.mock_os_environ.update({
64 'CHANGE_INFO': str(self.change_info_file),
Luca Farsi64598e82024-08-28 13:39:25 -070065 'TOP': '/tmp/top',
66 'DIST_DIR': '/tmp/top/out/dist',
Luca Farsib9c54642024-08-13 17:16:33 -070067 })
68
Luca Farsi64598e82024-08-28 13:39:25 -070069 def _write_soong_ui_file(self):
70 soong_path = pathlib.Path('/tmp/top/build/soong')
71 soong_path.mkdir(parents=True)
72 with open(os.path.join(soong_path, 'soong_ui.bash'), 'w') as f:
73 f.write("""
74 #/bin/bash
75 echo HOST_OUT_TESTCASES='/tmp/top/host_out_testcases'
76 echo TARGET_OUT_TESTCASES='/tmp/top/target_out_testcases'
77 echo PRODUCT_OUT='/tmp/top/product_out'
78 echo SOONG_HOST_OUT='/tmp/top/soong_host_out'
79 echo HOST_OUT='/tmp/top/host_out'
80 """)
81 os.chmod(os.path.join(soong_path, 'soong_ui.bash'), 0o666)
82
83 def _write_change_info_file(self):
84 change_info_contents = {
85 'changes': [{
86 'projectPath': '/project/path',
87 'revisions': [{
88 'fileInfos': [{
89 'path': 'file/path/file_name',
90 }],
91 }],
92 }]
93 }
94
95 with open(self.change_info_file, 'w') as f:
96 json.dump(change_info_contents, f)
97
98 def _write_test_mapping_file(self):
99 test_mapping_contents = {
100 'test-mapping-group': [
101 {
102 'name': 'test_mapping_module',
103 },
104 ],
105 }
106
107 with open('/project/path/file/path/TEST_MAPPING', 'w') as f:
108 json.dump(test_mapping_contents, f)
109
Luca Farsib9c54642024-08-13 17:16:33 -0700110 def test_general_tests_optimized(self):
111 optimizer = self._create_general_tests_optimizer()
112
113 build_targets = optimizer.get_build_targets()
114
115 expected_build_targets = set(
116 optimized_targets.GeneralTestsOptimizer._REQUIRED_MODULES
117 )
118 expected_build_targets.add('test_mapping_module')
119
120 self.assertSetEqual(build_targets, expected_build_targets)
121
122 def test_no_change_info_no_optimization(self):
123 del os.environ['CHANGE_INFO']
124
125 optimizer = self._create_general_tests_optimizer()
126
127 build_targets = optimizer.get_build_targets()
128
129 self.assertSetEqual(build_targets, {'general-tests'})
130
131 def test_mapping_groups_unused_module_not_built(self):
132 test_context = self._create_test_context()
133 test_context['testInfos'][0]['extraOptions'] = [
134 {
135 'key': 'additional-files-filter',
136 'values': ['general-tests.zip'],
137 },
138 {
139 'key': 'test-mapping-test-group',
140 'values': ['unused-test-mapping-group'],
141 },
142 ]
143 optimizer = self._create_general_tests_optimizer(
144 build_context=self._create_build_context(test_context=test_context)
145 )
146
147 build_targets = optimizer.get_build_targets()
148
149 expected_build_targets = set(
150 optimized_targets.GeneralTestsOptimizer._REQUIRED_MODULES
151 )
152 self.assertSetEqual(build_targets, expected_build_targets)
153
154 def test_general_tests_used_by_non_test_mapping_test_no_optimization(self):
155 test_context = self._create_test_context()
156 test_context['testInfos'][0]['extraOptions'] = [{
157 'key': 'additional-files-filter',
158 'values': ['general-tests.zip'],
159 }]
160 optimizer = self._create_general_tests_optimizer(
161 build_context=self._create_build_context(test_context=test_context)
162 )
163
164 build_targets = optimizer.get_build_targets()
165
166 self.assertSetEqual(build_targets, {'general-tests'})
167
168 def test_malformed_change_info_raises(self):
169 with open(self.change_info_file, 'w') as f:
170 f.write('not change info')
171
172 optimizer = self._create_general_tests_optimizer()
173
174 with self.assertRaises(json.decoder.JSONDecodeError):
175 build_targets = optimizer.get_build_targets()
176
177 def test_malformed_test_mapping_raises(self):
178 with open('/project/path/file/path/TEST_MAPPING', 'w') as f:
179 f.write('not test mapping')
180
181 optimizer = self._create_general_tests_optimizer()
182
183 with self.assertRaises(json.decoder.JSONDecodeError):
184 build_targets = optimizer.get_build_targets()
185
Luca Farsi64598e82024-08-28 13:39:25 -0700186 @mock.patch('subprocess.run')
187 def test_packaging_outputs_success(self, subprocess_run):
188 subprocess_run.return_value = self._get_soong_vars_output()
189 optimizer = self._create_general_tests_optimizer()
190 self._set_up_build_outputs(['test_mapping_module'])
Luca Farsib9c54642024-08-13 17:16:33 -0700191
Luca Farsi64598e82024-08-28 13:39:25 -0700192 targets = optimizer.get_build_targets()
193 package_commands = optimizer.get_package_outputs_commands()
Luca Farsib9c54642024-08-13 17:16:33 -0700194
Luca Farsi64598e82024-08-28 13:39:25 -0700195 self._verify_soong_zip_commands(package_commands, ['test_mapping_module'])
Luca Farsib9c54642024-08-13 17:16:33 -0700196
Luca Farsi64598e82024-08-28 13:39:25 -0700197 @mock.patch('subprocess.run')
198 def test_get_soong_dumpvars_fails_raises(self, subprocess_run):
199 subprocess_run.return_value = self._get_soong_vars_output(return_code=-1)
200 optimizer = self._create_general_tests_optimizer()
201 self._set_up_build_outputs(['test_mapping_module'])
Luca Farsib9c54642024-08-13 17:16:33 -0700202
Luca Farsi64598e82024-08-28 13:39:25 -0700203 targets = optimizer.get_build_targets()
204
205 with self.assertRaisesRegex(RuntimeError, 'Soong dumpvars failed!'):
206 package_commands = optimizer.get_package_outputs_commands()
207
208 @mock.patch('subprocess.run')
209 def test_get_soong_dumpvars_bad_output_raises(self, subprocess_run):
210 subprocess_run.return_value = self._get_soong_vars_output(
211 stdout='This output is bad'
212 )
213 optimizer = self._create_general_tests_optimizer()
214 self._set_up_build_outputs(['test_mapping_module'])
215
216 targets = optimizer.get_build_targets()
217
218 with self.assertRaisesRegex(
219 RuntimeError, 'Error parsing soong dumpvars output'
220 ):
221 package_commands = optimizer.get_package_outputs_commands()
222
223 @mock.patch('subprocess.run')
224 def test_no_build_outputs_packaging_fails(self, subprocess_run):
225 subprocess_run.return_value = self._get_soong_vars_output()
226 optimizer = self._create_general_tests_optimizer()
227
228 targets = optimizer.get_build_targets()
229
230 with self.assertRaisesRegex(
231 RuntimeError, 'No items specified to be added to zip'
232 ):
233 package_commands = optimizer.get_package_outputs_commands()
234
235 def _create_general_tests_optimizer(self, build_context: BuildContext = None):
Luca Farsib9c54642024-08-13 17:16:33 -0700236 if not build_context:
237 build_context = self._create_build_context()
238 return optimized_targets.GeneralTestsOptimizer(
239 'general-tests', build_context, None
240 )
241
242 def _create_build_context(
243 self,
244 general_tests_optimized: bool = True,
245 test_context: dict[str, any] = None,
246 ) -> BuildContext:
247 if not test_context:
248 test_context = self._create_test_context()
249 build_context_dict = {}
250 build_context_dict['enabledBuildFeatures'] = [{'name': 'optimized_build'}]
251 if general_tests_optimized:
Luca Farsi64598e82024-08-28 13:39:25 -0700252 build_context_dict['enabledBuildFeatures'].append(
253 {'name': 'general_tests_optimized'}
254 )
Luca Farsib9c54642024-08-13 17:16:33 -0700255 build_context_dict['testContext'] = test_context
256 return BuildContext(build_context_dict)
257
258 def _create_test_context(self):
259 return {
260 'testInfos': [
261 {
262 'name': 'atp_test',
263 'target': 'test_target',
264 'branch': 'branch',
265 'extraOptions': [
266 {
267 'key': 'additional-files-filter',
268 'values': ['general-tests.zip'],
269 },
270 {
271 'key': 'test-mapping-test-group',
272 'values': ['test-mapping-group'],
273 },
274 ],
275 'command': '/tf/command',
276 'extraBuildTargets': [
277 'extra_build_target',
278 ],
279 },
280 ],
281 }
282
Luca Farsi64598e82024-08-28 13:39:25 -0700283 def _get_soong_vars_output(
284 self, return_code: int = 0, stdout: str = ''
285 ) -> subprocess.CompletedProcess:
286 return_value = subprocess.CompletedProcess(args=[], returncode=return_code)
287 if not stdout:
288 stdout = textwrap.dedent(f"""\
289 HOST_OUT_TESTCASES='{self._host_out_testcases}'
290 TARGET_OUT_TESTCASES='{self._target_out_testcases}'
291 PRODUCT_OUT='{self._product_out}'
292 SOONG_HOST_OUT='{self._soong_host_out}'
293 HOST_OUT='{self._host_out}'""")
294
295 return_value.stdout = stdout
296 return return_value
297
298 def _set_up_build_outputs(self, targets: list[str]):
299 for target in targets:
300 host_dir = self._host_out_testcases / target
301 host_dir.mkdir()
302 (host_dir / f'{target}.config').touch()
303 (host_dir / f'test_file').touch()
304
305 target_dir = self._target_out_testcases / target
306 target_dir.mkdir()
307 (target_dir / f'{target}.config').touch()
308 (target_dir / f'test_file').touch()
309
310 def _verify_soong_zip_commands(self, commands: list[str], targets: list[str]):
311 """Verify the structure of the zip commands.
312
313 Zip commands have to start with the soong_zip binary path, then are followed
314 by a couple of options and the name of the file being zipped. Depending on
315 which zip we are creating look for a few essential items being added in
316 those zips.
317
318 Args:
319 commands: list of command lists
320 targets: list of targets expected to be in general-tests.zip
321 """
322 for command in commands:
323 self.assertEqual(
324 '/tmp/top/host_out/prebuilts/build-tools/linux-x86/bin/soong_zip',
325 command[0],
326 )
327 self.assertEqual('-d', command[1])
328 self.assertEqual('-o', command[2])
329 match (command[3]):
330 case '/tmp/top/out/dist/general-tests_configs.zip':
331 self.assertIn(f'{self._host_out}/host_general-tests_list', command)
332 self.assertIn(
333 f'{self._product_out}/target_general-tests_list', command
334 )
335 return
336 case '/tmp/top/out/dist/general-tests_list.zip':
337 self.assertIn('-f', command)
338 self.assertIn(f'{self._host_out}/general-tests_list', command)
339 return
340 case '/tmp/top/out/dist/general-tests.zip':
341 for target in targets:
342 self.assertIn(f'{self._host_out_testcases}/{target}', command)
343 self.assertIn(f'{self._target_out_testcases}/{target}', command)
344 self.assertIn(
345 f'{self._soong_host_out}/framework/cts-tradefed.jar', command
346 )
347 self.assertIn(
348 f'{self._soong_host_out}/framework/compatibility-host-util.jar',
349 command,
350 )
351 self.assertIn(
352 f'{self._soong_host_out}/framework/vts-tradefed.jar', command
353 )
354 return
355 case _:
356 self.fail(f'malformed command: {command}')
357
Luca Farsib9c54642024-08-13 17:16:33 -0700358
359if __name__ == '__main__':
360 # Setup logging to be silent so unit tests can pass through TF.
361 logging.disable(logging.ERROR)
362 unittest.main()