blob: 18abd8e54f0545b5b2dd4a612b4ec3d98a9c1eed [file] [log] [blame]
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +00001# 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
15import dataclasses
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +000016import glob
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000017from importlib import resources
18import logging
19import os
20from pathlib import Path
21import re
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +000022import shutil
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000023import signal
24import stat
25import subprocess
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +000026import sys
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000027import tempfile
28import textwrap
29import time
30import unittest
31import zipfile
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000032
33EXII_RETURN_CODE = 0
34INTERRUPTED_RETURN_CODE = 130
35
36
37class RunToolWithLoggingTest(unittest.TestCase):
38
39 @classmethod
40 def setUpClass(cls):
41 super().setUpClass()
42 # Configure to print logging to stdout.
43 logging.basicConfig(filename=None, level=logging.DEBUG)
44 console = logging.StreamHandler(sys.stdout)
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +000045 logging.getLogger("").addHandler(console)
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000046
47 def setUp(self):
48 super().setUp()
49 self.working_dir = tempfile.TemporaryDirectory()
50 # Run all the tests from working_dir which is our temp Android build top.
51 os.chdir(self.working_dir.name)
52 # Extract envsetup.zip which contains the envsetup.sh and other dependent
53 # scripts required to set up the build environments.
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +000054 with resources.files("testdata").joinpath("envsetup.zip").open("rb") as p:
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000055 with zipfile.ZipFile(p, "r") as zip_f:
56 zip_f.extractall()
57
58 def tearDown(self):
59 self.working_dir.cleanup()
60 super().tearDown()
61
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000062 def test_does_not_log_when_logger_var_empty(self):
63 test_tool = TestScript.create(self.working_dir)
64
65 self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000066 ANDROID_TOOL_LOGGER=""
67 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
68 """)
69
70 test_tool.assert_called_once_with_args("arg1 arg2")
71
72 def test_does_not_log_with_logger_unset(self):
73 test_tool = TestScript.create(self.working_dir)
74
75 self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000076 unset ANDROID_TOOL_LOGGER
77 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
78 """)
79
80 test_tool.assert_called_once_with_args("arg1 arg2")
81
82 def test_log_success_with_logger_enabled(self):
83 test_tool = TestScript.create(self.working_dir)
84 test_logger = TestScript.create(self.working_dir)
85
86 self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000087 ANDROID_TOOL_LOGGER="{test_logger.executable}"
88 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
89 """)
90
91 test_tool.assert_called_once_with_args("arg1 arg2")
92 expected_logger_args = (
93 "--tool_tag FAKE_TOOL --start_timestamp \d+\.\d+ --end_timestamp"
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +000094 " \d+\.\d+ --tool_args arg1 arg2 --exit_code 0"
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +000095 )
96 test_logger.assert_called_once_with_args(expected_logger_args)
97
98 def test_run_tool_output_is_same_with_and_without_logging(self):
99 test_tool = TestScript.create(self.working_dir, "echo 'tool called'")
100 test_logger = TestScript.create(self.working_dir)
101
102 run_tool_with_logging_stdout, run_tool_with_logging_stderr = (
103 self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000104 ANDROID_TOOL_LOGGER="{test_logger.executable}"
105 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
106 """)
107 )
108
109 run_tool_without_logging_stdout, run_tool_without_logging_stderr = (
110 self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000111 ANDROID_TOOL_LOGGER="{test_logger.executable}"
112 {test_tool.executable} arg1 arg2
113 """)
114 )
115
116 self.assertEqual(
117 run_tool_with_logging_stdout, run_tool_without_logging_stdout
118 )
119 self.assertEqual(
120 run_tool_with_logging_stderr, run_tool_without_logging_stderr
121 )
122
123 def test_logger_output_is_suppressed(self):
124 test_tool = TestScript.create(self.working_dir)
125 test_logger = TestScript.create(self.working_dir, "echo 'logger called'")
126
127 run_tool_with_logging_output, _ = self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000128 ANDROID_TOOL_LOGGER="{test_logger.executable}"
129 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
130 """)
131
132 self.assertNotIn("logger called", run_tool_with_logging_output)
133
134 def test_logger_error_is_suppressed(self):
135 test_tool = TestScript.create(self.working_dir)
136 test_logger = TestScript.create(
137 self.working_dir, "echo 'logger failed' > /dev/stderr; exit 1"
138 )
139
140 _, err = self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000141 ANDROID_TOOL_LOGGER="{test_logger.executable}"
142 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
143 """)
144
145 self.assertNotIn("logger failed", err)
146
147 def test_log_success_when_tool_interrupted(self):
148 test_tool = TestScript.create(self.working_dir, script_body="sleep 100")
149 test_logger = TestScript.create(self.working_dir)
150
151 process = self._run_script_in_build_env(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000152 ANDROID_TOOL_LOGGER="{test_logger.executable}"
153 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
154 """)
155
156 pgid = os.getpgid(process.pid)
157 # Give sometime for the subprocess to start.
158 time.sleep(1)
159 # Kill the subprocess and any processes created in the same group.
160 os.killpg(pgid, signal.SIGINT)
161
162 returncode, _, _ = self._wait_for_process(process)
163 self.assertEqual(returncode, INTERRUPTED_RETURN_CODE)
164
165 expected_logger_args = (
166 "--tool_tag FAKE_TOOL --start_timestamp \d+\.\d+ --end_timestamp"
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +0000167 " \d+\.\d+ --tool_args arg1 arg2 --exit_code 130"
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000168 )
169 test_logger.assert_called_once_with_args(expected_logger_args)
170
171 def test_logger_can_be_toggled_on(self):
172 test_tool = TestScript.create(self.working_dir)
173 test_logger = TestScript.create(self.working_dir)
174
175 self._run_script_and_wait(f"""
Zhuoyao Zhangef1c03f2024-05-07 22:18:37 +0000176 ANDROID_TOOL_LOGGER=""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000177 ANDROID_TOOL_LOGGER="{test_logger.executable}"
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000178 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
179 """)
180
181 test_logger.assert_called_with_times(1)
182
183 def test_logger_can_be_toggled_off(self):
184 test_tool = TestScript.create(self.working_dir)
185 test_logger = TestScript.create(self.working_dir)
186
187 self._run_script_and_wait(f"""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000188 ANDROID_TOOL_LOGGER="{test_logger.executable}"
Zhuoyao Zhangef1c03f2024-05-07 22:18:37 +0000189 ANDROID_TOOL_LOGGER=""
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000190 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
191 """)
192
193 test_logger.assert_not_called()
194
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +0000195 def test_integration_tool_event_logger_dry_run(self):
196 test_tool = TestScript.create(self.working_dir)
197 logger_path = self._import_logger()
198
199 self._run_script_and_wait(f"""
200 TMPDIR="{self.working_dir.name}"
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +0000201 ANDROID_TOOL_LOGGER="{logger_path}"
202 ANDROID_TOOL_LOGGER_EXTRA_ARGS="--dry_run"
203 run_tool_with_logging "FAKE_TOOL" {test_tool.executable} arg1 arg2
204 """)
205
206 self._assert_logger_dry_run()
207
208 def _import_logger(self) -> Path:
209 logger = "tool_event_logger"
210 logger_path = Path(self.working_dir.name).joinpath(logger)
211 with resources.as_file(resources.files("testdata").joinpath(logger)) as p:
212 shutil.copy(p, logger_path)
213 Path.chmod(logger_path, 0o755)
214 return logger_path
215
216 def _assert_logger_dry_run(self):
217 log_files = glob.glob(self.working_dir.name + "/tool_event_logger_*/*.log")
218 self.assertEqual(len(log_files), 1)
219
220 with open(log_files[0], "r") as f:
221 lines = f.readlines()
222 self.assertEqual(len(lines), 1)
223 self.assertIn("dry run", lines[0])
224
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000225 def _create_build_env_script(self) -> str:
226 return f"""
227 source {Path(self.working_dir.name).joinpath("build/make/envsetup.sh")}
228 """
229
230 def _run_script_and_wait(self, test_script: str) -> tuple[str, str]:
231 process = self._run_script_in_build_env(test_script)
232 returncode, out, err = self._wait_for_process(process)
233 logging.debug("script stdout: %s", out)
234 logging.debug("script stderr: %s", err)
235 self.assertEqual(returncode, EXII_RETURN_CODE)
236 return out, err
237
238 def _run_script_in_build_env(self, test_script: str) -> subprocess.Popen:
239 setup_build_env_script = self._create_build_env_script()
240 return subprocess.Popen(
241 setup_build_env_script + test_script,
242 shell=True,
243 stdout=subprocess.PIPE,
244 stderr=subprocess.PIPE,
245 text=True,
246 start_new_session=True,
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +0000247 executable="/bin/bash",
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000248 )
249
250 def _wait_for_process(
251 self, process: subprocess.Popen
252 ) -> tuple[int, str, str]:
253 pgid = os.getpgid(process.pid)
254 out, err = process.communicate()
255 # Wait for all process in the same group to complete since the logger runs
256 # as a separate detached process.
257 self._wait_for_process_group(pgid)
258 return (process.returncode, out, err)
259
260 def _wait_for_process_group(self, pgid: int, timeout: int = 5):
261 """Waits for all subprocesses within the process group to complete."""
262 start_time = time.time()
263 while True:
264 if time.time() - start_time > timeout:
265 raise TimeoutError(
266 f"Process group did not complete after {timeout} seconds"
267 )
268 for pid in os.listdir("/proc"):
269 if pid.isdigit():
270 try:
271 if os.getpgid(int(pid)) == pgid:
272 time.sleep(0.1)
273 break
274 except (FileNotFoundError, PermissionError, ProcessLookupError):
275 pass
276 else:
277 # All processes have completed.
278 break
279
280
281@dataclasses.dataclass
282class TestScript:
283 executable: Path
284 output_file: Path
285
286 def create(temp_dir: Path, script_body: str = ""):
287 with tempfile.NamedTemporaryFile(dir=temp_dir.name, delete=False) as f:
288 output_file = f.name
289
290 with tempfile.NamedTemporaryFile(dir=temp_dir.name, delete=False) as f:
291 executable = f.name
292 executable_contents = textwrap.dedent(f"""
293 #!/bin/bash
294
295 echo "${{@}}" >> {output_file}
296 {script_body}
297 """)
298 f.write(executable_contents.encode("utf-8"))
299
Zhuoyao Zhangdb666bc2024-04-30 00:28:34 +0000300 Path.chmod(f.name, os.stat(f.name).st_mode | stat.S_IEXEC)
Zhuoyao Zhangcc44d2e2024-03-26 22:50:12 +0000301
302 return TestScript(executable, output_file)
303
304 def assert_called_with_times(self, expected_call_times: int):
305 lines = self._read_contents_from_output_file()
306 assert len(lines) == expected_call_times, (
307 f"Expect to call {expected_call_times} times, but actually called"
308 f" {len(lines)} times."
309 )
310
311 def assert_called_with_args(self, expected_args: str):
312 lines = self._read_contents_from_output_file()
313 assert len(lines) > 0
314 assert re.search(expected_args, lines[0]), (
315 f"Expect to call with args {expected_args}, but actually called with"
316 f" args {lines[0]}."
317 )
318
319 def assert_not_called(self):
320 self.assert_called_with_times(0)
321
322 def assert_called_once_with_args(self, expected_args: str):
323 self.assert_called_with_times(1)
324 self.assert_called_with_args(expected_args)
325
326 def _read_contents_from_output_file(self) -> list[str]:
327 with open(self.output_file, "r") as f:
328 return f.readlines()
329
330
331if __name__ == "__main__":
332 unittest.main()