Files
skill-seekers-reference/tests/test_issue_219_e2e.py
yusyus 6d37e43b83 feat: Grand Unification — one command, one interface, direct converters (#346)
* fix: resolve 8 pipeline bugs found during skill quality review

- Fix 0 APIs extracted from documentation by enriching summary.json
  with individual page file content before conflict detection
- Fix all "Unknown" entries in merged_api.md by injecting dict keys
  as API names and falling back to AI merger field names
- Fix frontmatter using raw slugs instead of config name by
  normalizing frontmatter after SKILL.md generation
- Fix leaked absolute filesystem paths in patterns/index.md by
  stripping .skillseeker-cache repo clone prefixes
- Fix ARCHITECTURE.md file count always showing "1 files" by
  counting files per language from code_analysis data
- Fix YAML parse errors on GitHub Actions workflows by converting
  boolean keys (on: true) to strings
- Fix false React/Vue.js framework detection in C# projects by
  filtering web frameworks based on primary language
- Improve how-to guide generation by broadening workflow example
  filter to include setup/config examples with sufficient complexity
- Fix test_git_sources_e2e failures caused by git init default
  branch being 'main' instead of 'master'

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address 6 review issues in ExecutionContext implementation

Fixes from code review:

1. Mode resolution (#3 critical): _args_to_data no longer unconditionally
   overwrites mode. Only writes mode="api" when --api-key explicitly passed.
   Env-var-based mode detection moved to _default_data() as lowest priority.

2. Re-initialization warning (#4): initialize() now logs debug message
   when called a second time instead of silently returning stale instance.

3. _raw_args preserved in override (#5): temp context now copies _raw_args
   from parent so get_raw() works correctly inside override blocks.

4. test_local_mode_detection env cleanup (#7): test now saves/restores
   API key env vars to prevent failures when ANTHROPIC_API_KEY is set.

5. _load_config_file error handling (#8): wraps FileNotFoundError and
   JSONDecodeError with user-friendly ValueError messages.

6. Lint fixes: added logging import, fixed Generator import from
   collections.abc, fixed AgentClient return type annotation.

Remaining P2/P3 items (documented, not blocking):
- Lock TOCTOU in override() — safe on CPython, needs fix for no-GIL
- get() reads _instance without lock — same CPython caveat
- config_path not stored on instance
- AnalysisSettings.depth not Literal constrained

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address all remaining P2/P3 review issues in ExecutionContext

1. Thread safety: get() now acquires _lock before reading _instance (#2)
2. Thread safety: override() saves/restores _initialized flag to prevent
   re-init during override blocks (#10)
3. Config path stored: _config_path PrivateAttr + config_path property (#6)
4. Literal validation: AnalysisSettings.depth now uses
   Literal["surface", "deep", "full"] — rejects invalid values (#9)
5. Test updated: test_analysis_depth_choices now expects ValidationError
   for invalid depth, added test_analysis_depth_valid_choices
6. Lint cleanup: removed unused imports, fixed whitespace in tests

All 10 previously reported issues now resolved.
26 tests pass, lint clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: restore 5 truncated scrapers, migrate unified_scraper, fix context init

5 scrapers had main() truncated with "# Original main continues here..."
after Kimi's migration — business logic was never connected:
- html_scraper.py — restored HtmlToSkillConverter extraction + build
- pptx_scraper.py — restored PptxToSkillConverter extraction + build
- confluence_scraper.py — restored ConfluenceToSkillConverter with 3 modes
- notion_scraper.py — restored NotionToSkillConverter with 4 sources
- chat_scraper.py — restored ChatToSkillConverter extraction + build

unified_scraper.py — migrated main() to context-first pattern with argv fallback

Fixed context initialization chain:
- main.py no longer initializes ExecutionContext (was stealing init from commands)
- create_command.py now passes config_path from source_info.parsed
- execution_context.py handles SourceInfo.raw_input (not raw_source)

All 18 scrapers now genuinely migrated. 26 tests pass, lint clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: resolve 7 data flow conflicts between ExecutionContext and legacy paths

Critical fixes (CLI args silently lost):
- unified_scraper Phase 6: reads ctx.enhancement.level instead of raw JSON
  when args=None (#3, #4)
- unified_scraper Phase 6 agent: reads ctx.enhancement.agent instead of
  3 independent env var lookups (#5)
- doc_scraper._run_enhancement: uses agent_client.api_key instead of raw
  os.environ.get() — respects config file api_key (#1)

Important fixes:
- main._handle_analyze_command: populates _fake_args from ExecutionContext
  so --agent and --api-key aren't lost in analyze→enhance path (#6)
- doc_scraper type annotations: replaced forward refs with Any to avoid
  F821 undefined name errors

All changes include RuntimeError fallback for backward compatibility when
ExecutionContext isn't initialized.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: 3 crashes + 1 stub in migrated scrapers found by deep scan

1. github_scraper.py: args.scrape_only and args.enhance_level crash when
   args=None (context path). Guarded with if args and getattr(). Also
   fixed agent fallback to read ctx.enhancement.agent.

2. codebase_scraper.py: args.output and args.skip_api_reference crash in
   summary block when args=None. Replaced with output_dir local var and
   ctx.analysis.skip_api_reference.

3. epub_scraper.py: main() was still a stub ending with "# Rest of main()
   continues..." — restored full extraction + build + enhancement logic
   using ctx values exclusively.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: complete ExecutionContext migration for remaining scrapers

Kimi's Phase 4 scraper migrations + Claude's review fixes.
All 18 scrapers now use context-first pattern with argv fallback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: Phase 1 — ExecutionContext.get() always returns context (no RuntimeError)

get() now returns a default context instead of raising RuntimeError when
not explicitly initialized. This eliminates the need for try/except
RuntimeError blocks in all 18 scrapers.

Components can always call ExecutionContext.get() safely — it returns
defaults if not initialized, or the explicitly initialized instance.

Updated tests: test_get_returns_defaults_when_not_initialized,
test_reset_clears_instance (no longer expects RuntimeError).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: Phase 2a-c — remove 16 individual scraper CLI commands

Removed individual scraper commands from:
- COMMAND_MODULES in main.py (16 entries: scrape, github, pdf, word,
  epub, video, jupyter, html, openapi, asciidoc, pptx, rss, manpage,
  confluence, notion, chat)
- pyproject.toml entry points (16 skill-seekers-<type> binaries)
- parsers/__init__.py (16 parser registrations)

All source types now accessed via: skill-seekers create <source>
Kept: create, unified, analyze, enhance, package, upload, install,
      install-agent, config, doctor, and utility commands.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: create SkillConverter base class + converter registry

New base interface that all 17 converters will inherit:
- SkillConverter.run() — extract + build (same call for all types)
- SkillConverter.extract() — override in subclass
- SkillConverter.build_skill() — override in subclass
- get_converter(source_type, config) — factory from registry
- CONVERTER_REGISTRY — maps source type → (module, class)

create_command will use get_converter() instead of _call_module().

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: Grand Unification — one command, one interface, direct converters

Complete the Grand Unification refactor: `skill-seekers create` is now
the single entry point for all 18 source types. Individual scraper CLI
commands (scrape, github, pdf, analyze, unified, etc.) are removed.

## Architecture changes

- **18 SkillConverter subclasses**: Every scraper now inherits SkillConverter
  with extract() + build_skill() + SOURCE_TYPE. Factory via get_converter().
- **create_command.py rewritten**: _build_config() constructs config dicts
  from ExecutionContext for each source type. Direct converter.run() calls
  replace the old _build_argv() + sys.argv swap + _call_module() machinery.
- **main.py simplified**: create command bypasses _reconstruct_argv entirely,
  calls CreateCommand(args).execute() directly. analyze/unified commands
  removed (create handles both via auto-detection).
- **CreateParser mode="all"**: Top-level parser now accepts all 120+ flags
  (--browser, --max-pages, --depth, etc.) since create is the only entry.
- **Centralized enhancement**: Runs once in create_command after converter,
  not duplicated in each scraper.
- **MCP tools use converters**: 5 scraping tools call get_converter()
  directly instead of subprocess. Config type auto-detected from keys.
- **ConfigValidator → UniSkillConfigValidator**: Renamed with backward-
  compat alias.
- **Data flow**: AgentClient + LocalSkillEnhancer read ExecutionContext
  first, env vars as fallback.

## What was removed

- main() from all 18 scraper files (~3400 lines)
- 18 CLI commands from COMMAND_MODULES + pyproject.toml entry points
- analyze + unified parsers from parser registry
- _build_argv, _call_module, _SKIP_ARGS, _DEST_TO_FLAG, all _route_*()
- setup_argument_parser, get_configuration, _check_deprecated_flags
- Tests referencing removed commands/functions

## Net impact

51 files changed, ~6000 lines removed. 2996 tests pass, 0 failures.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: review fixes for Grand Unification PR

- Add autouse conftest fixture to reset ExecutionContext singleton between tests
- Replace hardcoded defaults in _is_explicitly_set() with parser-derived defaults
- Upgrade ExecutionContext double-init log from debug to info
- Use logger.exception() in SkillConverter.run() to preserve tracebacks
- Fix docstring "17 types" → "18 types" in skill_converter.py
- DRY up 10 copy-paste help handlers into dict + loop (~100 lines removed)
- Fix 2 CI workflows still referencing removed `skill-seekers scrape` command
- Remove broken pyproject.toml entry point for codebase_scraper:main

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: resolve 12 logic/flow issues found in deep review

Critical fixes:
- UnifiedScraper.run(): replace sys.exit(1) with return 1, add return 0
- doc_scraper: use ExecutionContext.get() when already initialized instead
  of re-calling initialize() which silently discards new config
- unified_scraper: define enhancement_config before try/except to prevent
  UnboundLocalError in LOCAL enhancement timeout read

Important fixes:
- override(): cleaner tuple save/restore for singleton swap
- --agent without --api-key now sets mode="local" so env API key doesn't
  override explicit agent choice
- Remove DeprecationWarning from _reconstruct_argv (fires on every
  non-create command in production)
- Rewrite scrape_generic_tool to use get_converter() instead of subprocess
  calls to removed main() functions
- SkillConverter.run() checks build_skill() return value, returns 1 if False
- estimate_pages_tool uses -m module invocation instead of .py file path

Low-priority fixes:
- get_converter() raises descriptive ValueError on class name typo
- test_default_values: save/clear API key env vars before asserting mode
- test_get_converter_pdf: fix config key "path" → "pdf_path"

3056 passed, 4 failed (pre-existing dep version issues), 32 skipped.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: update MCP server tests to mock converter instead of subprocess

scrape_docs_tool now uses get_converter() + _run_converter() in-process
instead of run_subprocess_with_streaming. Update 4 TestScrapeDocsTool
tests to mock the converter layer instead of the removed subprocess path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: YusufKaraaslanSpyke <yusuf@spykegames.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 23:00:52 +03:00

332 lines
12 KiB
Python

#!/usr/bin/env python3
"""
End-to-End Tests for Issue #219 - All Three Problems
Tests verify complete fixes for:
1. Large file encoding error (ccxt/ccxt 1.4MB CHANGELOG)
2. Missing --enhance-local CLI flag
3. Custom API endpoint support (ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN)
"""
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock, patch
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
# Check if anthropic is available
try:
import anthropic # noqa: F401
ANTHROPIC_AVAILABLE = True
except ImportError:
ANTHROPIC_AVAILABLE = False
class TestIssue219Problem1LargeFiles(unittest.TestCase):
"""E2E Test: Problem #1 - Large file download via download_url"""
def setUp(self):
"""Set up test environment"""
try:
from github import Github, GithubException # noqa: F401
self.PYGITHUB_AVAILABLE = True
except ImportError:
self.PYGITHUB_AVAILABLE = False
if not self.PYGITHUB_AVAILABLE:
self.skipTest("PyGithub not installed")
from skill_seekers.cli.github_scraper import GitHubScraper
self.GitHubScraper = GitHubScraper
def test_large_file_extraction_end_to_end(self):
"""E2E: Verify large files (encoding='none') are downloaded via URL"""
config = {"repo": "ccxt/ccxt", "name": "ccxt", "github_token": None}
# Mock large CHANGELOG (1.4MB, encoding="none")
mock_content = Mock()
mock_content.type = "file"
mock_content.encoding = "none" # This is what GitHub API returns for large files
mock_content.size = 1388271
mock_content.download_url = (
"https://raw.githubusercontent.com/ccxt/ccxt/master/CHANGELOG.md"
)
with patch("skill_seekers.cli.github_scraper.Github"):
scraper = self.GitHubScraper(config)
scraper.repo = Mock()
scraper.repo.get_contents.return_value = mock_content
# Mock requests.get for download
with patch("requests.get") as mock_requests:
mock_response = Mock()
mock_response.text = "# CCXT Changelog\n\n## v4.4.20\n- Bug fixes"
mock_response.raise_for_status = Mock()
mock_requests.return_value = mock_response
# Call _extract_changelog (full workflow)
scraper._extract_changelog()
# VERIFY: download_url was called
mock_requests.assert_called_once_with(
"https://raw.githubusercontent.com/ccxt/ccxt/master/CHANGELOG.md",
timeout=30,
)
# VERIFY: CHANGELOG was extracted successfully
self.assertIn("changelog", scraper.extracted_data)
self.assertIn("Bug fixes", scraper.extracted_data["changelog"])
self.assertEqual(scraper.extracted_data["changelog"], mock_response.text)
def test_large_file_fallback_on_error(self):
"""E2E: Verify graceful handling if download_url fails"""
config = {"repo": "test/repo", "name": "test", "github_token": None}
# Mock large file without download_url
mock_content = Mock()
mock_content.type = "file"
mock_content.encoding = "none"
mock_content.size = 2000000
mock_content.download_url = None # Missing download URL
with patch("skill_seekers.cli.github_scraper.Github"):
scraper = self.GitHubScraper(config)
scraper.repo = Mock()
scraper.repo.get_contents.return_value = mock_content
# Should return None gracefully
result = scraper._get_file_content("CHANGELOG.md")
self.assertIsNone(result)
# Should not crash
scraper._extract_changelog()
self.assertEqual(scraper.extracted_data["changelog"], "")
class TestIssue219Problem2CLIFlags(unittest.TestCase):
"""E2E Test: Problem #2 - CLI flags working through create command"""
def test_create_command_has_enhancement_flags(self):
"""E2E: Verify --enhance-level flag exists in create command help"""
result = subprocess.run(
["skill-seekers", "create", "--help"], capture_output=True, text=True
)
# VERIFY: Command succeeds
self.assertEqual(result.returncode, 0, "create --help should succeed")
# VERIFY: Enhancement flags present
self.assertIn("--enhance-level", result.stdout, "Missing --enhance-level flag")
def test_enhance_level_flag_accepted_by_create(self):
"""E2E: Verify --enhance-level flag is accepted by create command parser"""
from skill_seekers.cli.main import create_parser
parser = create_parser()
# VERIFY: Parsing succeeds without "unrecognized arguments" error
try:
args = parser.parse_args(["create", "owner/repo", "--enhance-level", "2"])
self.assertEqual(args.enhance_level, 2, "Flag should be parsed as 2")
except SystemExit as e:
self.fail(f"Argument parsing failed with: {e}")
def test_github_scraper_class_accepts_enhance_level(self):
"""E2E: Verify GitHubScraper config accepts enhance_level."""
from skill_seekers.cli.github_scraper import GitHubScraper
config = {
"repo": "test/test",
"name": "test",
"github_token": None,
"enhance_level": 2,
}
with patch("skill_seekers.cli.github_scraper.Github"):
scraper = GitHubScraper(config)
# Just verify it doesn't crash with enhance_level in config
self.assertIsNotNone(scraper)
@unittest.skipIf(not ANTHROPIC_AVAILABLE, "anthropic package not installed")
class TestIssue219Problem3CustomAPIEndpoints(unittest.TestCase):
"""E2E Test: Problem #3 - Custom API endpoint support"""
def setUp(self):
"""Set up test environment"""
self.temp_dir = tempfile.mkdtemp()
self.skill_dir = Path(self.temp_dir) / "test_skill"
self.skill_dir.mkdir()
# Create minimal SKILL.md
(self.skill_dir / "SKILL.md").write_text("# Test Skill\n", encoding="utf-8")
# Create references directory
refs_dir = self.skill_dir / "references"
refs_dir.mkdir()
(refs_dir / "index.md").write_text("# Index\n", encoding="utf-8")
def tearDown(self):
"""Clean up test environment"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_anthropic_base_url_support(self):
"""E2E: Verify ANTHROPIC_BASE_URL environment variable is supported"""
try:
from skill_seekers.cli.enhance_skill import SkillEnhancer
except ImportError:
self.skipTest("anthropic package not installed")
# Set custom base URL
custom_url = "http://localhost:3000"
with (
patch.dict(
os.environ,
{"ANTHROPIC_API_KEY": "test-key-123", "ANTHROPIC_BASE_URL": custom_url},
),
patch("skill_seekers.cli.enhance_skill.anthropic.Anthropic") as mock_anthropic,
):
# Create enhancer
_enhancer = SkillEnhancer(self.skill_dir)
# VERIFY: Anthropic client called with custom base_url
mock_anthropic.assert_called_once()
call_kwargs = mock_anthropic.call_args[1]
self.assertIn("base_url", call_kwargs, "base_url should be passed")
self.assertEqual(
call_kwargs["base_url"],
custom_url,
"base_url should match ANTHROPIC_BASE_URL env var",
)
def test_anthropic_auth_token_support(self):
"""E2E: Verify ANTHROPIC_AUTH_TOKEN is accepted as alternative to ANTHROPIC_API_KEY"""
try:
from skill_seekers.cli.enhance_skill import SkillEnhancer
except ImportError:
self.skipTest("anthropic package not installed")
custom_token = "custom-auth-token-456"
# Use ANTHROPIC_AUTH_TOKEN instead of ANTHROPIC_API_KEY
with (
patch.dict(os.environ, {"ANTHROPIC_AUTH_TOKEN": custom_token}, clear=True),
patch("skill_seekers.cli.enhance_skill.anthropic.Anthropic") as mock_anthropic,
):
# Create enhancer (should accept ANTHROPIC_AUTH_TOKEN)
enhancer = SkillEnhancer(self.skill_dir)
# VERIFY: api_key set to ANTHROPIC_AUTH_TOKEN value
self.assertEqual(
enhancer.api_key,
custom_token,
"Should use ANTHROPIC_AUTH_TOKEN when ANTHROPIC_API_KEY not set",
)
# VERIFY: Anthropic client initialized with correct key
mock_anthropic.assert_called_once()
call_kwargs = mock_anthropic.call_args[1]
self.assertEqual(
call_kwargs["api_key"],
custom_token,
"api_key should match ANTHROPIC_AUTH_TOKEN",
)
def test_thinking_block_handling(self):
"""E2E: Verify ThinkingBlock doesn't cause .text AttributeError"""
try:
from skill_seekers.cli.enhance_skill import SkillEnhancer
except ImportError:
self.skipTest("anthropic package not installed")
with (
patch.dict(os.environ, {"ANTHROPIC_API_KEY": "test-key"}),
patch("skill_seekers.cli.enhance_skill.anthropic.Anthropic") as mock_anthropic,
):
enhancer = SkillEnhancer(self.skill_dir)
# Mock response with ThinkingBlock (newer SDK)
# ThinkingBlock has no .text attribute
mock_thinking_block = SimpleNamespace(type="thinking")
# TextBlock has .text attribute
mock_text_block = SimpleNamespace(text="# Enhanced SKILL.md\n\nContent here")
mock_message = Mock()
mock_message.content = [mock_thinking_block, mock_text_block]
mock_client = mock_anthropic.return_value
mock_client.messages.create.return_value = mock_message
# Read references (with proper metadata structure)
references = {
"index.md": {
"content": "# Index\nTest content",
"source": "documentation",
"confidence": "high",
"path": "index.md",
"truncated": False,
"size": 23,
"repo_id": None,
}
}
# Call enhance_skill_md (should handle ThinkingBlock gracefully)
result = enhancer.enhance_skill_md(references, current_skill_md="# Old")
# VERIFY: Should find text from TextBlock, ignore ThinkingBlock
self.assertIsNotNone(result, "Should return enhanced content")
self.assertEqual(
result,
"# Enhanced SKILL.md\n\nContent here",
"Should extract text from TextBlock",
)
@unittest.skipIf(not ANTHROPIC_AVAILABLE, "anthropic package not installed")
class TestIssue219IntegrationAll(unittest.TestCase):
"""E2E Integration: All 3 problems together"""
def test_all_fixes_work_together(self):
"""E2E: Verify all 3 fixes work in combination"""
# This test verifies the complete workflow:
# 1. CLI accepts --enhance-level via create command
# 2. Large files are downloaded
# 3. Custom API endpoints work
result = subprocess.run(
["skill-seekers", "create", "--help"], capture_output=True, text=True
)
# Enhancement flags present
self.assertIn("--enhance-level", result.stdout)
# Verify we can import all fixed modules
try:
from skill_seekers.cli import main # noqa: F401
from skill_seekers.cli.enhance_skill import SkillEnhancer # noqa: F401
from skill_seekers.cli.github_scraper import GitHubScraper # noqa: F401
# All imports successful
self.assertTrue(True, "All modules import successfully")
except ImportError as e:
self.fail(f"Module import failed: {e}")
if __name__ == "__main__":
# Run tests with verbose output
unittest.main(verbosity=2)