Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 1 | # 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 build_test_suites.py""" |
| 16 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame^] | 17 | import argparse |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 18 | from importlib import resources |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame^] | 19 | import json |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 20 | import multiprocessing |
| 21 | import os |
| 22 | import pathlib |
| 23 | import shutil |
| 24 | import signal |
| 25 | import stat |
| 26 | import subprocess |
| 27 | import sys |
| 28 | import tempfile |
| 29 | import textwrap |
| 30 | import time |
| 31 | from typing import Callable |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame^] | 32 | import unittest |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 33 | from unittest import mock |
| 34 | import build_test_suites |
| 35 | import ci_test_lib |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame^] | 36 | import optimized_targets |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 37 | from pyfakefs import fake_filesystem_unittest |
| 38 | |
| 39 | |
| 40 | class BuildTestSuitesTest(fake_filesystem_unittest.TestCase): |
| 41 | |
| 42 | def setUp(self): |
| 43 | self.setUpPyfakefs() |
| 44 | |
| 45 | os_environ_patcher = mock.patch.dict('os.environ', {}) |
| 46 | self.addCleanup(os_environ_patcher.stop) |
| 47 | self.mock_os_environ = os_environ_patcher.start() |
| 48 | |
| 49 | subprocess_run_patcher = mock.patch('subprocess.run') |
| 50 | self.addCleanup(subprocess_run_patcher.stop) |
| 51 | self.mock_subprocess_run = subprocess_run_patcher.start() |
| 52 | |
| 53 | self._setup_working_build_env() |
| 54 | |
| 55 | def test_missing_target_release_env_var_raises(self): |
| 56 | del os.environ['TARGET_RELEASE'] |
| 57 | |
| 58 | with self.assert_raises_word(build_test_suites.Error, 'TARGET_RELEASE'): |
| 59 | build_test_suites.main([]) |
| 60 | |
| 61 | def test_missing_target_product_env_var_raises(self): |
| 62 | del os.environ['TARGET_PRODUCT'] |
| 63 | |
| 64 | with self.assert_raises_word(build_test_suites.Error, 'TARGET_PRODUCT'): |
| 65 | build_test_suites.main([]) |
| 66 | |
| 67 | def test_missing_top_env_var_raises(self): |
| 68 | del os.environ['TOP'] |
| 69 | |
| 70 | with self.assert_raises_word(build_test_suites.Error, 'TOP'): |
| 71 | build_test_suites.main([]) |
| 72 | |
| 73 | def test_invalid_arg_raises(self): |
| 74 | invalid_args = ['--invalid_arg'] |
| 75 | |
| 76 | with self.assertRaisesRegex(SystemExit, '2'): |
| 77 | build_test_suites.main(invalid_args) |
| 78 | |
| 79 | def test_build_failure_returns(self): |
| 80 | self.mock_subprocess_run.side_effect = subprocess.CalledProcessError( |
| 81 | 42, None |
| 82 | ) |
| 83 | |
| 84 | with self.assertRaisesRegex(SystemExit, '42'): |
| 85 | build_test_suites.main([]) |
| 86 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame^] | 87 | def test_incorrectly_formatted_build_context_raises(self): |
| 88 | build_context = self.fake_top.joinpath('build_context') |
| 89 | build_context.touch() |
| 90 | os.environ['BUILD_CONTEXT'] = str(build_context) |
| 91 | |
| 92 | with self.assert_raises_word(build_test_suites.Error, 'JSON'): |
| 93 | build_test_suites.main([]) |
| 94 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 95 | def test_build_success_returns(self): |
| 96 | with self.assertRaisesRegex(SystemExit, '0'): |
| 97 | build_test_suites.main([]) |
| 98 | |
| 99 | def assert_raises_word(self, cls, word): |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame^] | 100 | return self.assertRaisesRegex(cls, rf'\b{word}\b') |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 101 | |
| 102 | def _setup_working_build_env(self): |
| 103 | self.fake_top = pathlib.Path('/fake/top') |
| 104 | self.fake_top.mkdir(parents=True) |
| 105 | |
| 106 | self.soong_ui_dir = self.fake_top.joinpath('build/soong') |
| 107 | self.soong_ui_dir.mkdir(parents=True, exist_ok=True) |
| 108 | |
| 109 | self.soong_ui = self.soong_ui_dir.joinpath('soong_ui.bash') |
| 110 | self.soong_ui.touch() |
| 111 | |
| 112 | self.mock_os_environ.update({ |
| 113 | 'TARGET_RELEASE': 'release', |
| 114 | 'TARGET_PRODUCT': 'product', |
| 115 | 'TOP': str(self.fake_top), |
| 116 | }) |
| 117 | |
| 118 | self.mock_subprocess_run.return_value = 0 |
| 119 | |
| 120 | |
| 121 | class RunCommandIntegrationTest(ci_test_lib.TestCase): |
| 122 | |
| 123 | def setUp(self): |
| 124 | self.temp_dir = ci_test_lib.TestTemporaryDirectory.create(self) |
| 125 | |
| 126 | # Copy the Python executable from 'non-code' resources and make it |
| 127 | # executable for use by tests that launch a subprocess. Note that we don't |
| 128 | # use Python's native `sys.executable` property since that is not set when |
| 129 | # running via the embedded launcher. |
| 130 | base_name = 'py3-cmd' |
| 131 | dest_file = self.temp_dir.joinpath(base_name) |
| 132 | with resources.as_file( |
| 133 | resources.files('testdata').joinpath(base_name) |
| 134 | ) as p: |
| 135 | shutil.copy(p, dest_file) |
| 136 | dest_file.chmod(dest_file.stat().st_mode | stat.S_IEXEC) |
| 137 | self.python_executable = dest_file |
| 138 | |
| 139 | self._managed_processes = [] |
| 140 | |
| 141 | def tearDown(self): |
| 142 | self._terminate_managed_processes() |
| 143 | |
| 144 | def test_raises_on_nonzero_exit(self): |
| 145 | with self.assertRaises(Exception): |
| 146 | build_test_suites.run_command([ |
| 147 | self.python_executable, |
| 148 | '-c', |
| 149 | textwrap.dedent(f"""\ |
| 150 | import sys |
| 151 | sys.exit(1) |
| 152 | """), |
| 153 | ]) |
| 154 | |
| 155 | def test_streams_stdout(self): |
| 156 | |
| 157 | def run_slow_command(stdout_file, marker): |
| 158 | with open(stdout_file, 'w') as f: |
| 159 | build_test_suites.run_command( |
| 160 | [ |
| 161 | self.python_executable, |
| 162 | '-c', |
| 163 | textwrap.dedent(f"""\ |
| 164 | import time |
| 165 | |
| 166 | print('{marker}', end='', flush=True) |
| 167 | |
| 168 | # Keep process alive until we check stdout. |
| 169 | time.sleep(10) |
| 170 | """), |
| 171 | ], |
| 172 | stdout=f, |
| 173 | ) |
| 174 | |
| 175 | marker = 'Spinach' |
| 176 | stdout_file = self.temp_dir.joinpath('stdout.txt') |
| 177 | |
| 178 | p = self.start_process(target=run_slow_command, args=[stdout_file, marker]) |
| 179 | |
| 180 | self.assert_file_eventually_contains(stdout_file, marker) |
| 181 | |
| 182 | def test_propagates_interruptions(self): |
| 183 | |
| 184 | def run(pid_file): |
| 185 | build_test_suites.run_command([ |
| 186 | self.python_executable, |
| 187 | '-c', |
| 188 | textwrap.dedent(f"""\ |
| 189 | import os |
| 190 | import pathlib |
| 191 | import time |
| 192 | |
| 193 | pathlib.Path('{pid_file}').write_text(str(os.getpid())) |
| 194 | |
| 195 | # Keep the process alive for us to explicitly interrupt it. |
| 196 | time.sleep(10) |
| 197 | """), |
| 198 | ]) |
| 199 | |
| 200 | pid_file = self.temp_dir.joinpath('pid.txt') |
| 201 | p = self.start_process(target=run, args=[pid_file]) |
| 202 | subprocess_pid = int(read_eventual_file_contents(pid_file)) |
| 203 | |
| 204 | os.kill(p.pid, signal.SIGINT) |
| 205 | p.join() |
| 206 | |
| 207 | self.assert_process_eventually_dies(p.pid) |
| 208 | self.assert_process_eventually_dies(subprocess_pid) |
| 209 | |
| 210 | def start_process(self, *args, **kwargs) -> multiprocessing.Process: |
| 211 | p = multiprocessing.Process(*args, **kwargs) |
| 212 | self._managed_processes.append(p) |
| 213 | p.start() |
| 214 | return p |
| 215 | |
| 216 | def assert_process_eventually_dies(self, pid: int): |
| 217 | try: |
| 218 | wait_until(lambda: not ci_test_lib.process_alive(pid)) |
| 219 | except TimeoutError as e: |
| 220 | self.fail(f'Process {pid} did not die after a while: {e}') |
| 221 | |
| 222 | def assert_file_eventually_contains(self, file: pathlib.Path, substring: str): |
| 223 | wait_until(lambda: file.is_file() and file.stat().st_size > 0) |
| 224 | self.assertIn(substring, read_file_contents(file)) |
| 225 | |
| 226 | def _terminate_managed_processes(self): |
| 227 | for p in self._managed_processes: |
| 228 | if not p.is_alive(): |
| 229 | continue |
| 230 | |
| 231 | # We terminate the process with `SIGINT` since using `terminate` or |
| 232 | # `SIGKILL` doesn't kill any grandchild processes and we don't have |
| 233 | # `psutil` available to easily query all children. |
| 234 | os.kill(p.pid, signal.SIGINT) |
| 235 | |
| 236 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame^] | 237 | class BuildPlannerTest(unittest.TestCase): |
| 238 | |
| 239 | class TestOptimizedBuildTarget(optimized_targets.OptimizedBuildTarget): |
| 240 | |
| 241 | def __init__(self, output_targets): |
| 242 | self.output_targets = output_targets |
| 243 | |
| 244 | def get_build_targets(self): |
| 245 | return self.output_targets |
| 246 | |
| 247 | def package_outputs(self): |
| 248 | return f'packaging {" ".join(self.output_targets)}' |
| 249 | |
| 250 | def test_build_optimization_off_builds_everything(self): |
| 251 | build_targets = {'target_1', 'target_2'} |
| 252 | build_planner = self.create_build_planner( |
| 253 | build_context=self.create_build_context(optimized_build_enabled=False), |
| 254 | build_targets=build_targets, |
| 255 | ) |
| 256 | |
| 257 | build_plan = build_planner.create_build_plan() |
| 258 | |
| 259 | self.assertSetEqual(build_targets, build_plan.build_targets) |
| 260 | |
| 261 | def test_build_optimization_off_doesnt_package(self): |
| 262 | build_targets = {'target_1', 'target_2'} |
| 263 | build_planner = self.create_build_planner( |
| 264 | build_context=self.create_build_context(optimized_build_enabled=False), |
| 265 | build_targets=build_targets, |
| 266 | ) |
| 267 | |
| 268 | build_plan = build_planner.create_build_plan() |
| 269 | |
| 270 | self.assertEqual(len(build_plan.packaging_functions), 0) |
| 271 | |
| 272 | def test_build_optimization_on_optimizes_target(self): |
| 273 | build_targets = {'target_1', 'target_2'} |
| 274 | build_planner = self.create_build_planner( |
| 275 | build_targets=build_targets, |
| 276 | build_context=self.create_build_context( |
| 277 | enabled_build_features={self.get_target_flag('target_1')} |
| 278 | ), |
| 279 | ) |
| 280 | |
| 281 | build_plan = build_planner.create_build_plan() |
| 282 | |
| 283 | expected_targets = {self.get_optimized_target_name('target_1'), 'target_2'} |
| 284 | self.assertSetEqual(expected_targets, build_plan.build_targets) |
| 285 | |
| 286 | def test_build_optimization_on_packages_target(self): |
| 287 | build_targets = {'target_1', 'target_2'} |
| 288 | build_planner = self.create_build_planner( |
| 289 | build_targets=build_targets, |
| 290 | build_context=self.create_build_context( |
| 291 | enabled_build_features={self.get_target_flag('target_1')} |
| 292 | ), |
| 293 | ) |
| 294 | |
| 295 | build_plan = build_planner.create_build_plan() |
| 296 | |
| 297 | optimized_target_name = self.get_optimized_target_name('target_1') |
| 298 | self.assertIn( |
| 299 | f'packaging {optimized_target_name}', |
| 300 | self.run_packaging_functions(build_plan), |
| 301 | ) |
| 302 | |
| 303 | def test_individual_build_optimization_off_doesnt_optimize(self): |
| 304 | build_targets = {'target_1', 'target_2'} |
| 305 | build_planner = self.create_build_planner( |
| 306 | build_targets=build_targets, |
| 307 | ) |
| 308 | |
| 309 | build_plan = build_planner.create_build_plan() |
| 310 | |
| 311 | self.assertSetEqual(build_targets, build_plan.build_targets) |
| 312 | |
| 313 | def test_individual_build_optimization_off_doesnt_package(self): |
| 314 | build_targets = {'target_1', 'target_2'} |
| 315 | build_planner = self.create_build_planner( |
| 316 | build_targets=build_targets, |
| 317 | ) |
| 318 | |
| 319 | build_plan = build_planner.create_build_plan() |
| 320 | |
| 321 | expected_packaging_function_outputs = {None, None} |
| 322 | self.assertSetEqual( |
| 323 | expected_packaging_function_outputs, |
| 324 | self.run_packaging_functions(build_plan), |
| 325 | ) |
| 326 | |
| 327 | def create_build_planner( |
| 328 | self, |
| 329 | build_targets: set[str], |
| 330 | build_context: dict[str, any] = None, |
| 331 | args: argparse.Namespace = None, |
| 332 | target_optimizations: dict[ |
| 333 | str, optimized_targets.OptimizedBuildTarget |
| 334 | ] = None, |
| 335 | ) -> build_test_suites.BuildPlanner: |
| 336 | if not build_context: |
| 337 | build_context = self.create_build_context() |
| 338 | if not args: |
| 339 | args = self.create_args(extra_build_targets=build_targets) |
| 340 | if not target_optimizations: |
| 341 | target_optimizations = self.create_target_optimizations( |
| 342 | build_context, build_targets |
| 343 | ) |
| 344 | return build_test_suites.BuildPlanner( |
| 345 | build_context, args, target_optimizations |
| 346 | ) |
| 347 | |
| 348 | def create_build_context( |
| 349 | self, |
| 350 | optimized_build_enabled: bool = True, |
| 351 | enabled_build_features: set[str] = set(), |
| 352 | test_context: dict[str, any] = {}, |
| 353 | ) -> dict[str, any]: |
| 354 | build_context = {} |
| 355 | build_context['enabled_build_features'] = enabled_build_features |
| 356 | if optimized_build_enabled: |
| 357 | build_context['enabled_build_features'].add('optimized_build') |
| 358 | build_context['test_context'] = test_context |
| 359 | return build_context |
| 360 | |
| 361 | def create_args( |
| 362 | self, extra_build_targets: set[str] = set() |
| 363 | ) -> argparse.Namespace: |
| 364 | parser = argparse.ArgumentParser() |
| 365 | parser.add_argument('extra_targets', nargs='*') |
| 366 | return parser.parse_args(extra_build_targets) |
| 367 | |
| 368 | def create_target_optimizations( |
| 369 | self, build_context: dict[str, any], build_targets: set[str] |
| 370 | ): |
| 371 | target_optimizations = dict() |
| 372 | for target in build_targets: |
| 373 | target_optimizations[target] = ( |
| 374 | lambda target, build_context, args: optimized_targets.get_target_optimizer( |
| 375 | target, |
| 376 | self.get_target_flag(target), |
| 377 | build_context, |
| 378 | self.TestOptimizedBuildTarget( |
| 379 | {self.get_optimized_target_name(target)} |
| 380 | ), |
| 381 | ) |
| 382 | ) |
| 383 | |
| 384 | return target_optimizations |
| 385 | |
| 386 | def get_target_flag(self, target: str): |
| 387 | return f'{target}_enabled' |
| 388 | |
| 389 | def get_optimized_target_name(self, target: str): |
| 390 | return f'{target}_optimized' |
| 391 | |
| 392 | def run_packaging_functions( |
| 393 | self, build_plan: build_test_suites.BuildPlan |
| 394 | ) -> set[str]: |
| 395 | output = set() |
| 396 | for packaging_function in build_plan.packaging_functions: |
| 397 | output.add(packaging_function()) |
| 398 | |
| 399 | return output |
| 400 | |
| 401 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 402 | def wait_until( |
| 403 | condition_function: Callable[[], bool], |
| 404 | timeout_secs: float = 3.0, |
| 405 | polling_interval_secs: float = 0.1, |
| 406 | ): |
| 407 | """Waits until a condition function returns True.""" |
| 408 | |
| 409 | start_time_secs = time.time() |
| 410 | |
| 411 | while not condition_function(): |
| 412 | if time.time() - start_time_secs > timeout_secs: |
| 413 | raise TimeoutError( |
| 414 | f'Condition not met within timeout: {timeout_secs} seconds' |
| 415 | ) |
| 416 | |
| 417 | time.sleep(polling_interval_secs) |
| 418 | |
| 419 | |
| 420 | def read_file_contents(file: pathlib.Path) -> str: |
| 421 | with open(file, 'r') as f: |
| 422 | return f.read() |
| 423 | |
| 424 | |
| 425 | def read_eventual_file_contents(file: pathlib.Path) -> str: |
| 426 | wait_until(lambda: file.is_file() and file.stat().st_size > 0) |
| 427 | return read_file_contents(file) |
| 428 | |
| 429 | |
| 430 | if __name__ == '__main__': |
| 431 | ci_test_lib.main() |