diff --git a/tests/test_history.py b/tests/test_history.py new file mode 100644 index 0000000..1f8bef9 --- /dev/null +++ b/tests/test_history.py @@ -0,0 +1,100 @@ +"""Tests for history learning module.""" + +import pytest +import tempfile +import os +from pathlib import Path + +from shellgenius.history import HistoryStorage, HistoryLearner, HistoryEntry + + +class TestHistoryStorage: + @pytest.fixture + def temp_storage(self): + """Create temporary storage for testing.""" + with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: + f.write("entries: []\nmetadata:\n version: '1.0'") + f.flush() + yield f.name + os.unlink(f.name) + + def test_init_storage(self, temp_storage): + """Test storage initialization.""" + storage = HistoryStorage(temp_storage) + + assert storage.storage_path == temp_storage + + def test_add_and_get_entry(self, temp_storage): + """Test adding and retrieving history entries.""" + storage = HistoryStorage(temp_storage) + + entry = HistoryEntry( + id="test-id", + timestamp="2024-01-01T00:00:00", + description="Test command", + commands=["echo hello"], + shell_type="bash", + ) + + storage.add_entry(entry) + entries = storage.get_entries() + + assert len(entries) == 1 + assert entries[0].description == "Test command" + + def test_search_history(self, temp_storage): + """Test searching history.""" + storage = HistoryStorage(temp_storage) + + entry = HistoryEntry( + id="test-id", + timestamp="2024-01-01T00:00:00", + description="List files command", + commands=["ls -la"], + shell_type="bash", + ) + storage.add_entry(entry) + + results = storage.search("files") + + assert len(results) == 1 + + def test_clear_history(self, temp_storage): + """Test clearing history.""" + storage = HistoryStorage(temp_storage) + + entry = HistoryEntry( + id="test-id", + timestamp="2024-01-01T00:00:00", + description="Test", + commands=["echo"], + shell_type="bash", + ) + storage.add_entry(entry) + + storage.clear() + entries = storage.get_entries() + + assert len(entries) == 0 + + +class TestHistoryLearner: + def test_learn_command(self): + """Test learning from generated command.""" + with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: + f.write("entries: []\nmetadata:\n version: '1.0'") + f.flush() + storage_path = f.name + + try: + with patch('shellgenius.history.get_config') as mock_config: + mock_config.return_value.get.return_value = storage_path + mock_config.return_value.is_history_enabled.return_value = True + + learner = HistoryLearner() + entry = learner.learn("list files", ["ls -la"], "bash") + + assert entry.description == "list files" + assert "ls -la" in entry.commands + finally: + os.unlink(storage_path)