-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtests.py
More file actions
168 lines (137 loc) · 5.69 KB
/
Copy pathtests.py
File metadata and controls
168 lines (137 loc) · 5.69 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
#!/usr/bin/env python3
"""
TinyToT Test Runner
Runs comprehensive tests against the TinyToT server using mcphost
Tests are schema-driven and should pass without code changes
"""
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import List, Tuple
model = os.getenv("MODEL", "tinytot")
providerName = os.getenv("PROVIDER_NAME", "ollama")
providerUrl = os.getenv("PROVIDER_URL")
mcpConfig = os.getenv("MCP_CONFIG", os.path.expanduser("~/.mcphost.json"))
testTimeout = int(os.getenv("TEST_TIMEOUT", "15"))
class TestRunner:
def __init__(self):
self.testDir = Path(__file__).parent / "tests"
self.passed = 0
self.failed = 0
self.results = []
def runSingleTest(
self,
prompt: str,
expectedCategory: str,
expectedTool: str,
expectedPatterns: List[str],
) -> Tuple[bool, str]:
"""Run a single test case using mcphost"""
try:
# Run mcphost with our TinyToT model
env = os.environ.copy()
# Build command with optional provider URL for custom ports
cmd = ["mcphost"]
cmd.extend(["--quiet"])
if providerUrl:
cmd.extend(["--provider-url", providerUrl])
if mcpConfig and os.path.exists(mcpConfig):
cmd.extend(["--config", mcpConfig])
if model and providerName:
cmd.extend(["-m", f"{providerName}:{model}"])
cmd.extend(["-p", prompt])
result = subprocess.run(cmd, capture_output=True, text=True, timeout=testTimeout, env=env)
if result.returncode != 0:
return False, f"Command failed: {result.stderr}"
output = result.stdout
# Check expected patterns
for pattern in expectedPatterns:
if not re.search(pattern, output, re.IGNORECASE | re.DOTALL):
return False, f"Pattern not found: {pattern}"
return True, "PASSED"
except subprocess.TimeoutExpired:
return False, "Test timed out"
except Exception as e:
return False, f"Error: {str(e)}"
def parseTestFile(self, filepath: Path) -> List[Tuple[str, str, str, List[str]]]:
"""Parse a .tst file and return test cases"""
testCases = []
with open(filepath, "r") as f:
for lineNum, line in enumerate(f, 1):
line = line.strip()
if line.startswith("#") or not line:
continue
# Parse: PROMPT | EXPECTED_CATEGORY | EXPECTED_TOOL | EXPECTED_PATTERNS
if "|" in line:
parts = [part.strip() for part in line.split("|")]
if len(parts) >= 4:
prompt = parts[0]
expectedCategory = parts[1]
expectedTool = parts[2]
# Split patterns by .* for multiple patterns
expectedPatterns = [p.strip() for p in parts[3].split(".*") if p.strip()]
testCases.append((prompt, expectedCategory, expectedTool, expectedPatterns))
return testCases
def runAllTests(self):
"""Run all test files"""
print(f"{model} Model Test Suite")
print("=" * 50)
print(f"Timeout: {testTimeout}", flush=True)
# Find all .tst files
testFiles = list(self.testDir.glob("*.tst"))
print(f"Found {len(testFiles)} test files\n")
for testFile in testFiles:
print(f"\nRunning tests from: {testFile.name}")
print("-" * 40)
testCases = self.parseTestFile(testFile)
for i, (
prompt,
expectedCategory,
expectedTool,
expectedPatterns,
) in enumerate(testCases, 1):
print(f"Test {i}: {prompt[:50]}{'...' if len(prompt) > 50 else ''}")
success, message = self.runSingleTest(prompt, expectedCategory, expectedTool, expectedPatterns)
if success:
print(" ✓ PASSED")
self.passed += 1
else:
print(f" ✗ FAILED: {message}")
self.failed += 1
self.results.append(
{
"file": testFile.name,
"test_num": i,
"prompt": prompt,
"expected_category": expectedCategory,
"expected_tool": expectedTool,
"success": success,
"message": message,
}
)
def printSummary(self):
"""Print test results summary"""
print("\n" + "=" * 50)
print("TEST RESULTS SUMMARY")
print("=" * 50)
print(f"Total Tests: {self.passed + self.failed}")
print(f"Passed: {self.passed}")
print(f"Failed: {self.failed}")
if self.failed > 0:
print("\nFAILED TESTS:")
for result in self.results:
if not result["success"]:
print(f" {result['file']} Test {result['test_num']}: {result['prompt'][:40]}...")
print(f" Reason: {result['message']}")
if self.passed == self.passed + self.failed:
print("\nALL TESTS PASSED! Schema-driven system working perfectly!")
else:
print(f"\n{self.failed} tests failed. Run the server, install mcphost, and update data files to fix.")
if __name__ == "__main__":
runner = TestRunner()
runner.runAllTests()
runner.printSummary()
# Exit with appropriate code
sys.exit(0 if runner.failed == 0 else 1)