File size: 12,200 Bytes
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""Tests for error handling across all services."""

import json
from pathlib import Path
from tempfile import TemporaryDirectory

import pytest

from polyhedra.server import call_tool, get_services
from polyhedra.services.citation_manager import CitationManager
from polyhedra.services.context_manager import ContextManager
from polyhedra.services.rag_service import RAGService


class TestNetworkErrorHandling:
    """Test network error scenarios."""

    @pytest.mark.asyncio
    async def test_invalid_paper_id(self):
        """Should handle invalid paper ID gracefully."""
        result = await call_tool(
            "get_paper",
            {"paper_id": "invalid-nonexistent-id-12345"}
        )
        data = json.loads(result[0].text)
        # May return error or empty result depending on API
        assert isinstance(data, (dict, type(None)))


class TestFileSystemErrorHandling:
    """Test file system error scenarios."""

    @pytest.mark.asyncio
    async def test_read_missing_files(self, tmp_path, monkeypatch):
        """Should report missing files without failing."""
        monkeypatch.chdir(tmp_path)
        
        # Clear service cache
        services = get_services()
        services.clear()

        result = await call_tool(
            "get_context",
            {"paths": ["missing1.md", "missing2.md", "missing3.md"]}
        )
        data = json.loads(result[0].text)
        
        assert "missing" in data
        assert len(data["missing"]) == 3
        assert "missing1.md" in data["missing"]
        print("βœ“ Missing files reported correctly")

    @pytest.mark.asyncio
    async def test_read_mixed_existing_missing(self, tmp_path, monkeypatch):
        """Should read existing files and report missing ones."""
        monkeypatch.chdir(tmp_path)
        
        # Create one file
        (tmp_path / "exists.md").write_text("content", encoding="utf-8")
        
        # Clear service cache
        services = get_services()
        services.clear()

        result = await call_tool(
            "get_context",
            {"paths": ["exists.md", "missing.md"]}
        )
        data = json.loads(result[0].text)
        
        assert "exists.md" in data["contents"]
        assert "missing.md" in data["missing"]
        print("βœ“ Graceful degradation working")

    def test_write_to_nonexistent_directory(self, tmp_path):
        """Should create parent directories automatically."""
        manager = ContextManager(tmp_path)
        
        # Should succeed by creating directories
        bytes_written = manager.write_file(
            "deep/nested/path/file.txt",
            "content"
        )
        
        assert bytes_written > 0
        assert (tmp_path / "deep" / "nested" / "path" / "file.txt").exists()
        print("βœ“ Creates parent directories")


class TestValidationErrorHandling:
    """Test validation error scenarios."""

    def test_invalid_bibtex_format(self, tmp_path):
        """Should reject invalid BibTeX with clear error."""
        manager = CitationManager(tmp_path)
        
        with pytest.raises(ValueError) as exc_info:
            manager.add_entry("invalid bibtex")
        
        # Accepts either error message from different bibtexparser versions
        error_msg = str(exc_info.value)
        assert "Invalid BibTeX" in error_msg or "No valid BibTeX entries" in error_msg
        print("βœ“ Invalid BibTeX rejected with clear error")

    def test_bibtex_missing_required_fields(self, tmp_path):
        """Should reject BibTeX missing ID."""
        manager = CitationManager(tmp_path)
        
        # BibTeX without proper structure
        invalid_bibtex = "@article{}"
        
        with pytest.raises(ValueError) as exc_info:
            manager.add_entry(invalid_bibtex)
        
        error_msg = str(exc_info.value)
        assert "BibTeX" in error_msg or "ID" in error_msg
        print("βœ“ Missing fields detected")

    def test_empty_papers_list_indexing(self, tmp_path):
        """Should reject empty papers list."""
        service = RAGService(tmp_path)
        
        with pytest.raises(ValueError) as exc_info:
            service.index_papers([])
        
        assert "empty" in str(exc_info.value).lower()
        print("βœ“ Empty papers list rejected")

    def test_paper_missing_title(self, tmp_path):
        """Should reject paper without title."""
        service = RAGService(tmp_path)
        
        papers = [
            {"paperId": "123", "abstract": "Test"}
            # Missing title
        ]
        
        with pytest.raises(ValueError) as exc_info:
            service.index_papers(papers)
        
        assert "title" in str(exc_info.value).lower()
        print("βœ“ Missing title detected")

    @pytest.mark.asyncio
    async def test_empty_search_query(self):
        """Should reject empty search query."""
        from polyhedra.services.semantic_scholar import SemanticScholarService
        
        service = SemanticScholarService()
        try:
            with pytest.raises(ValueError) as exc_info:
                await service.search("")
            
            assert "empty" in str(exc_info.value).lower()
            print("βœ“ Empty query rejected")
        finally:
            await service.close()

    @pytest.mark.asyncio
    async def test_invalid_search_limit(self):
        """Should reject invalid limit values."""
        from polyhedra.services.semantic_scholar import SemanticScholarService
        
        service = SemanticScholarService()
        try:
            # Test limit too high
            with pytest.raises(ValueError) as exc_info:
                await service.search("test", limit=101)
            assert "between 1 and 100" in str(exc_info.value)
            
            # Test limit too low
            with pytest.raises(ValueError) as exc_info:
                await service.search("test", limit=0)
            assert "between 1 and 100" in str(exc_info.value)
            
            print("βœ“ Invalid limits rejected")
        finally:
            await service.close()


class TestStateErrorHandling:
    """Test state-related error scenarios."""

    @pytest.mark.asyncio
    async def test_query_before_indexing(self, tmp_path, monkeypatch):
        """Should error when querying before indexing."""
        monkeypatch.chdir(tmp_path)
        
        # Initialize project structure
        (tmp_path / "literature").mkdir()
        (tmp_path / "references.bib").write_text("", encoding="utf-8")
        
        # Clear service cache
        services = get_services()
        services.clear()

        result = await call_tool(
            "query_similar_papers",
            {"query": "test", "k": 5}
        )
        data = json.loads(result[0].text)
        
        assert "error" in data
        assert "not indexed" in data["error"].lower()
        print("βœ“ Query before indexing handled")

    @pytest.mark.asyncio
    async def test_index_missing_papers_file(self, tmp_path, monkeypatch):
        """Should error when papers file doesn't exist."""
        monkeypatch.chdir(tmp_path)
        
        # Clear service cache
        services = get_services()
        services.clear()

        result = await call_tool(
            "index_papers",
            {"papers_path": "literature/papers.json"}
        )
        data = json.loads(result[0].text)
        
        assert "error" in data
        assert "not found" in data["error"].lower()
        print("βœ“ Missing papers file handled")


