Skip to content

Commit 55e4286

Browse files
gabrielle-laucopybara-github
authored andcommitted
Handle restarting logcat thread processing if non-alive after env reset
PiperOrigin-RevId: 864898141
1 parent 9ae3d59 commit 55e4286

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

android_env/components/logcat_thread.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,12 @@ def pause(self):
7777
self._log_stream.pause_stream()
7878

7979
def resume(self):
80+
"""Resume or restart the thread if it's dead after resetting environment."""
81+
if not self._thread.is_alive():
82+
self._should_stop.clear()
83+
self._thread = threading.Thread(target=self._process_logs)
84+
self._thread.daemon = True
85+
self._thread.start()
8086
self._log_stream.resume_stream()
8187

8288
def kill(self):

android_env/components/logcat_thread_test.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ def has_next_value(self):
4242
def kill(self):
4343
self._kill = True
4444

45+
def reset(self):
46+
self._kill = False
47+
4548
def __iter__(self):
4649
while True:
4750
if self._kill:
@@ -74,6 +77,10 @@ def stop_stream(self):
7477
self.stream_is_alive = False
7578
self.logs.kill()
7679

80+
def reset(self):
81+
self.stream_is_alive = True
82+
self.logs.reset()
83+
7784

7885
class LogcatThreadTest(absltest.TestCase):
7986

@@ -135,6 +142,27 @@ def my_handler(event: re.Pattern[str], match: re.Match[str]):
135142
some_state.wait(timeout=1.0)
136143
self.assertFalse(some_state.is_set())
137144

145+
def test_resume_does_not_recreate_alive_thread(self):
146+
logcat = logcat_thread.LogcatThread(log_stream=self.fake_log_stream)
147+
thread_before = logcat._thread
148+
self.assertTrue(thread_before.is_alive())
149+
logcat.resume()
150+
thread_after = logcat._thread
151+
self.assertTrue(thread_after.is_alive())
152+
self.assertIs(thread_before, thread_after)
153+
154+
def test_resume_recreates_thread(self):
155+
logcat = logcat_thread.LogcatThread(log_stream=self.fake_log_stream)
156+
self.assertTrue(logcat._thread.is_alive())
157+
logcat.kill()
158+
self.assertFalse(logcat._thread.is_alive())
159+
self.assertTrue(logcat._should_stop.is_set())
160+
self.fake_log_stream.reset()
161+
logcat.resume()
162+
self.assertTrue(logcat._thread.is_alive())
163+
self.assertFalse(logcat._should_stop.is_set())
164+
self.assertTrue(logcat._thread.daemon)
165+
138166

139167
if __name__ == '__main__':
140168
absltest.main()

0 commit comments

Comments
 (0)