forked from yusufkaraaslan/Skill_Seekers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_guide_enhancer.py
More file actions
619 lines (509 loc) · 21.7 KB
/
test_guide_enhancer.py
File metadata and controls
619 lines (509 loc) · 21.7 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#!/usr/bin/env python3
"""
Comprehensive tests for GuideEnhancer (C3.3 AI Enhancement)
Tests dual-mode AI enhancement for how-to guides:
- API mode (Claude API)
- LOCAL mode (Claude Code CLI)
- Auto mode detection
- All 5 enhancement methods
"""
import json
import os
from unittest.mock import MagicMock, Mock, patch
import pytest
from skill_seekers.cli.guide_enhancer import (
GuideEnhancer,
PrerequisiteItem,
StepEnhancement,
TroubleshootingItem,
)
class TestGuideEnhancerModeDetection:
"""Test mode detection logic"""
def test_auto_mode_with_api_key(self):
"""Test auto mode detects API when key present and library available"""
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}),
patch("skill_seekers.cli.guide_enhancer.ANTHROPIC_AVAILABLE", True),
patch("skill_seekers.cli.guide_enhancer.anthropic", create=True) as mock_anthropic,
):
mock_anthropic.Anthropic = Mock()
enhancer = GuideEnhancer(mode="auto")
# Will be 'api' if library available, otherwise 'local' or 'none'
assert enhancer.mode in ["api", "local", "none"]
def test_auto_mode_without_api_key(self):
"""Test auto mode falls back to LOCAL when no API key"""
with patch.dict(os.environ, {}, clear=True):
if "ANTHROPIC_API_KEY" in os.environ:
del os.environ["ANTHROPIC_API_KEY"]
enhancer = GuideEnhancer(mode="auto")
assert enhancer.mode in ["local", "none"]
def test_explicit_api_mode(self):
"""Test explicit API mode"""
enhancer = GuideEnhancer(mode="api")
assert enhancer.mode in ["api", "none"] # none if no API key
def test_explicit_local_mode(self):
"""Test explicit LOCAL mode"""
enhancer = GuideEnhancer(mode="local")
assert enhancer.mode in ["local", "none"] # none if no claude CLI
def test_explicit_none_mode(self):
"""Test explicit none mode"""
enhancer = GuideEnhancer(mode="none")
assert enhancer.mode == "none"
def test_claude_cli_check(self):
"""Test Claude CLI availability check"""
enhancer = GuideEnhancer(mode="local")
# Should either detect claude or fall back to api/none
assert enhancer.mode in ["local", "api", "none"]
class TestGuideEnhancerStepDescriptions:
"""Test step description enhancement"""
def test_enhance_step_descriptions_empty_list(self):
"""Test with empty steps list"""
enhancer = GuideEnhancer(mode="none")
steps = []
result = enhancer.enhance_step_descriptions(steps)
assert result == []
def test_enhance_step_descriptions_none_mode(self):
"""Test step descriptions in none mode returns empty"""
enhancer = GuideEnhancer(mode="none")
steps = [
{
"description": "scraper.scrape(url)",
"code": "result = scraper.scrape(url)",
}
]
result = enhancer.enhance_step_descriptions(steps)
assert result == []
@patch.object(GuideEnhancer, "_call_claude_api")
def test_enhance_step_descriptions_api_mode(self, mock_call):
"""Test step descriptions with API mode"""
mock_call.return_value = json.dumps(
{
"step_descriptions": [
{
"step_index": 0,
"explanation": "Initialize the scraper with the target URL",
"variations": ["Use async scraper for better performance"],
}
]
}
)
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}),
patch("skill_seekers.cli.guide_enhancer.ANTHROPIC_AVAILABLE", True),
patch("skill_seekers.cli.guide_enhancer.anthropic", create=True) as mock_anthropic,
):
mock_anthropic.Anthropic = Mock()
enhancer = GuideEnhancer(mode="api")
if enhancer.mode != "api":
pytest.skip("API mode not available")
enhancer.client = Mock() # Mock the client
steps = [
{
"description": "scraper.scrape(url)",
"code": "result = scraper.scrape(url)",
}
]
result = enhancer.enhance_step_descriptions(steps)
assert len(result) == 1
assert isinstance(result[0], StepEnhancement)
assert result[0].step_index == 0
assert "Initialize" in result[0].explanation
assert len(result[0].variations) == 1
def test_enhance_step_descriptions_malformed_json(self):
"""Test handling of malformed JSON response"""
enhancer = GuideEnhancer(mode="none")
with patch.object(enhancer, "_call_ai", return_value="invalid json"):
steps = [{"description": "test", "code": "code"}]
result = enhancer.enhance_step_descriptions(steps)
assert result == []
class TestGuideEnhancerTroubleshooting:
"""Test troubleshooting enhancement"""
def test_enhance_troubleshooting_none_mode(self):
"""Test troubleshooting in none mode"""
enhancer = GuideEnhancer(mode="none")
guide_data = {
"title": "Test Guide",
"steps": [{"description": "test", "code": "code"}],
"language": "python",
}
result = enhancer.enhance_troubleshooting(guide_data)
assert result == []
@patch.object(GuideEnhancer, "_call_claude_api")
def test_enhance_troubleshooting_api_mode(self, mock_call):
"""Test troubleshooting with API mode"""
mock_call.return_value = json.dumps(
{
"troubleshooting": [
{
"problem": "ImportError: No module named requests",
"symptoms": ["Import fails", "Module not found error"],
"diagnostic_steps": ["Check pip list", "Verify virtual env"],
"solution": "Run: pip install requests",
}
]
}
)
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}),
patch("skill_seekers.cli.guide_enhancer.ANTHROPIC_AVAILABLE", True),
patch("skill_seekers.cli.guide_enhancer.anthropic", create=True) as mock_anthropic,
):
mock_anthropic.Anthropic = Mock()
enhancer = GuideEnhancer(mode="api")
if enhancer.mode != "api":
pytest.skip("API mode not available")
enhancer.client = Mock()
guide_data = {
"title": "Test Guide",
"steps": [{"description": "import requests", "code": "import requests"}],
"language": "python",
}
result = enhancer.enhance_troubleshooting(guide_data)
assert len(result) == 1
assert isinstance(result[0], TroubleshootingItem)
assert "ImportError" in result[0].problem
assert len(result[0].symptoms) == 2
assert len(result[0].diagnostic_steps) == 2
assert "pip install" in result[0].solution
class TestGuideEnhancerPrerequisites:
"""Test prerequisite enhancement"""
def test_enhance_prerequisites_empty_list(self):
"""Test with empty prerequisites"""
enhancer = GuideEnhancer(mode="none")
result = enhancer.enhance_prerequisites([])
assert result == []
def test_enhance_prerequisites_none_mode(self):
"""Test prerequisites in none mode"""
enhancer = GuideEnhancer(mode="none")
prereqs = ["requests", "beautifulsoup4"]
result = enhancer.enhance_prerequisites(prereqs)
assert result == []
@patch.object(GuideEnhancer, "_call_claude_api")
def test_enhance_prerequisites_api_mode(self, mock_call):
"""Test prerequisites with API mode"""
mock_call.return_value = json.dumps(
{
"prerequisites_detailed": [
{
"name": "requests",
"why": "HTTP client for making web requests",
"setup": "pip install requests",
},
{
"name": "beautifulsoup4",
"why": "HTML/XML parser for web scraping",
"setup": "pip install beautifulsoup4",
},
]
}
)
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}),
patch("skill_seekers.cli.guide_enhancer.ANTHROPIC_AVAILABLE", True),
patch("skill_seekers.cli.guide_enhancer.anthropic", create=True) as mock_anthropic,
):
mock_anthropic.Anthropic = Mock()
enhancer = GuideEnhancer(mode="api")
if enhancer.mode != "api":
pytest.skip("API mode not available")
enhancer.client = Mock()
prereqs = ["requests", "beautifulsoup4"]
result = enhancer.enhance_prerequisites(prereqs)
assert len(result) == 2
assert isinstance(result[0], PrerequisiteItem)
assert result[0].name == "requests"
assert "HTTP client" in result[0].why
assert "pip install" in result[0].setup
class TestGuideEnhancerNextSteps:
"""Test next steps enhancement"""
def test_enhance_next_steps_none_mode(self):
"""Test next steps in none mode"""
enhancer = GuideEnhancer(mode="none")
guide_data = {"title": "Test Guide", "description": "Test"}
result = enhancer.enhance_next_steps(guide_data)
assert result == []
@patch.object(GuideEnhancer, "_call_claude_api")
def test_enhance_next_steps_api_mode(self, mock_call):
"""Test next steps with API mode"""
mock_call.return_value = json.dumps(
{
"next_steps": [
"How to handle async workflows",
"How to add error handling",
"How to implement caching",
]
}
)
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}),
patch("skill_seekers.cli.guide_enhancer.ANTHROPIC_AVAILABLE", True),
patch("skill_seekers.cli.guide_enhancer.anthropic", create=True) as mock_anthropic,
):
mock_anthropic.Anthropic = Mock()
enhancer = GuideEnhancer(mode="api")
if enhancer.mode != "api":
pytest.skip("API mode not available")
enhancer.client = Mock()
guide_data = {
"title": "How to Scrape Docs",
"description": "Basic scraping",
}
result = enhancer.enhance_next_steps(guide_data)
assert len(result) == 3
assert "async" in result[0].lower()
assert "error" in result[1].lower()
class TestGuideEnhancerUseCases:
"""Test use case enhancement"""
def test_enhance_use_cases_none_mode(self):
"""Test use cases in none mode"""
enhancer = GuideEnhancer(mode="none")
guide_data = {"title": "Test Guide", "description": "Test"}
result = enhancer.enhance_use_cases(guide_data)
assert result == []
@patch.object(GuideEnhancer, "_call_claude_api")
def test_enhance_use_cases_api_mode(self, mock_call):
"""Test use cases with API mode"""
mock_call.return_value = json.dumps(
{
"use_cases": [
"Use when you need to automate documentation extraction",
"Ideal for building knowledge bases from technical docs",
]
}
)
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}),
patch("skill_seekers.cli.guide_enhancer.ANTHROPIC_AVAILABLE", True),
patch("skill_seekers.cli.guide_enhancer.anthropic", create=True) as mock_anthropic,
):
mock_anthropic.Anthropic = Mock()
enhancer = GuideEnhancer(mode="api")
if enhancer.mode != "api":
pytest.skip("API mode not available")
enhancer.client = Mock()
guide_data = {
"title": "How to Scrape Docs",
"description": "Documentation scraping",
}
result = enhancer.enhance_use_cases(guide_data)
assert len(result) == 2
assert "automate" in result[0].lower()
assert "knowledge base" in result[1].lower()
class TestGuideEnhancerFullWorkflow:
"""Test complete guide enhancement workflow"""
def test_enhance_guide_none_mode(self):
"""Test full guide enhancement in none mode"""
enhancer = GuideEnhancer(mode="none")
guide_data = {
"title": "How to Scrape Documentation",
"steps": [
{"description": "Import libraries", "code": "import requests"},
{"description": "Create scraper", "code": "scraper = Scraper()"},
],
"language": "python",
"prerequisites": ["requests"],
"description": "Basic scraping guide",
}
result = enhancer.enhance_guide(guide_data)
# In none mode, should return original guide
assert result["title"] == guide_data["title"]
assert len(result["steps"]) == 2
@patch.object(GuideEnhancer, "_call_claude_api")
def test_enhance_guide_api_mode_success(self, mock_call):
"""Test successful full guide enhancement via API"""
mock_call.return_value = json.dumps(
{
"step_descriptions": [
{
"step_index": 0,
"explanation": "Import required libraries",
"variations": [],
},
{
"step_index": 1,
"explanation": "Initialize scraper instance",
"variations": [],
},
],
"troubleshooting": [
{
"problem": "Import error",
"symptoms": ["Module not found"],
"diagnostic_steps": ["Check installation"],
"solution": "pip install requests",
}
],
"prerequisites_detailed": [
{
"name": "requests",
"why": "HTTP client",
"setup": "pip install requests",
}
],
"next_steps": ["How to add authentication"],
"use_cases": ["Automate documentation extraction"],
}
)
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}),
patch("skill_seekers.cli.guide_enhancer.ANTHROPIC_AVAILABLE", True),
patch("skill_seekers.cli.guide_enhancer.anthropic", create=True) as mock_anthropic,
):
mock_anthropic.Anthropic = Mock()
enhancer = GuideEnhancer(mode="api")
if enhancer.mode != "api":
pytest.skip("API mode not available")
enhancer.client = Mock()
guide_data = {
"title": "How to Scrape Documentation",
"steps": [
{"description": "Import libraries", "code": "import requests"},
{"description": "Create scraper", "code": "scraper = Scraper()"},
],
"language": "python",
"prerequisites": ["requests"],
"description": "Basic scraping guide",
}
result = enhancer.enhance_guide(guide_data)
# Check enhancements were applied
assert "step_enhancements" in result
assert "troubleshooting_detailed" in result
assert "prerequisites_detailed" in result
assert "next_steps_detailed" in result
assert "use_cases" in result
def test_enhance_guide_error_fallback(self):
"""Test graceful fallback on enhancement error"""
enhancer = GuideEnhancer(mode="none")
with patch.object(enhancer, "enhance_guide", side_effect=Exception("API error")):
guide_data = {
"title": "Test",
"steps": [],
"language": "python",
"prerequisites": [],
"description": "Test",
}
# Should not raise exception - graceful fallback
try:
enhancer = GuideEnhancer(mode="none")
result = enhancer.enhance_guide(guide_data)
# In none mode with error, returns original
assert result["title"] == guide_data["title"]
except Exception:
pytest.fail("Should handle errors gracefully")
class TestGuideEnhancerLocalMode:
"""Test LOCAL mode (Claude Code CLI)"""
@patch("subprocess.run")
def test_call_claude_local_success(self, mock_run):
"""Test successful LOCAL mode call"""
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps(
{
"step_descriptions": [],
"troubleshooting": [],
"prerequisites_detailed": [],
"next_steps": [],
"use_cases": [],
}
),
)
enhancer = GuideEnhancer(mode="local")
if enhancer.mode == "local":
prompt = "Test prompt"
result = enhancer._call_claude_local(prompt)
assert result is not None
assert mock_run.called
@patch("subprocess.run")
def test_call_claude_local_timeout(self, mock_run):
"""Test LOCAL mode timeout handling"""
from subprocess import TimeoutExpired
mock_run.side_effect = TimeoutExpired("claude", 300)
enhancer = GuideEnhancer(mode="local")
if enhancer.mode == "local":
prompt = "Test prompt"
result = enhancer._call_claude_local(prompt)
assert result is None
class TestGuideEnhancerPromptGeneration:
"""Test prompt generation"""
def test_create_enhancement_prompt(self):
"""Test comprehensive enhancement prompt generation"""
enhancer = GuideEnhancer(mode="none")
guide_data = {
"title": "How to Test",
"steps": [{"description": "Write test", "code": "def test_example(): pass"}],
"language": "python",
"prerequisites": ["pytest"],
}
prompt = enhancer._create_enhancement_prompt(guide_data)
assert "How to Test" in prompt
assert "pytest" in prompt
assert "STEP_DESCRIPTIONS" in prompt
assert "TROUBLESHOOTING" in prompt
assert "PREREQUISITES" in prompt
assert "NEXT_STEPS" in prompt
assert "USE_CASES" in prompt
assert "JSON" in prompt
def test_format_steps_for_prompt(self):
"""Test step formatting for prompts"""
enhancer = GuideEnhancer(mode="none")
steps = [
{"description": "Import", "code": "import requests"},
{"description": "Create", "code": "obj = Object()"},
]
formatted = enhancer._format_steps_for_prompt(steps)
assert "Step 1" in formatted
assert "Step 2" in formatted
assert "import requests" in formatted
assert "obj = Object()" in formatted
def test_format_steps_empty(self):
"""Test formatting empty steps list"""
enhancer = GuideEnhancer(mode="none")
formatted = enhancer._format_steps_for_prompt([])
assert formatted == "No steps provided"
class TestGuideEnhancerResponseParsing:
"""Test response parsing"""
def test_parse_enhancement_response_valid_json(self):
"""Test parsing valid JSON response"""
enhancer = GuideEnhancer(mode="none")
response = json.dumps(
{
"step_descriptions": [{"step_index": 0, "explanation": "Test", "variations": []}],
"troubleshooting": [],
"prerequisites_detailed": [],
"next_steps": [],
"use_cases": [],
}
)
guide_data = {
"title": "Test",
"steps": [{"description": "Test", "code": "test"}],
"language": "python",
}
result = enhancer._parse_enhancement_response(response, guide_data)
assert "step_enhancements" in result
assert len(result["step_enhancements"]) == 1
def test_parse_enhancement_response_with_extra_text(self):
"""Test parsing JSON embedded in text"""
enhancer = GuideEnhancer(mode="none")
json_data = {
"step_descriptions": [],
"troubleshooting": [],
"prerequisites_detailed": [],
"next_steps": [],
"use_cases": [],
}
response = f"Here's the result:\n{json.dumps(json_data)}\nDone!"
guide_data = {"title": "Test", "steps": [], "language": "python"}
result = enhancer._parse_enhancement_response(response, guide_data)
# Should extract JSON successfully
assert "title" in result
def test_parse_enhancement_response_invalid_json(self):
"""Test handling invalid JSON"""
enhancer = GuideEnhancer(mode="none")
response = "This is not valid JSON"
guide_data = {"title": "Test", "steps": [], "language": "python"}
result = enhancer._parse_enhancement_response(response, guide_data)
# Should return original guide_data on parse error
assert result["title"] == "Test"
if __name__ == "__main__":
pytest.main([__file__, "-v"])