diff --git a/mobly/controllers/android_device_lib/services/base_service.py b/mobly/controllers/android_device_lib/services/base_service.py index 8706bf03..9e36805b 100644 --- a/mobly/controllers/android_device_lib/services/base_service.py +++ b/mobly/controllers/android_device_lib/services/base_service.py @@ -110,7 +110,9 @@ def create_output_excerpts(self, test_info): service to the call to `create_output_excerpts`. Use `AndroidDevice#generate_filename` to get the proper filenames for - excerpts. + excerpts. Services that stream output into an append-only host file can use + :class:`~mobly.utils.IncrementalFileCopier` to copy newly appended content + on each call. This is usually called at the end of: `setup_class`, `teardown_test`, or `teardown_class`. diff --git a/mobly/controllers/android_device_lib/services/logcat.py b/mobly/controllers/android_device_lib/services/logcat.py index 50e99314..61d320fc 100644 --- a/mobly/controllers/android_device_lib/services/logcat.py +++ b/mobly/controllers/android_device_lib/services/logcat.py @@ -14,7 +14,6 @@ import logging import os -import shutil import time from typing import Any, Callable, Optional, Pattern, Sequence, Set, Union @@ -80,9 +79,9 @@ def __init__(self, android_device, configs=None): super().__init__(android_device, configs) self._ad = android_device self._adb_logcat_process = None - self._adb_logcat_file_obj = None self.adb_logcat_file_path = None self._processor = None + self._excerpt_copier = None self._last_connection_time = None # Kernel boot id observed by the most recent `start()`; None until the # service has started once (or if the id could not be read). @@ -101,6 +100,18 @@ def _get_processor(self) -> logcat_processor.LogcatProcessor: ) return self._processor + def _ensure_excerpt_copier(self) -> Optional[utils.IncrementalFileCopier]: + if not self.adb_logcat_file_path: + return None + if ( + self._excerpt_copier is None + or self._excerpt_copier.source_path != self.adb_logcat_file_path + ): + self._excerpt_copier = utils.IncrementalFileCopier( + self.adb_logcat_file_path, ignore_existing_content=True + ) + return self._excerpt_copier + def _enable_logpersist(self): """Attempts to enable logpersist daemon to persist logs.""" # Logpersist is only allowed on rootable devices because of excessive @@ -358,20 +369,12 @@ def create_output_excerpts(self, test_info): self.OUTPUT_FILE_TYPE, test_info, 'txt' ) excerpt_file_path = os.path.join(dest_path, filename) - with open( - excerpt_file_path, - 'w', - encoding='utf-8', - errors='replace', - # When newline is '', line endings are read without conversion. - newline='', - ) as out: - # Devices may accidentally go offline during test, - # check not None before copying. - if self._adb_logcat_file_obj: - # Copies from the current offset (where the previous excerpt ended) - # to EOF in large chunks instead of line-by-line in Python. - shutil.copyfileobj(self._adb_logcat_file_obj, out) + copier = self._ensure_excerpt_copier() + if copier is not None: + copier.copy_new(excerpt_file_path) + else: + with open(excerpt_file_path, 'wb'): + pass self._ad.log.debug('logcat excerpt created at: %s', excerpt_file_path) return [excerpt_file_path] @@ -424,35 +427,15 @@ def update_config(self, new_config): self._config = new_config self._processor = None - def _open_logcat_file(self): - """Creates a file object that points to the beginning of the logcat file. - - Wait for the logcat file to be created by the subprocess if it doesn't - exist. - """ - if not self._adb_logcat_file_obj: - deadline = time.perf_counter() + CREATE_LOGCAT_FILE_TIMEOUT_SEC - while not os.path.exists(self.adb_logcat_file_path): - if time.perf_counter() > deadline: - raise Error( - self._ad, 'Timeout while waiting for logcat file to be created.' - ) - time.sleep(1) - self._adb_logcat_file_obj = open( - self.adb_logcat_file_path, # pytype: disable=wrong-arg-types - 'r', - encoding='utf-8', - errors='replace', - # When newline is '', line endings are read without conversion. - newline='', - ) - self._adb_logcat_file_obj.seek(0, os.SEEK_END) - - def _close_logcat_file(self): - """Closes and resets the logcat file object, if it exists.""" - if self._adb_logcat_file_obj: - self._adb_logcat_file_obj.close() - self._adb_logcat_file_obj = None + def _wait_for_logcat_file(self): + """Waits for the logcat file to be created by the subprocess.""" + deadline = time.perf_counter() + CREATE_LOGCAT_FILE_TIMEOUT_SEC + while not os.path.exists(self.adb_logcat_file_path): + if time.perf_counter() > deadline: + raise Error( + self._ad, 'Timeout while waiting for logcat file to be created.' + ) + time.sleep(1) def start(self): """Starts a standing adb logcat collection. @@ -488,7 +471,7 @@ def start(self): elif self._config.clear_log: self.clear_adb_log() self._start(dump_buffer=rebooted) - self._open_logcat_file() + self._wait_for_logcat_file() def _start(self, dump_buffer=False): """Starts the actual subprocess logic of starting logcat. @@ -499,7 +482,6 @@ def _start(self, dump_buffer=False): """ self._enable_logpersist() if self._config.output_file_path: - self._close_logcat_file() self.adb_logcat_file_path = self._config.output_file_path if not self.adb_logcat_file_path: f_name = self._ad.generate_filename( @@ -507,6 +489,7 @@ def _start(self, dump_buffer=False): ) logcat_file_path = os.path.join(self._ad.log_path, f_name) self.adb_logcat_file_path = logcat_file_path + self._ensure_excerpt_copier() self._processor = logcat_processor.LogcatProcessor( self.adb_logcat_file_path, timeout_error_cls=lambda msg: LogcatTimeoutError(self._ad, msg), @@ -537,7 +520,6 @@ def _start(self, dump_buffer=False): def stop(self): """Stops the adb logcat service.""" - self._close_logcat_file() self._stop() def _stop(self): diff --git a/mobly/utils.py b/mobly/utils.py index 21017354..ba490ec4 100644 --- a/mobly/utils.py +++ b/mobly/utils.py @@ -13,6 +13,7 @@ # limitations under the License. import base64 +import codecs import concurrent.futures import datetime import inspect @@ -22,6 +23,7 @@ import random import re import shlex +import shutil import signal import string import subprocess @@ -721,3 +723,135 @@ def find_subclass_in_module(base_class, module): % (base_class.__name__, [subclass.__name__ for subclass in subclasses]) ) return subclasses[0] + + +class IncrementalFileCopier: + """Incrementally copies newly appended data from a growing file. + + `IncrementalFileCopier` tracks a source file path and a read byte offset so + callers can repeatedly copy only the bytes appended since the previous call — + for example, splitting a continuous serial, SSH, daemon, or telemetry output + stream into per-step, per-phase, or per-test files. + + No file descriptor is kept open between calls, so the copier requires no + explicit cleanup and does not interfere with external processes appending to, + rotating, or recreating the source file. + + Examples: + Copy newly appended output after each step into separate files:: + + copier = utils.IncrementalFileCopier('/tmp/serial_console.log') + run_step_one() + copier.copy_new('/tmp/step_1_serial.log') + run_step_two() + copier.copy_new('/tmp/step_2_serial.log') + + Attach to an existing file while skipping content written earlier:: + + copier = utils.IncrementalFileCopier( + '/var/log/daemon.log', ignore_existing_content=True + ) + trigger_action() + copier.copy_new('/tmp/action_daemon.log') + + Copy newly appended chunks of a binary stream without text decoding:: + + copier = utils.IncrementalFileCopier('/tmp/hci_snoop.bin', encoding=None) + copier.copy_new('/tmp/segment_1.bin') + """ + + def __init__( + self, + source_path: str | os.PathLike[str], + ignore_existing_content: bool = False, + encoding: str | None = 'utf-8', + errors: str = 'replace', + ) -> None: + """Initializes an `IncrementalFileCopier` for `source_path`. + + Args: + source_path: Path to the file to read from. The file does not need to + exist yet when the copier is created. + ignore_existing_content: If True, initializes the read offset to the + current size of `source_path` so pre-existing content is skipped. If + False, starts reading from byte 0. + encoding: Text encoding used to decode and write copied content, or None + to copy raw bytes without decoding. + errors: Error handling scheme passed to the incremental decoder when + `encoding` is set (for example, `'replace'`, `'ignore'`, or `'strict'`). + """ + self._source_path = os.fspath(source_path) + self._encoding = encoding + self._errors = errors + self._offset = self._current_size() if ignore_existing_content else 0 + + @property + def source_path(self) -> str: + """Path of the source file tracked by this copier.""" + return self._source_path + + @property + def offset(self) -> int: + """Current byte offset from which the next `copy_new` call will read.""" + return self._offset + + def _current_size(self) -> int: + try: + return os.path.getsize(self._source_path) + except OSError: + return 0 + + def advance_to_end(self) -> None: + """Advances `offset` to the current end of `source_path`. + + Any uncopied bytes currently in `source_path` will be skipped by subsequent + `copy_new` calls. + """ + self._offset = self._current_size() + + def reset(self) -> None: + """Resets `offset` to 0 so the next call reads from the start of the file.""" + self._offset = 0 + + def copy_new(self, dest_path: str | os.PathLike[str]) -> int: + """Copies content appended to `source_path` since the last call. + + Parent directories of `dest_path` are created automatically. If + `source_path` does not exist yet, an empty file is created at `dest_path`. + If `source_path` was truncated or recreated smaller than `offset`, `offset` + resets to 0 before reading. When `encoding` is set, original line endings + (`\\n` and `\\r\\n`) are preserved verbatim. + + Args: + dest_path: Destination file path for the newly appended data. + + Returns: + The number of source bytes read from `source_path`. + """ + dest_str = os.fspath(dest_path) + parent_dir = os.path.dirname(dest_str) + if parent_dir: + create_dir(parent_dir) + if not os.path.exists(self._source_path): + with open(dest_str, 'wb'): + pass + return 0 + with open(self._source_path, 'rb') as src: + if os.fstat(src.fileno()).st_size < self._offset: + self._offset = 0 + start_offset = self._offset + src.seek(start_offset) + if self._encoding is None: + with open(dest_str, 'wb') as dst: + shutil.copyfileobj(src, dst) + else: + decoder = codecs.getincrementaldecoder(self._encoding)( + errors=self._errors + ) + with open(dest_str, 'w', encoding=self._encoding, newline='') as dst: + while chunk := src.read(65536): + dst.write(decoder.decode(chunk, final=False)) + if tail := decoder.decode(b'', final=True): + dst.write(tail) + self._offset = src.tell() + return self._offset - start_offset diff --git a/tests/mobly/controllers/android_device_lib/services/logcat_test.py b/tests/mobly/controllers/android_device_lib/services/logcat_test.py index 46def19f..864fd2f2 100755 --- a/tests/mobly/controllers/android_device_lib/services/logcat_test.py +++ b/tests/mobly/controllers/android_device_lib/services/logcat_test.py @@ -109,7 +109,7 @@ def AssertFileDoesNotContain(self, content, file_path): @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch('mobly.logger.get_log_file_timestamp') def test_start_and_stop( self, @@ -188,7 +188,7 @@ def test_start_in_fastboot_mode( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_update_config( self, open_logcat_mock, @@ -231,7 +231,7 @@ def test_update_config( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_update_config_while_running( self, open_logcat_mock, @@ -305,7 +305,7 @@ def _pause_and_resume_logcat_service( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch( 'mobly.controllers.android_device_lib.services.logcat.Logcat.clear_adb_log', return_value=mock_android_device.MockAdbProxy('1'), @@ -399,7 +399,7 @@ def test_pause_and_resume( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch( 'mobly.controllers.android_device_lib.services.logcat.Logcat.clear_adb_log', return_value=mock_android_device.MockAdbProxy('1'), @@ -516,7 +516,7 @@ def _shell(cmd, *args, **kwargs): @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch( 'mobly.controllers.android_device_lib.services.logcat.Logcat.clear_adb_log' ) @@ -571,7 +571,7 @@ def test_restart_after_reboot_keeps_boot_logs( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch( 'mobly.controllers.android_device_lib.services.logcat.Logcat.clear_adb_log' ) @@ -613,7 +613,7 @@ def test_restart_without_reboot_clears_log( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch( 'mobly.controllers.android_device_lib.services.logcat.Logcat.clear_adb_log' ) @@ -677,14 +677,23 @@ def test_logcat_service_create_output_excerpts( ): mock_serial = '1' ad = android_device.AndroidDevice(serial=mock_serial) - logcat_service = logcat.Logcat(ad) + preexisting_path = os.path.join( + self.tmp_dir, f'logcat,{mock_serial},fakemodel,base.txt' + ) + NOT_IN_EXCERPT = 'Not in excerpt.\n' + with open(preexisting_path, 'w', newline='') as f: + f.write(NOT_IN_EXCERPT) + logcat_service = logcat.Logcat( + ad, logcat.Config(output_file_path=preexisting_path) + ) logcat_service._start() def _write_logcat_file_and_assert_excerpts_exists( logcat_file_content, test_begin_time, test_name ): - with open(logcat_service.adb_logcat_file_path, 'a', newline='') as f: - f.write(logcat_file_content) + if logcat_file_content: + with open(logcat_service.adb_logcat_file_path, 'a', newline='') as f: + f.write(logcat_file_content) test_output_dir = os.path.join(self.tmp_dir, test_name) mock_record = records.TestResultRecord(test_name) mock_record.begin_time = test_begin_time @@ -708,13 +717,6 @@ def _write_logcat_file_and_assert_excerpts_exists( self.assertTrue(os.path.exists(expected_path)) return expected_path - # Generate logs before the file pointer is created. - # This message will not be captured in the excerpt. - NOT_IN_EXCERPT = 'Not in excerpt.\n' - with open(logcat_service.adb_logcat_file_path, 'a', newline='') as f: - f.write(NOT_IN_EXCERPT) - # With the file pointer created, generate logs and make an excerpt. - logcat_service._open_logcat_file() # Both CR and LF should be preserved no matter the operating system. FILE_CONTENT = 'Some log.\r\nAnother log.\n' expected_path1 = _write_logcat_file_and_assert_excerpts_exists( @@ -733,15 +735,197 @@ def _write_logcat_file_and_assert_excerpts_exists( ) self.AssertFileContains(FILE_CONTENT, expected_path2) self.AssertFileDoesNotContain(FILE_CONTENT, expected_path1) - # Simulate devices accidentally go offline, logcat service stopped. + # Logs written before `stop()` are still clipped, and a subsequent excerpt + # with no new logs is empty. + PRE_STOP_CONTENT = 'Logs before stop\n' + with open(logcat_service.adb_logcat_file_path, 'a', newline='') as f: + f.write(PRE_STOP_CONTENT) logcat_service.stop() - FILE_CONTENT = 'Whatever logs\n' expected_path3 = _write_logcat_file_and_assert_excerpts_exists( - logcat_file_content=FILE_CONTENT, + logcat_file_content='', test_begin_time=789, - test_name='test_offline', + test_name='test_stopped', + ) + self.AssertFileContains(PRE_STOP_CONTENT, expected_path3) + expected_path4 = _write_logcat_file_and_assert_excerpts_exists( + logcat_file_content='', + test_begin_time=999, + test_name='test_stopped_empty', ) - self.assertEqual(os.stat(expected_path3).st_size, 0) + self.assertEqual(os.stat(expected_path4).st_size, 0) + + @mock.patch( + 'mobly.controllers.android_device_lib.adb.AdbProxy', + return_value=mock_android_device.MockAdbProxy('1'), + ) + @mock.patch( + 'mobly.controllers.android_device_lib.fastboot.FastbootProxy', + return_value=mock_android_device.MockFastbootProxy('1'), + ) + @mock.patch('mobly.utils.start_standing_subprocess') + @mock.patch('mobly.utils.stop_standing_subprocess') + @mock.patch( + 'mobly.controllers.android_device_lib.services.logcat.Logcat.clear_adb_log' + ) + def test_create_output_excerpts_preserves_logs_across_reboot_restart( + self, + clear_adb_mock, + stop_proc_mock, + start_proc_mock, + FastbootProxy, + MockAdbProxy, + ): + """Logs written before and during a mid-test reboot stay in the excerpt.""" + ad = android_device.AndroidDevice(serial='1') + ad.log_path = self.tmp_dir + boot_ids = iter(['boot-1', 'boot-2']) + ad.adb.shell = mock.MagicMock( + side_effect=lambda cmd, *a, **kw: ( + next(boot_ids).encode('utf-8') + if cmd == logcat._BOOT_ID_CMD + else b'' + ) + ) + logcat_service = logcat.Logcat(ad) + starts = 0 + + def _fake_start_proc(cmd, shell=False): + nonlocal starts + starts += 1 + with open( + logcat_service.adb_logcat_file_path, 'a', encoding='utf-8', newline='' + ) as f: + if starts == 1: + f.write('Initial startup line.\n') + else: + f.write('Boot dump line before wait.\n') + return 'process' + + start_proc_mock.side_effect = _fake_start_proc + + def _make_test_info(name, begin_time): + out_dir = os.path.join(self.tmp_dir, name) + rec = records.TestResultRecord(name) + rec.begin_time = begin_time + rec.signature = f'{name}-{begin_time}' + return runtime_test_info.RuntimeTestInfo(name, out_dir, rec) + + logcat_service.start() + with open( + logcat_service.adb_logcat_file_path, 'a', encoding='utf-8', newline='' + ) as f: + f.write('Setup class log.\n') + setup_excerpt = logcat_service.create_output_excerpts( + _make_test_info('setup_class', 100) + )[0] + self.AssertFileContains('Initial startup line.\n', setup_excerpt) + self.AssertFileContains('Setup class log.\n', setup_excerpt) + + # Test logs before reboot, then handle_reboot stops and restarts logcat. + with open( + logcat_service.adb_logcat_file_path, 'a', encoding='utf-8', newline='' + ) as f: + f.write('Pre-reboot test log.\n') + logcat_service.stop() + logcat_service.start() + with open( + logcat_service.adb_logcat_file_path, 'a', encoding='utf-8', newline='' + ) as f: + f.write('Post-reboot test log.\n') + + reboot_excerpt = logcat_service.create_output_excerpts( + _make_test_info('test_reboot', 200) + )[0] + self.AssertFileDoesNotContain('Setup class log.\n', reboot_excerpt) + self.AssertFileContains('Pre-reboot test log.\n', reboot_excerpt) + self.AssertFileContains('Boot dump line before wait.\n', reboot_excerpt) + self.AssertFileContains('Post-reboot test log.\n', reboot_excerpt) + + # Next test excerpt starts after `test_reboot` ended. + with open( + logcat_service.adb_logcat_file_path, 'a', encoding='utf-8', newline='' + ) as f: + f.write('Next test log.\n') + next_excerpt = logcat_service.create_output_excerpts( + _make_test_info('test_next', 300) + )[0] + self.AssertFileDoesNotContain('Pre-reboot test log.\n', next_excerpt) + self.AssertFileDoesNotContain('Post-reboot test log.\n', next_excerpt) + self.AssertFileContains('Next test log.\n', next_excerpt) + logcat_service.stop() + + @mock.patch( + 'mobly.controllers.android_device_lib.adb.AdbProxy', + return_value=mock_android_device.MockAdbProxy('1'), + ) + @mock.patch( + 'mobly.controllers.android_device_lib.fastboot.FastbootProxy', + return_value=mock_android_device.MockFastbootProxy('1'), + ) + def test_create_output_excerpts_when_never_started( + self, FastbootProxy, MockAdbProxy + ): + ad = android_device.AndroidDevice(serial='1') + logcat_service = logcat.Logcat(ad) + rec = records.TestResultRecord('test_unstarted') + rec.begin_time = 100 + rec.signature = 'test_unstarted-100' + info = runtime_test_info.RuntimeTestInfo( + 'test_unstarted', os.path.join(self.tmp_dir, 'test_unstarted'), rec + ) + excerpt_path = logcat_service.create_output_excerpts(info)[0] + self.assertEqual(os.stat(excerpt_path).st_size, 0) + + @mock.patch( + 'mobly.controllers.android_device_lib.adb.AdbProxy', + return_value=mock_android_device.MockAdbProxy('1'), + ) + @mock.patch( + 'mobly.controllers.android_device_lib.fastboot.FastbootProxy', + return_value=mock_android_device.MockFastbootProxy('1'), + ) + @mock.patch('mobly.utils.start_standing_subprocess') + @mock.patch('mobly.utils.stop_standing_subprocess') + @mock.patch( + 'mobly.controllers.android_device_lib.services.logcat.Logcat.clear_adb_log' + ) + def test_create_output_excerpts_resets_when_output_file_path_changes( + self, + clear_adb_mock, + stop_proc_mock, + start_proc_mock, + FastbootProxy, + MockAdbProxy, + ): + ad = android_device.AndroidDevice(serial='1') + file1 = os.path.join(self.tmp_dir, 'log1.txt') + file2 = os.path.join(self.tmp_dir, 'log2.txt') + with open(file1, 'w', encoding='utf-8', newline='') as f: + f.write('Old file1 header.\n') + with open(file2, 'w', encoding='utf-8', newline='') as f: + f.write('Pre-existing file2 content.\n') + start_proc_mock.return_value = 'process' + + logcat_service = logcat.Logcat(ad, logcat.Config(output_file_path=file1)) + logcat_service.start() + with open(file1, 'a', encoding='utf-8', newline='') as f: + f.write('File1 test log.\n') + logcat_service.stop() + logcat_service.update_config(logcat.Config(output_file_path=file2)) + logcat_service.start() + with open(file2, 'a', encoding='utf-8', newline='') as f: + f.write('File2 test log.\n') + + rec = records.TestResultRecord('test_reconfig') + rec.begin_time = 100 + rec.signature = 'test_reconfig-100' + info = runtime_test_info.RuntimeTestInfo( + 'test_reconfig', os.path.join(self.tmp_dir, 'test_reconfig'), rec + ) + excerpt_path = logcat_service.create_output_excerpts(info)[0] + self.AssertFileDoesNotContain('Pre-existing file2 content.\n', excerpt_path) + self.AssertFileContains('File2 test log.\n', excerpt_path) + logcat_service.stop() @mock.patch( 'mobly.controllers.android_device_lib.adb.AdbProxy', @@ -754,7 +938,7 @@ def _write_logcat_file_and_assert_excerpts_exists( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch('mobly.logger.get_log_file_timestamp') def test_take_logcat_with_extra_params( self, @@ -1119,7 +1303,7 @@ def test_features_work_across_and_after_create_output_excerpts(self): f'excerpt_{test_info.name}.txt' if test_info else 'logcat.txt' ) ) - self.logcat_service._open_logcat_file() + self.logcat_service._ensure_excerpt_copier() # 1. Take a position marker before initial action start_pos = self.logcat_service.now() diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py index 1486d590..c4a56978 100755 --- a/tests/mobly/controllers/android_device_test.py +++ b/tests/mobly/controllers/android_device_test.py @@ -1565,7 +1565,7 @@ def test_AndroidDevice_with_reserved_character_in_serial_log_path( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_AndroidDevice_change_log_path_with_service( self, open_logcat_mock, @@ -1647,7 +1647,7 @@ def test_AndroidDevice_update_serial( @mock.patch('mobly.utils.create_dir') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_AndroidDevice_update_serial_with_service_running( self, open_logcat_mock, @@ -1878,7 +1878,7 @@ def test_AndroidDevice_unload_snippet( 'mobly.controllers.android_device_lib.snippet_client_v2.SnippetClientV2' ) @mock.patch('mobly.utils.get_available_host_port') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') def test_AndroidDevice_snippet_cleanup( @@ -1938,7 +1938,7 @@ def test_AndroidDevice_debug_tag(self, MockFastboot, MockAdbProxy): ) @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_AndroidDevice_handle_usb_disconnect( self, open_logcat_mock, @@ -1992,7 +1992,7 @@ def resume(self): ) @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_AndroidDevice_handle_reboot( self, open_logcat_mock, @@ -2046,7 +2046,7 @@ def resume(self): ) @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_AndroidDevice_handle_reboot_changes_build_info( self, open_logcat_mock, @@ -2074,7 +2074,7 @@ def test_AndroidDevice_handle_reboot_changes_build_info( ) @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') @mock.patch('mobly.utils.stop_standing_subprocess') - @mock.patch.object(logcat.Logcat, '_open_logcat_file') + @mock.patch.object(logcat.Logcat, '_wait_for_logcat_file') def test_AndroidDevice_handle_reboot_changes_build_info_with_caching( self, open_logcat_mock, diff --git a/tests/mobly/utils_test.py b/tests/mobly/utils_test.py index 75aa7930..4351713a 100755 --- a/tests/mobly/utils_test.py +++ b/tests/mobly/utils_test.py @@ -974,6 +974,89 @@ def test_find_subclass_in_module_when_multiple_subclasses(self): base_test.BaseTestClass, multiple_subclasses_module ) + def test_incremental_file_copier_ignore_existing(self): + src = os.path.join(self.tmp_dir, 'source.log') + with open(src, 'w', encoding='utf-8', newline='') as f: + f.write('pre-existing\n') + copier = utils.IncrementalFileCopier(src, ignore_existing_content=True) + self.assertEqual(copier.source_path, src) + self.assertEqual(copier.offset, len(b'pre-existing\n')) + + with open(src, 'a', encoding='utf-8', newline='') as f: + f.write('chunk1\r\nline2\n') + out1 = os.path.join(self.tmp_dir, 'out', 'step1.log') + self.assertEqual(copier.copy_new(out1), len(b'chunk1\r\nline2\n')) + with open(out1, 'r', encoding='utf-8', newline='') as f: + self.assertEqual(f.read(), 'chunk1\r\nline2\n') + + with open(src, 'a', encoding='utf-8', newline='') as f: + f.write('chunk2\n') + out2 = os.path.join(self.tmp_dir, 'out', 'step2.log') + self.assertEqual(copier.copy_new(out2), len(b'chunk2\n')) + with open(out2, 'r', encoding='utf-8', newline='') as f: + self.assertEqual(f.read(), 'chunk2\n') + + # Subsequent copy with no new data creates an empty file and returns 0. + out3 = os.path.join(self.tmp_dir, 'out', 'step3.log') + self.assertEqual(copier.copy_new(out3), 0) + self.assertEqual(os.path.getsize(out3), 0) + + def test_incremental_file_copier_default_reads_from_start_and_missing_source( + self, + ): + missing = os.path.join(self.tmp_dir, 'missing.log') + copier = utils.IncrementalFileCopier(missing) + self.assertEqual(copier.offset, 0) + empty_out = os.path.join(self.tmp_dir, 'empty.log') + self.assertEqual(copier.copy_new(empty_out), 0) + self.assertEqual(os.path.getsize(empty_out), 0) + + with open(missing, 'wb') as f: + f.write(b'hello \xff world\n') + out_invalid_utf8 = os.path.join(self.tmp_dir, 'utf8.log') + self.assertEqual( + copier.copy_new(out_invalid_utf8), len(b'hello \xff world\n') + ) + with open(out_invalid_utf8, 'r', encoding='utf-8', newline='') as f: + self.assertEqual(f.read(), 'hello \ufffd world\n') + + # Default `ignore_existing_content=False` reads existing content from byte 0. + default_copier = utils.IncrementalFileCopier(missing) + full_out = os.path.join(self.tmp_dir, 'full.log') + default_copier.copy_new(full_out) + with open(full_out, 'r', encoding='utf-8', newline='') as f: + self.assertEqual(f.read(), 'hello \ufffd world\n') + + def test_incremental_file_copier_binary_mode_reset_and_truncation(self): + src = os.path.join(self.tmp_dir, 'binary.bin') + with open(src, 'wb') as f: + f.write(b'\x00\xff\xfe\r\n') + copier = utils.IncrementalFileCopier(src, encoding=None) + bin1 = os.path.join(self.tmp_dir, 'bin1.bin') + self.assertEqual(copier.copy_new(bin1), 5) + with open(bin1, 'rb') as f: + self.assertEqual(f.read(), b'\x00\xff\xfe\r\n') + + # `reset()` rewinds offset back to 0. + copier.reset() + self.assertEqual(copier.offset, 0) + bin2 = os.path.join(self.tmp_dir, 'bin2.bin') + self.assertEqual(copier.copy_new(bin2), 5) + with open(bin2, 'rb') as f: + self.assertEqual(f.read(), b'\x00\xff\xfe\r\n') + + # `advance_to_end()` skips new uncopied bytes, and truncating below offset + # resets offset to 0. + with open(src, 'ab') as f: + f.write(b'skipped bytes that make file longer') + copier.advance_to_end() + with open(src, 'wb') as f: + f.write(b'short') + bin3 = os.path.join(self.tmp_dir, 'bin3.bin') + self.assertEqual(copier.copy_new(bin3), 5) + with open(bin3, 'rb') as f: + self.assertEqual(f.read(), b'short') + if __name__ == '__main__': unittest.main()