from datetime import datetime import os import time import unittest from sia.working_memory import WorkingMemory from sia.stop_command import StopCommand from sia.entry.background_entry import BackgroundEntry class StopCommandTest(unittest.TestCase): def setUp(self): """Set up test cases with a fresh working memory""" self.memory = WorkingMemory() self.test_timestamp = datetime(2024, 10, 31, 12, 0, 0) # Use current directory as working directory self.work_dir = os.getcwd() def wait_for_process_start(self, entry: BackgroundEntry, timeout=1.0): """Wait for process to start, checking context pid""" start_time = time.time() while time.time() - start_time < timeout: entry.update() context = entry.generate_context() if context.get("pid") is not None: return True time.sleep(0.1) return False def test_stop_command_cleanup(self): """Test stop command cleans up and removes all entries""" # Add background process with correct work_dir parameter entry = BackgroundEntry("test-id", self.work_dir, "sleep 10") self.memory.add_entry(entry) # Wait for process to start and get PID self.assertTrue(self.wait_for_process_start(entry)) context = entry.generate_context() pid = int(context.get("pid")) # Execute stop command command = StopCommand() result = command.execute(self.memory) # Verify entries removed and process terminated self.assertTrue(result.should_stop) self.assertEqual(self.memory.get_entries_count(), 0) # Verify process was terminated time.sleep(0.1) # Give process time to terminate with self.assertRaises(ProcessLookupError): os.kill(pid, 0)