class TestGracefulDegradation:
    """Test graceful degradation in partial failures."""

    @pytest.mark.asyncio
    async def test_multiple_file_read_partial_success(self, tmp_path, monkeypatch):
        """Should return available files and report missing ones."""
        monkeypatch.chdir(tmp_path)
        
        # Create some files
        (tmp_path / "file1.md").write_text("Content 1", encoding="utf-8")
        (tmp_path / "file2.md").write_text("Content 2", encoding="utf-8")
        (tmp_path / "file3.md").write_text("Content 3", encoding="utf-8")
        
        # Clear service cache
        services = get_services()
        services.clear()

        result = await call_tool(
            "get_context",
            {
                "paths": [
                    "file1.md",
                    "missing1.md",
                    "file2.md",
                    "missing2.md",
                    "file3.md"
                ]
            }
        )
        data = json.loads(result[0].text)
        
        # Should have 3 successful reads
        assert len(data["contents"]) == 3
        assert "file1.md" in data["contents"]
        assert "file2.md" in data["contents"]
        assert "file3.md" in data["contents"]
        
        # Should report 2 missing
        assert len(data["missing"]) == 2
        assert "missing1.md" in data["missing"]
        assert "missing2.md" in data["missing"]
        
        print("βœ“ Partial success handled correctly")

    def test_duplicate_citation_handling(self, tmp_path):
        """Should handle duplicate citations gracefully."""
        manager = CitationManager(tmp_path)
        
        bibtex = """@article{test2021,
    author = {Test, A.},
    title = {Test Paper},
    year = {2021}
}"""
        
        # Add first time
        key1, added1 = manager.add_entry(bibtex)
        assert added1 is True
        
        # Add duplicate
        key2, added2 = manager.add_entry(bibtex)
        assert added2 is False
        assert key1 == key2
        
        print("βœ“ Duplicate citations handled")


class TestErrorMessaging:
    """Test error message clarity and consistency."""

    @pytest.mark.asyncio
    async def test_error_message_format(self, tmp_path, monkeypatch):
        """Error messages should have consistent format."""
        monkeypatch.chdir(tmp_path)
        
        # Clear service cache
        services = get_services()
        services.clear()

        # Test unknown tool
        result = await call_tool("unknown_tool", {})
        data = json.loads(result[0].text)
        
        assert "error" in data
        assert isinstance(data["error"], str)
        assert len(data["error"]) > 0
        print("βœ“ Error message format consistent")

    @pytest.mark.asyncio
    async def test_error_includes_context(self, tmp_path, monkeypatch):
        """Error messages should include helpful context."""
        monkeypatch.chdir(tmp_path)
        
        # Clear service cache
        services = get_services()
        services.clear()

        result = await call_tool(
            "index_papers",
            {"papers_path": "nonexistent.json"}
        )
        data = json.loads(result[0].text)
        
        assert "error" in data
        # Should mention the file path
        assert "nonexistent.json" in data["error"]
        print("βœ“ Error includes context")


class TestErrorRecovery:
    """Test error recovery scenarios."""

    @pytest.mark.asyncio
    async def test_retry_after_error(self, tmp_path, monkeypatch):
        """Should be able to retry after error."""
        monkeypatch.chdir(tmp_path)
        
        # Clear service cache
        services = get_services()
        services.clear()

        # First attempt fails (missing file)
        result1 = await call_tool(
            "index_papers",
            {"papers_path": "papers.json"}
        )
        data1 = json.loads(result1[0].text)
        assert "error" in data1
        
        # Create file
        (tmp_path / "papers.json").write_text(
            json.dumps([
                {
                    "paperId": "1",
                    "title": "Test Paper",
                    "abstract": "Abstract",
                    "authors": ["Test"],
                    "year": 2021
                }
            ]),
            encoding="utf-8"
        )
        
        # Retry succeeds
        result2 = await call_tool(
            "index_papers",
            {"papers_path": "papers.json"}
        )
        data2 = json.loads(result2[0].text)
        assert data2.get("success") is True
        
        print("βœ“ Retry after error works")