Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
added more messaging and cli tests
Alishahryar143a0786fc154
diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 1eef7a2c..4b775a80 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -1,8 +1,13 @@"""Tests for cli/ module."""import pytest+import asyncio+import json+import osfrom unittest.mock import AsyncMock, MagicMock, patch+# --- Existing Parser Tests ---+class TestCLIParser:"""Test CLIParser event parsing."""@@ -154,6 +159,9 @@ class TestCLIParser:assert result == []+# --- CLI Session Tests ---++class TestCLISession:"""Test CLISession."""@@ -166,7 +174,7 @@ class TestCLISession:api_url="http://localhost:8082/v1",allowed_dirs=["/home/user/projects"],)- assert session.workspace == "/tmp/test" or "test" in session.workspace+ assert session.workspace == os.path.normpath(os.path.abspath("/tmp/test"))assert session.api_url == "http://localhost:8082/v1"assert not session.is_busy@@ -202,6 +210,306 @@ class TestCLISession:assert session._extract_session_id({"type": "message"}) is Noneassert session._extract_session_id("not a dict") is None+ @pytest.mark.asyncio+ async def test_start_task_basic_flow(self):+ """Test start_task running a basic command flow."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ # Mock subprocess+ mock_process = AsyncMock()+ mock_process.stdout.read.side_effect = [+ b'{"type": "message", "content": "Hello"}\n',+ b'{"session_id": "sess_1"}\n',+ b"", # EOF+ ]+ mock_process.stderr.read.return_value = b"" # No error+ mock_process.wait.return_value = 0+ mock_process.returncode = 0++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process++ events = []+ async for event in session.start_task("Hello"):+ events.append(event)++ # Verify command construction+ # Arg 1 is subprocess command+ args = mock_exec.call_args[0]+ assert args[0] == "claude"+ assert "-p" in args+ assert "Hello" in args++ # Verify events+ assert (+ len(events) == 4+ ) # message, session_id, session_info (synthesized), exit+ assert events[0] == {"type": "message", "content": "Hello"}+ assert events[1] == {"type": "session_info", "session_id": "sess_1"}+ # The session_info event is yielded by _handle_line_gen right after extracting ID+ assert events[2] == {"session_id": "sess_1"} # The original event+ assert events[3] == {"type": "exit", "code": 0, "stderr": None}++ assert session.current_session_id == "sess_1"++ @pytest.mark.asyncio+ async def test_start_task_with_session_resume(self):+ """Test resuming an existing session."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = AsyncMock()+ mock_process.stdout.read.side_effect = [+ b"",+ ] # Immediate EOF+ mock_process.stderr.read.return_value = b""+ mock_process.wait.return_value = 0++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process++ async for _ in session.start_task("Hello", session_id="sess_abc"):+ pass++ args = mock_exec.call_args[0]+ assert "--resume" in args+ assert "sess_abc" in args++ @pytest.mark.asyncio+ async def test_start_task_process_failure_with_stderr(self):+ """Test process exit with error code and stderr output."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = AsyncMock()+ mock_process.stdout.read.side_effect = [b""] # No stdout+ mock_process.stderr.read.return_value = b"Fatal error"+ mock_process.wait.return_value = 1++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process++ events = []+ async for event in session.start_task("Hello"):+ events.append(event)++ # Should have error event from stderr, then exit event+ assert len(events) == 2+ assert events[0]["type"] == "error"+ assert events[0]["error"]["message"] == "Fatal error"++ assert events[1]["type"] == "exit"+ assert events[1]["code"] == 1+ assert events[1]["stderr"] == "Fatal error"++ @pytest.mark.asyncio+ async def test_stop_session(self):+ """Test stopping the session process."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = MagicMock()+ mock_process.returncode = None # Running+ # Mock wait to simulate async finish+ mock_process.wait = AsyncMock(return_value=0)++ session.process = mock_process++ stopped = await session.stop()++ assert stopped is True+ mock_process.terminate.assert_called_once()+ mock_process.wait.assert_called()++ @pytest.mark.asyncio+ async def test_stop_session_timeout_force_kill(self):+ """Test force kill if terminate times out."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = MagicMock()+ mock_process.returncode = None++ # First wait times out+ async def wait_side_effect():+ if not mock_process.kill.called:+ await asyncio.sleep(6) # Should be > 5.0 timeout+ return 0++ # We can simulate timeout by raising TimeoutError directly on first call+ mock_process.wait = AsyncMock(side_effect=[asyncio.TimeoutError, 0])++ session.process = mock_process++ stopped = await session.stop()++ assert stopped is True+ mock_process.terminate.assert_called()+ mock_process.kill.assert_called()++ @pytest.mark.asyncio+ async def test_start_task_split_buffer(self):+ """Test handling of JSON split across chunks."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = AsyncMock()+ # Split json: {"type": "mess... age"}+ mock_process.stdout.read.side_effect = [+ b'{"type": "mess',+ b'age", "content": "Split"}\n',+ b"",+ ]+ mock_process.stderr.read.return_value = b""+ mock_process.wait.return_value = 0++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process++ events = []+ async for event in session.start_task("test"):+ if event["type"] == "message":+ events.append(event)++ assert len(events) == 1+ assert events[0]["content"] == "Split"++ @pytest.mark.asyncio+ async def test_start_task_remnant_buffer(self):+ """Test handling of buffer remnant at EOF (no newline at end)."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = AsyncMock()+ mock_process.stdout.read.side_effect = [+ b'{"type": "message", "content": "Remnant"}', # No newline+ b"",+ ]+ mock_process.stderr.read.return_value = b""+ mock_process.wait.return_value = 0++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process++ events = []+ async for event in session.start_task("test"):+ if event["type"] == "message":+ events.append(event)++ assert len(events) == 1+ assert events[0]["content"] == "Remnant"++ @pytest.mark.asyncio+ async def test_start_task_non_v1_url(self):+ """Test start_task with a non-v1 URL."""+ from cli.session import CLISession++ # URL not ending in /v1+ session = CLISession("/tmp", "http://localhost:8082")++ mock_process = AsyncMock()+ mock_process.stdout.read.side_effect = [b""]+ mock_process.stderr.read.return_value = b""+ mock_process.wait.return_value = 0++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process+ async for _ in session.start_task("test"):+ pass++ # Check env var+ kwargs = mock_exec.call_args[1]+ env = kwargs["env"]+ assert env["ANTHROPIC_BASE_URL"] == "http://localhost:8082"++ @pytest.mark.asyncio+ async def test_start_task_allowed_dirs(self):+ """Test start_task includes allowed dirs in command."""+ from cli.session import CLISession++ session = CLISession(+ "/tmp", "http://localhost:8082/v1", allowed_dirs=["/dir1", "/dir2"]+ )++ mock_process = AsyncMock()+ mock_process.stdout.read.side_effect = [b""]+ mock_process.stderr.read.return_value = b""+ mock_process.wait.return_value = 0++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process+ async for _ in session.start_task("test"):+ pass++ cmd = mock_exec.call_args[0]+ assert "--add-dir" in cmd+ assert os.path.normpath("/dir1") in cmd+ assert os.path.normpath("/dir2") in cmd++ @pytest.mark.asyncio+ async def test_start_task_json_error(self):+ """Test handling of non-JSON output from CLI."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = AsyncMock()+ mock_process.stdout.read.side_effect = [b"Not valid json\n", b""]+ mock_process.stderr.read.return_value = b""+ mock_process.wait.return_value = 0++ with patch(+ "asyncio.create_subprocess_exec", new_callable=AsyncMock+ ) as mock_exec:+ mock_exec.return_value = mock_process++ events = []+ async for event in session.start_task("test"):+ if event["type"] == "raw":+ events.append(event)++ assert len(events) == 1+ assert events[0]["content"] == "Not valid json"++ @pytest.mark.asyncio+ async def test_stop_exception(self):+ """Test exception handling during stop."""+ from cli.session import CLISession++ session = CLISession("/tmp", "http://localhost:8082/v1")++ mock_process = MagicMock()+ mock_process.returncode = None+ # Raise exception on terminate+ mock_process.terminate.side_effect = RuntimeError("Permission denied")++ session.process = mock_process++ stopped = await session.stop()+ assert stopped is False+class TestCLISessionManager:"""Test CLISessionManager."""diff --git a/tests/test_messaging.py b/tests/test_messaging.pyindex a4547e4a..970098bb 100644--- a/tests/test_messaging.py+++ b/tests/test_messaging.py@@ -1,8 +1,12 @@"""Tests for messaging/ module."""import pytest-from datetime import datetime-from unittest.mock import AsyncMock, MagicMock+import json+import os+from datetime import datetime, timedelta+from unittest.mock import AsyncMock, MagicMock, patch, mock_open++# --- Existing Tests ---class TestMessagingModels:@@ -99,6 +103,9 @@ class TestSessionStore:found = store.get_session_by_msg("chat_456", "msg_789", "telegram")assert found == "sess_123"+ # Verify persistence file created+ assert os.path.exists(str(tmp_path / "sessions.json"))+def test_update_last_message(self, tmp_path):"""Test updating last message in session."""from messaging.session import SessionStore@@ -112,6 +119,22 @@ class TestSessionStore:found = store.get_session_by_msg("chat_1", "msg_2", "telegram")assert found == "sess_1"+ # Original message mapping should still work+ found_old = store.get_session_by_msg("chat_1", "msg_1", "telegram")+ assert found_old == "sess_1"++ # Verify record updated+ record = store.get_session_record("sess_1")+ assert record.last_msg_id == "msg_2"++ def test_update_last_message_unknown_session(self, tmp_path):+ """Test updating unknown session does nothing."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))+ store.update_last_message("unknown", "msg_x")+ # Should log warning but not crash+def test_get_session_record(self, tmp_path):"""Test getting full session record."""from messaging.session import SessionStore@@ -133,6 +156,214 @@ class TestSessionStore:found = store.get_session_by_msg("notexist", "notexist", "telegram")assert found is None+ def test_rename_session(self, tmp_path):+ """Test renaming a session."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))+ store.save_session("old_id", "c1", "m1", "telegram")+ store.update_last_message("old_id", "m2")++ success = store.rename_session("old_id", "new_id")+ assert success is True++ # Verify old id gone+ assert store.get_session_record("old_id") is None++ # Verify new id exists+ rec = store.get_session_record("new_id")+ assert rec is not None+ assert rec.session_id == "new_id"++ # Verify mappings point to new id+ assert store.get_session_by_msg("c1", "m1", "telegram") == "new_id"+ assert store.get_session_by_msg("c1", "m2", "telegram") == "new_id"++ def test_rename_unknown_session(self, tmp_path):+ """Test renaming unknown session fails."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))+ success = store.rename_session("unknown", "new")+ assert success is False++ def test_cleanup_old_sessions(self, tmp_path):+ """Test cleaning up expired sessions."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))++ # Create an old session manually+ old_date = (datetime.utcnow() - timedelta(days=40)).isoformat()+ store.save_session("old_sess", "c_old", "m_old")+ # Manipulate the created_at directly+ store._sessions["old_sess"].created_at = old_date++ # Create a new session+ store.save_session("new_sess", "c_new", "m_new")++ # Cleanup+ removed = store.cleanup_old_sessions(max_age_days=30)+ assert removed == 1++ assert store.get_session_record("old_sess") is None+ assert store.get_session_by_msg("c_old", "m_old") is None+ assert store.get_session_record("new_sess") is not None++ def test_cleanup_old_sessions_invalid_date(self, tmp_path):+ """Test cleanup handles invalid date formats gracefully."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))+ store.save_session("bad_date_sess", "c", "m")+ store._sessions["bad_date_sess"].created_at = "not-a-date"++ # Should not crash+ store.cleanup_old_sessions(30)+ # Should still exist because parsing failed so it wasn't removed (or default behavior)+ # The code tries parsing, excepts, and continues, so it isn't removed.+ assert store.get_session_record("bad_date_sess") is not None++ # --- Tree Tests ---++ def test_save_and_get_tree(self, tmp_path):+ """Test saving and retrieving trees."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))++ tree_data = {+ "root": "r1",+ "nodes": {"r1": {"content": "root"}, "n1": {"content": "child"}},+ }+ store.save_tree("r1", tree_data)++ loaded = store.get_tree("r1")+ assert loaded == tree_data++ # Verify node mapping+ assert store.get_tree_root_for_node("r1") == "r1"+ assert store.get_tree_root_for_node("n1") == "r1"++ # Verify get_tree_by_node+ assert store.get_tree_by_node("n1") == tree_data+ assert store.get_tree_by_node("unknown") is None++ def test_update_tree_node(self, tmp_path):+ """Test updating a specific node in a tree."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))++ store.save_tree("r1", {"nodes": {"r1": {}}})++ # Add new node+ store.update_tree_node("r1", "n2", {"data": "test"})++ tree = store.get_tree("r1")+ assert "n2" in tree["nodes"]+ assert tree["nodes"]["n2"]["data"] == "test"+ assert store.get_tree_root_for_node("n2") == "r1"++ def test_update_tree_node_unknown_tree(self, tmp_path):+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))+ store.update_tree_node("unknown_root", "n1", {})+ # Should not crash++ def test_register_node(self, tmp_path):+ """Test manual node registration."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))+ store.register_node("n_manual", "r_manual")+ assert store.get_tree_root_for_node("n_manual") == "r_manual"++ def test_cleanup_old_trees(self, tmp_path):+ """Test cleaning up expired trees."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))++ old_date = (datetime.utcnow() - timedelta(days=40)).isoformat()++ # Old tree+ store.save_tree(+ "old_root", {"nodes": {"old_root": {"created_at": old_date}, "child": {}}}+ )++ # New tree+ store.save_tree(+ "new_root",+ {"nodes": {"new_root": {"created_at": datetime.utcnow().isoformat()}}},+ )++ removed = store.cleanup_old_trees(30)+ assert removed == 1++ assert store.get_tree("old_root") is None+ assert (+ store.get_tree_root_for_node("child") is None+ ) # Node mapping should be gone+ assert store.get_tree("new_root") is not None++ # --- Persistence & Edge Cases ---++ def test_load_existing_legacy_format(self, tmp_path):+ """Test loading legacy session format (int IDs)."""+ from messaging.session import SessionStore++ data = {+ "sessions": {+ "s1": {+ "session_id": "s1",+ "chat_id": 123, # Legacy int+ "initial_msg_id": 100, # Legacy int+ "last_msg_id": 101, # Legacy int+ "created_at": "2024-01-01",+ "updated_at": "2024-01-01",+ # platform missing -> should default to telegram+ }+ }+ }++ p = tmp_path / "sessions.json"+ with open(p, "w") as f:+ json.dump(data, f)++ store = SessionStore(storage_path=str(p))+ rec = store.get_session_record("s1")++ assert rec.chat_id == "123" # Converted to str+ assert rec.platform == "telegram" # Defaulted+ assert store.get_session_by_msg("123", "100", "telegram") == "s1"++ def test_load_corrupt_file(self, tmp_path):+ """Test loading corrupt/invalid json file."""+ p = tmp_path / "sessions.json"+ with open(p, "w") as f:+ f.write("{invalid json")++ from messaging.session import SessionStore++ # Should log error and start empty, avoiding crash+ store = SessionStore(storage_path=str(p))+ assert store._sessions == {}++ def test_save_error_handling(self, tmp_path):+ """Test error during save."""+ from messaging.session import SessionStore++ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))++ # Mock open to raise exception+ with patch("builtins.open", side_effect=IOError("Disk full")):+ store.save_session("s1", "c1", "m1")++ # Should log error but not crash. Session should be in memory though.+ assert "s1" in store._sessions+class TestTreeQueueManager:"""Test TreeQueueManager."""