import base64 import importlib.util import io import json from pathlib import Path import subprocess import sys import tempfile import types import unittest from unittest.mock import MagicMock, patch import zipfile spec = importlib.util.spec_from_file_location("gateway", Path(__file__).with_name("app.py")) gateway = importlib.util.module_from_spec(spec) spec.loader.exec_module(gateway) class GatewayTests(unittest.TestCase): def execute_file_tool(self, root, name, arguments): payload = base64.b64encode(json.dumps({"name": name, "arguments": arguments}).encode()).decode() script = gateway.SCRIPT.replace("pathlib.Path('/workspace')", "pathlib.Path(" + repr(str(root)) + ")") result = subprocess.run([sys.executable, "-X", "utf8", "-c", "PAYLOAD=" + repr(payload) + "\n" + script], capture_output=True, timeout=10) self.assertEqual(0, result.returncode, result.stderr.decode()) return json.loads(result.stdout) def test_file_roundtrip_and_parent_traversal_rejection(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) / "workspace" root.mkdir() self.assertIn("written", self.execute_file_tool(root, "write_file", {"path": "src/test.txt", "content": "真实内容"})) self.assertEqual("真实内容", self.execute_file_tool(root, "read_file", {"path": "src/test.txt"})["content"]) self.assertIn("error", self.execute_file_tool(root, "write_file", {"path": "../outside.txt", "content": "denied"})) self.assertFalse((Path(directory) / "outside.txt").exists()) def test_large_file_read_is_rejected(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / "large.txt").write_bytes(b"x" * 64001) self.assertIn("error", self.execute_file_tool(root, "read_file", {"path": "large.txt"})) def test_workspace_inspection_requires_nonempty_source_and_excludes_dependencies(self): with tempfile.TemporaryDirectory() as directory: root=Path(directory) (root/'node_modules').mkdir() (root/'node_modules/fake.js').write_text('dependency code') (root/'index.html').write_text('') (root/'.env').write_text('SECRET=must-not-appear') self.assertEqual(0,self.execute_file_tool(root,'workspace_inspect',{})['sourceFiles']) (root/'index.html').write_text('