|
| 1 | +"""Checks for behaviour that Cython compilation can break. |
| 2 | +
|
| 3 | +These run on source in CI and, through packaging/build/test_wheel.sh, against |
| 4 | +every compiled wheel on Linux, Windows and macOS. They cover what the rest of |
| 5 | +the suite does not reach: every module importing, the introspection that |
| 6 | +pydantic-ai, FastMCP and FastAPI do on compiled functions, and a module agent |
| 7 | +run end to end with a scripted model, so no API key or network is needed. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import asyncio |
| 13 | +import importlib |
| 14 | +import inspect |
| 15 | +import json |
| 16 | +import pkgutil |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +import pytest |
| 20 | + |
| 21 | +import codewiki |
| 22 | + |
| 23 | +# --------------------------------------------------------------------------- |
| 24 | +# Every module imports |
| 25 | +# --------------------------------------------------------------------------- |
| 26 | + |
| 27 | + |
| 28 | +def test_every_module_imports(): |
| 29 | + failures = {} |
| 30 | + count = 0 |
| 31 | + for info in pkgutil.walk_packages(codewiki.__path__, "codewiki."): |
| 32 | + count += 1 |
| 33 | + try: |
| 34 | + importlib.import_module(info.name) |
| 35 | + except Exception as e: # noqa: BLE001 — collect every failure, not just the first |
| 36 | + failures[info.name] = f"{type(e).__name__}: {e}" |
| 37 | + assert count > 100, f"only {count} modules found; is the package complete?" |
| 38 | + assert not failures, failures |
| 39 | + |
| 40 | + |
| 41 | +# --------------------------------------------------------------------------- |
| 42 | +# Introspection by frameworks |
| 43 | +# --------------------------------------------------------------------------- |
| 44 | + |
| 45 | + |
| 46 | +# caw's toolkit still uses asyncio.iscoroutinefunction, so check both forms. |
| 47 | +@pytest.mark.filterwarnings("ignore:'asyncio.iscoroutinefunction' is deprecated") |
| 48 | +def test_async_functions_are_still_coroutine_functions(): |
| 49 | + # pydantic-ai, FastMCP and caw pick sync vs async by inspecting these; |
| 50 | + # a compiled function that stops reporting as a coroutine function |
| 51 | + # would have its coroutine returned unawaited. |
| 52 | + from codewiki.src.be.caw_toolkit import CawToolKit |
| 53 | + from codewiki.src.be.documentation_generator import DocumentationGenerator |
| 54 | + from codewiki.src.be.pydantic_ai_backend import PydanticAIBackend |
| 55 | + |
| 56 | + for fn in ( |
| 57 | + PydanticAIBackend.run_module_agent, |
| 58 | + DocumentationGenerator.run, |
| 59 | + CawToolKit.read_code_components, |
| 60 | + CawToolKit.str_replace_editor, |
| 61 | + CawToolKit.generate_sub_module_documentation, |
| 62 | + ): |
| 63 | + assert inspect.iscoroutinefunction(fn), fn.__qualname__ |
| 64 | + assert asyncio.iscoroutinefunction(fn), fn.__qualname__ |
| 65 | + |
| 66 | + |
| 67 | +def test_pydantic_ai_tool_schemas(): |
| 68 | + from codewiki.src.be.agent_tools.generate_sub_module_documentations import ( |
| 69 | + generate_sub_module_documentation_tool, |
| 70 | + ) |
| 71 | + from codewiki.src.be.agent_tools.read_code_components import read_code_components_tool |
| 72 | + from codewiki.src.be.agent_tools.str_replace_editor import str_replace_editor_tool |
| 73 | + |
| 74 | + expected = { |
| 75 | + "read_code_components": {"component_ids"}, |
| 76 | + "str_replace_editor": {"working_dir", "command", "path", "file_text"}, |
| 77 | + "generate_sub_module_documentation": {"sub_module_specs"}, |
| 78 | + } |
| 79 | + for tool in ( |
| 80 | + read_code_components_tool, |
| 81 | + str_replace_editor_tool, |
| 82 | + generate_sub_module_documentation_tool, |
| 83 | + ): |
| 84 | + schema = tool.function_schema |
| 85 | + assert tool.takes_ctx, tool.name |
| 86 | + assert schema.is_async, tool.name |
| 87 | + assert tool.description and tool.description.strip(), tool.name |
| 88 | + properties = set(schema.json_schema.get("properties", {})) |
| 89 | + assert expected[tool.name] <= properties, (tool.name, properties) |
| 90 | + # The parameter docs come from the docstring; compiled code must keep it. |
| 91 | + if tool.name == "str_replace_editor": |
| 92 | + assert "description" in schema.json_schema["properties"]["working_dir"] |
| 93 | + |
| 94 | + |
| 95 | +def test_caw_toolkit_tools_register_with_fastmcp(): |
| 96 | + from mcp.server.fastmcp import FastMCP |
| 97 | + |
| 98 | + from codewiki._vendor.caw.mcp import register_tool |
| 99 | + from codewiki._vendor.caw.toolkit import _make_tool_func |
| 100 | + from codewiki.src.be.caw_toolkit import CawToolKit |
| 101 | + |
| 102 | + server = FastMCP("compiled-wheel-check") |
| 103 | + for name in dir(CawToolKit): |
| 104 | + attr = getattr(CawToolKit, name) |
| 105 | + info = getattr(attr, "_toolkit_tool_info", None) |
| 106 | + if info is not None: |
| 107 | + register_tool(server, _make_tool_func(attr, info)) |
| 108 | + |
| 109 | + tools = {t.name: t for t in asyncio.run(server.list_tools())} |
| 110 | + assert { |
| 111 | + "read_code_components", |
| 112 | + "str_replace_editor", |
| 113 | + "generate_sub_module_documentation", |
| 114 | + } <= set(tools) |
| 115 | + editor = tools["str_replace_editor"] |
| 116 | + assert editor.description |
| 117 | + assert {"working_dir", "command", "path"} <= set(editor.inputSchema["properties"]) |
| 118 | + assert {"working_dir", "command"} <= set(editor.inputSchema.get("required", [])) |
| 119 | + # The Context parameter is injected by FastMCP, never exposed to the model. |
| 120 | + assert "ctx" not in editor.inputSchema["properties"] |
| 121 | + |
| 122 | + |
| 123 | +@pytest.mark.parametrize("module", ["codewiki.src.fe.web_app", "codewiki.src.fe.visualise_docs"]) |
| 124 | +def test_fastapi_routes_build_an_openapi_schema(module): |
| 125 | + app = importlib.import_module(module).app |
| 126 | + schema = app.openapi() |
| 127 | + assert schema["paths"], module |
| 128 | + |
| 129 | + |
| 130 | +# --------------------------------------------------------------------------- |
| 131 | +# End to end: dependency analysis + module agent with a scripted model |
| 132 | +# --------------------------------------------------------------------------- |
| 133 | + |
| 134 | + |
| 135 | +def _write(path: Path, text: str) -> None: |
| 136 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 137 | + path.write_text(text, encoding="utf-8") |
| 138 | + |
| 139 | + |
| 140 | +def test_module_agent_end_to_end_with_scripted_model(tmp_path, monkeypatch): |
| 141 | + from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart |
| 142 | + from pydantic_ai.models.function import FunctionModel |
| 143 | + |
| 144 | + import codewiki.src.be.pydantic_ai_backend as backend_module |
| 145 | + from codewiki.src.be.dependency_analyzer.dependency_graphs_builder import ( |
| 146 | + DependencyGraphBuilder, |
| 147 | + ) |
| 148 | + from codewiki.src.config import MODULE_TREE_FILENAME, Config |
| 149 | + |
| 150 | + repo = tmp_path / "repo" |
| 151 | + _write(repo / "pkg" / "__init__.py", "") |
| 152 | + _write( |
| 153 | + repo / "pkg" / "greeter.py", |
| 154 | + "from collections import defaultdict\n\n" |
| 155 | + "from pkg.format import shout\n\n\n" |
| 156 | + "class Greeter:\n" |
| 157 | + " def __init__(self):\n" |
| 158 | + " self.seen = defaultdict(int)\n\n" |
| 159 | + " def greet(self, name):\n" |
| 160 | + " self.seen[name] += 1\n" |
| 161 | + " return shout(name)\n", |
| 162 | + ) |
| 163 | + _write(repo / "pkg" / "format.py", "def shout(name):\n return f'HELLO {name.upper()}'\n") |
| 164 | + out = tmp_path / "docs" |
| 165 | + out.mkdir() |
| 166 | + |
| 167 | + config = Config.from_cli( |
| 168 | + repo_path=str(repo), |
| 169 | + output_dir=str(out), |
| 170 | + llm_base_url="http://127.0.0.1:9", |
| 171 | + llm_api_key="unused", |
| 172 | + main_model="scripted", |
| 173 | + cluster_model="scripted", |
| 174 | + ) |
| 175 | + |
| 176 | + # Dependency analysis: the compiled-wheel crash (defaultdict vs a `dict` |
| 177 | + # annotation) happened in this step. |
| 178 | + components, leaves = DependencyGraphBuilder(config).build_dependency_graph() |
| 179 | + ids = set(components) |
| 180 | + assert any(i.endswith("::Greeter") for i in ids), ids |
| 181 | + assert any(i.endswith("::shout") for i in ids), ids |
| 182 | + assert leaves |
| 183 | + |
| 184 | + (out / MODULE_TREE_FILENAME).write_text( |
| 185 | + json.dumps({"Core": {"path": "pkg", "components": leaves, "children": {}}}), |
| 186 | + encoding="utf-8", |
| 187 | + ) |
| 188 | + |
| 189 | + tool_returns: list[str] = [] |
| 190 | + |
| 191 | + def scripted(messages, info): |
| 192 | + tool_returns[:] = [ |
| 193 | + str(part.content) |
| 194 | + for message in messages |
| 195 | + for part in message.parts |
| 196 | + if isinstance(part, ToolReturnPart) |
| 197 | + ] |
| 198 | + step = len(tool_returns) |
| 199 | + if step == 0: |
| 200 | + return ModelResponse( |
| 201 | + parts=[ToolCallPart("read_code_components", {"component_ids": leaves})] |
| 202 | + ) |
| 203 | + if step == 1: |
| 204 | + page = ( |
| 205 | + "# Core\n\nGreets people.\n\n```mermaid\ngraph TD\n A[Greeter] --> B[shout]\n```\n" |
| 206 | + ) |
| 207 | + return ModelResponse( |
| 208 | + parts=[ |
| 209 | + ToolCallPart( |
| 210 | + "str_replace_editor", |
| 211 | + { |
| 212 | + "working_dir": "docs", |
| 213 | + "command": "create", |
| 214 | + "path": "Core.md", |
| 215 | + "file_text": page, |
| 216 | + }, |
| 217 | + ) |
| 218 | + ] |
| 219 | + ) |
| 220 | + return ModelResponse(parts=[TextPart("Documentation written.")]) |
| 221 | + |
| 222 | + monkeypatch.setattr( |
| 223 | + backend_module, "create_fallback_models", lambda config: FunctionModel(scripted) |
| 224 | + ) |
| 225 | + backend = backend_module.PydanticAIBackend(config) |
| 226 | + asyncio.run(backend.run_module_agent("Core", components, leaves, ["Core"], str(out))) |
| 227 | + |
| 228 | + assert len(tool_returns) == 2, tool_returns |
| 229 | + read_result, editor_result = tool_returns |
| 230 | + assert "class Greeter" in read_result or "def shout" in read_result, read_result[:300] |
| 231 | + assert "created" in editor_result.lower(), editor_result[:300] |
| 232 | + page = (out / "Core.md").read_text(encoding="utf-8") |
| 233 | + assert page.startswith("# Core") |
| 234 | + assert "```mermaid" in page |
0 commit comments