-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_deepwiki_repo_info.py
More file actions
533 lines (417 loc) · 18.3 KB
/
test_deepwiki_repo_info.py
File metadata and controls
533 lines (417 loc) · 18.3 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
"""
Unit tests for the repo_info tool with DeepWiki integration.
Tests cover:
1. DeepWiki success case (GitHub repo)
2. DeepWiki failure/timeout -> fallback to repocards
3. GitLab repository URL handling
4. Non-GitHub/non-GitLab URL handling
5. Various URL format edge cases
Run with: pytest tests/test_deepwiki_repo_info.py -v
"""
from __future__ import annotations
import asyncio
import os
import sys
from pathlib import Path
from unittest.mock import AsyncMock, patch, Mock
import pytest
# Add src to path
src_path = Path(__file__).parent.parent / "src"
if str(src_path) not in sys.path:
sys.path.insert(0, str(src_path))
# Mock the problematic imports before importing the modules
sys.modules["retriever"] = Mock()
sys.modules["retriever.software_doc"] = Mock()
sys.modules["retriever.reranker"] = Mock()
sys.modules["api"] = Mock()
sys.modules["api.pipeline"] = Mock()
from ai_agent.agent.tools.repo_info_tool import (
RepoSummaryInput,
RepoSummaryOutput,
_REPO_INFO_INFLIGHT,
_clear_repo_summary_cache_for_tests,
tool_repo_summary,
)
from ai_agent.agent.tools.deepwiki_tool import (
DeepWikiContentsOutput,
DeepWikiInput,
get_wiki_contents,
)
from ai_agent.agent.utils import coerce_github_url_or_none, _coerce_owner_repo_ref
# ======================== Fixtures ========================
@pytest.fixture
def mock_deepwiki_success():
"""Mock successful DeepWiki response."""
return DeepWikiContentsOutput(
success=True,
contents="# Test Repository\n\nThis is a test repository with documentation from DeepWiki.",
truncated=False,
)
@pytest.fixture
def mock_deepwiki_failure():
"""Mock failed DeepWiki response."""
return DeepWikiContentsOutput(
success=False,
error="DeepWiki request timed out after 60s",
truncated=False,
)
@pytest.fixture
def mock_repocards_response():
"""Mock repocards.get_repo_info response."""
return (
"# Test Repository (via repocards)\n\nREADME content from repocards fallback."
)
@pytest.fixture(autouse=True)
def clear_repo_info_cache_between_tests():
_clear_repo_summary_cache_for_tests()
yield
_clear_repo_summary_cache_for_tests()
# ======================== DeepWiki Tool Tests ========================
@pytest.mark.asyncio
async def test_deepwiki_success():
"""Test successful DeepWiki wiki contents retrieval."""
with patch("ai_agent.agent.tools.deepwiki_tool.MCPServerStreamableHTTP") as mock_server_class:
# Setup mock server
mock_server = AsyncMock()
mock_server.__aenter__ = AsyncMock(return_value=mock_server)
mock_server.__aexit__ = AsyncMock(return_value=None)
mock_server.direct_call_tool = AsyncMock(
return_value=[
"# Repository Documentation\n\nThis is test content from DeepWiki."
]
)
mock_server_class.return_value = mock_server
# Test
result = await get_wiki_contents(DeepWikiInput(url="owner/repo"))
print(result)
assert result.success is True
assert result.contents is not None
assert "Repository Documentation" in result.contents
assert result.error is None
@pytest.mark.asyncio
async def test_deepwiki_timeout():
"""Test DeepWiki timeout handling."""
with patch("ai_agent.agent.tools.deepwiki_tool.MCPServerStreamableHTTP") as mock_server_class:
mock_server = AsyncMock()
mock_server.__aenter__ = AsyncMock(return_value=mock_server)
mock_server.__aexit__ = AsyncMock(return_value=None)
mock_server.direct_call_tool = AsyncMock(side_effect=asyncio.TimeoutError())
mock_server_class.return_value = mock_server
result = await get_wiki_contents(DeepWikiInput(url="owner/repo"))
assert result.success is False
assert "timed out" in result.error.lower()
@pytest.mark.asyncio
async def test_deepwiki_empty_response():
"""Test DeepWiki returning empty/None content."""
with patch("ai_agent.agent.tools.deepwiki_tool.MCPServerStreamableHTTP") as mock_server_class:
mock_server = AsyncMock()
mock_server.__aenter__ = AsyncMock(return_value=mock_server)
mock_server.__aexit__ = AsyncMock(return_value=None)
mock_server.direct_call_tool = AsyncMock(return_value=[])
mock_server_class.return_value = mock_server
result = await get_wiki_contents(DeepWikiInput(url="owner/repo"))
assert result.success is False
assert "No content returned" in result.error
@pytest.mark.asyncio
async def test_deepwiki_connection_error():
"""Test DeepWiki connection errors."""
with patch("ai_agent.agent.tools.deepwiki_tool.MCPServerStreamableHTTP") as mock_server_class:
mock_server_class.side_effect = ConnectionError("Connection refused")
result = await get_wiki_contents(DeepWikiInput(url="owner/repo"))
assert result.success is False
assert "Failed to connect" in result.error
# ======================== URL Coercion Tests ========================
class TestURLCoercion:
"""Test URL parsing and normalization."""
def test_coerce_github_url_owner_repo_format(self):
"""Test owner/repo format."""
result = coerce_github_url_or_none("owner/repo")
assert result == "https://github.com/owner/repo"
def test_coerce_github_url_full_https(self):
"""Test full HTTPS GitHub URL."""
result = coerce_github_url_or_none("https://github.com/owner/repo")
assert result == "https://github.com/owner/repo"
def test_coerce_github_url_with_tree_ref(self):
"""Test GitHub URL with tree/ref."""
result = coerce_github_url_or_none("https://github.com/owner/repo/tree/main")
assert result == "https://github.com/owner/repo#main"
def test_coerce_github_url_with_git_suffix(self):
"""Test GitHub URL with .git suffix."""
result = coerce_github_url_or_none("https://github.com/owner/repo.git")
assert result == "https://github.com/owner/repo"
def test_coerce_github_url_without_scheme(self):
"""Test github.com URL without scheme."""
result = coerce_github_url_or_none("github.com/owner/repo")
assert result == "https://github.com/owner/repo"
def test_coerce_github_url_gitlab_returns_none(self):
"""Test that GitLab URLs return None."""
result = coerce_github_url_or_none("https://gitlab.com/owner/repo")
assert result is None
def test_coerce_github_url_random_url_returns_none(self):
"""Test that non-GitHub URLs return None."""
result = coerce_github_url_or_none("https://example.com/some/path")
assert result is None
def test_coerce_github_url_empty_string_returns_none(self):
"""Test that empty string returns None."""
result = coerce_github_url_or_none("")
assert result is None
def test_coerce_owner_repo_ref_extraction(self):
"""Test _coerce_owner_repo_ref extracts owner, repo, ref correctly."""
owner, repo, ref = _coerce_owner_repo_ref("owner/repo")
assert owner == "owner"
assert repo == "repo"
assert ref is None
def test_coerce_owner_repo_ref_with_tree(self):
"""Test _coerce_owner_repo_ref with tree/branch."""
owner, repo, ref = _coerce_owner_repo_ref(
"https://github.com/owner/repo/tree/develop"
)
assert owner == "owner"
assert repo == "repo"
assert ref == "develop"
def test_coerce_owner_repo_ref_invalid_raises(self):
"""Test _coerce_owner_repo_ref raises on invalid input."""
with pytest.raises(ValueError, match="BAD_REPO_URL"):
_coerce_owner_repo_ref("not-a-valid-repo")
def test_coerce_owner_repo_ref_gitlab_raises(self):
"""Test _coerce_owner_repo_ref raises on GitLab URL."""
with pytest.raises(ValueError, match="BAD_REPO_URL"):
_coerce_owner_repo_ref("https://gitlab.com/owner/repo")
# ======================== Repo Info Tool Tests ========================
@pytest.mark.asyncio
async def test_repo_info_deepwiki_success(mock_deepwiki_success):
"""Test repo_info tool with successful DeepWiki response."""
with patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki:
mock_deepwiki.return_value = mock_deepwiki_success
result = await tool_repo_summary(RepoSummaryInput(url="owner/repo"))
assert isinstance(result, RepoSummaryOutput)
assert result.source == "deepwiki"
assert "DeepWiki" in result.summary
assert result.truncated is False
mock_deepwiki.assert_called_once()
@pytest.mark.asyncio
async def test_repo_info_deepwiki_failure_fallback_to_repocards(
mock_deepwiki_failure, mock_repocards_response
):
"""Test repo_info tool falls back to repocards when DeepWiki fails."""
with (
patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki,
patch(
"ai_agent.agent.tools.repo_info_tool.repocards.get_repo_info"
) as mock_repocards,
):
mock_deepwiki.return_value = mock_deepwiki_failure
mock_repocards.return_value = mock_repocards_response
result = await tool_repo_summary(RepoSummaryInput(url="owner/repo"))
assert isinstance(result, RepoSummaryOutput)
assert result.source == "repocards"
assert "repocards" in result.summary.lower()
mock_deepwiki.assert_called_once()
mock_repocards.assert_called_once()
@pytest.mark.asyncio
async def test_repo_info_deepwiki_exception_fallback():
"""Test repo_info tool handles DeepWiki exceptions and falls back."""
with (
patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki,
patch(
"ai_agent.agent.tools.repo_info_tool.repocards.get_repo_info"
) as mock_repocards,
):
mock_deepwiki.side_effect = Exception("DeepWiki connection error")
mock_repocards.return_value = "# Fallback content"
result = await tool_repo_summary(RepoSummaryInput(url="owner/repo"))
assert result.source == "repocards"
mock_repocards.assert_called_once()
@pytest.mark.asyncio
async def test_repo_info_both_fail_error_response():
"""Test repo_info tool when both DeepWiki and repocards fail."""
with (
patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki,
patch(
"ai_agent.agent.tools.repo_info_tool.repocards.get_repo_info"
) as mock_repocards,
):
mock_deepwiki.return_value = DeepWikiContentsOutput(
success=False, error="DeepWiki failed"
)
mock_repocards.side_effect = Exception("Repocards API error")
result = await tool_repo_summary(RepoSummaryInput(url="owner/repo"))
assert result.source == "error"
assert "Error" in result.summary
assert "Failed to fetch repository information" in result.summary
@pytest.mark.asyncio
async def test_repo_info_truncation():
"""Test that repo_info properly handles content truncation."""
# Create content longer than MAX_CHARS (20000)
long_content = "x" * 25000
with patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki:
mock_deepwiki.return_value = DeepWikiContentsOutput(
success=True, contents=long_content, truncated=True
)
result = await tool_repo_summary(RepoSummaryInput(url="owner/repo"))
assert result.truncated is True
assert result.source == "deepwiki"
@pytest.mark.asyncio
async def test_repo_info_cache_hit_avoids_second_deepwiki_call(mock_deepwiki_success):
"""Second identical repo lookup should be served from cache."""
with patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki:
mock_deepwiki.return_value = mock_deepwiki_success
first = await tool_repo_summary(RepoSummaryInput(url="owner/repo"))
second = await tool_repo_summary(RepoSummaryInput(url="owner/repo"))
assert first.source == "deepwiki"
assert second.source == "deepwiki"
mock_deepwiki.assert_called_once()
@pytest.mark.asyncio
async def test_repo_info_inflight_dedup_for_parallel_calls(mock_deepwiki_success):
"""Parallel identical repo lookups should share one DeepWiki request."""
async def delayed_success(*_args, **_kwargs):
await asyncio.sleep(0.05)
return mock_deepwiki_success
with patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki:
mock_deepwiki.side_effect = delayed_success
out1, out2 = await asyncio.gather(
tool_repo_summary(RepoSummaryInput(url="owner/repo")),
tool_repo_summary(RepoSummaryInput(url="owner/repo")),
)
assert out1.source == "deepwiki"
assert out2.source == "deepwiki"
mock_deepwiki.assert_called_once()
def test_repo_info_clear_helper_clears_inflight_state():
"""Test helper should clear both cache and in-flight maps."""
_REPO_INFO_INFLIGHT["k"] = None # type: ignore[assignment]
_clear_repo_summary_cache_for_tests()
assert _REPO_INFO_INFLIGHT == {}
# ======================== Integration Tests ========================
@pytest.mark.asyncio
@pytest.mark.skipif(
not os.getenv("INTEGRATION_TESTS"),
reason="Skipping integration tests (set INTEGRATION_TESTS=1 to run)",
)
async def test_real_github_repo():
"""Integration test with a real GitHub repository (requires network)."""
result = await tool_repo_summary(
RepoSummaryInput(url="https://github.com/python/cpython")
)
assert result.source in ["deepwiki", "repocards"]
assert len(result.summary) > 0
assert result.summary != ""
# ======================== Edge Cases ========================
class TestEdgeCases:
"""Test edge cases and unusual inputs."""
@pytest.mark.asyncio
async def test_repo_info_with_various_github_formats(self):
"""Test repo_info handles various GitHub URL formats."""
test_cases = [
"owner/repo",
"https://github.com/owner/repo",
"http://github.com/owner/repo",
"github.com/owner/repo",
"https://github.com/owner/repo.git",
"https://github.com/owner/repo/tree/main",
]
with patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki:
mock_deepwiki.return_value = DeepWikiContentsOutput(
success=True, contents="# Test", truncated=False
)
for url in test_cases:
result = await tool_repo_summary(RepoSummaryInput(url=url))
assert result.source == "deepwiki"
assert result.summary is not None
def test_gitlab_url_detection(self):
"""Test that GitLab URLs are properly detected as non-GitHub."""
gitlab_urls = [
"https://gitlab.com/owner/repo",
"gitlab.com/owner/repo",
"https://gitlab.example.com/owner/repo",
]
for url in gitlab_urls:
result = coerce_github_url_or_none(url)
assert result is None, f"Expected None for {url}, got {result}"
def test_other_urls_detection(self):
"""Test that non-GitHub/non-GitLab URLs return None."""
other_urls = [
"https://bitbucket.org/owner/repo",
"https://example.com/some/path",
"https://docs.github.com/",
"not-a-url-at-all",
"http://localhost:3000/repo",
]
for url in other_urls:
result = coerce_github_url_or_none(url)
assert result is None, f"Expected None for {url}, got {result}"
@pytest.mark.asyncio
async def test_empty_url(self):
"""Test handling of empty URL string."""
with (
patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki,
patch(
"ai_agent.agent.tools.repo_info_tool.repocards.get_repo_info"
) as mock_repocards,
):
mock_deepwiki.side_effect = ValueError("BAD_REPO_URL")
mock_repocards.side_effect = Exception("Invalid URL")
result = await tool_repo_summary(RepoSummaryInput(url=""))
assert result.source == "error"
@pytest.mark.asyncio
async def test_url_with_special_characters(self):
"""Test handling of URLs with special characters in repo name."""
with patch(
"ai_agent.agent.tools.repo_info_tool.get_wiki_contents",
new_callable=AsyncMock,
) as mock_deepwiki:
mock_deepwiki.return_value = DeepWikiContentsOutput(
success=True, contents="# Test", truncated=False
)
# Test with hyphens, underscores, dots
result = await tool_repo_summary(
RepoSummaryInput(url="owner/repo-name_with.special")
)
assert result.source == "deepwiki"
# ======================== Performance Tests ========================
@pytest.mark.asyncio
async def test_deepwiki_timeout_duration():
"""Test that DeepWiki timeout is properly configured."""
import time
with patch("ai_agent.agent.tools.deepwiki_tool.MCPServerStreamableHTTP") as mock_server_class:
mock_server = AsyncMock()
mock_server.__aenter__ = AsyncMock(return_value=mock_server)
mock_server.__aexit__ = AsyncMock(return_value=None)
# Simulate a slow response
async def slow_call(*args, **kwargs):
await asyncio.sleep(100) # Longer than timeout
mock_server.direct_call_tool = slow_call
mock_server_class.return_value = mock_server
start = time.time()
result = await get_wiki_contents(DeepWikiInput(url="owner/repo"))
duration = time.time() - start
# Should timeout and not take 100 seconds
assert duration < 65 # Timeout is 60s plus some buffer
assert result.success is False
assert "timed out" in result.error.lower()