-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_new_features.py
More file actions
284 lines (226 loc) · 8.15 KB
/
test_new_features.py
File metadata and controls
284 lines (226 loc) · 8.15 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
#!/usr/bin/env python3
"""
Test script for new Phase 1 features:
- Data preview
- List themes
- Better error messages
- Config export/import
"""
import sys
import json
import asyncio
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent / "src"))
from plotnine_mcp.data_loader import load_data, DataSource
from plotnine_mcp.plot_builder import build_plot, PlotBuildError, THEME_MAP, GEOM_MAP
from plotnine_mcp.schemas import Aesthetics, GeomConfig, ThemeConfig, OutputConfig
from plotnine_mcp.error_utils import (
suggest_column_name,
format_column_error,
suggest_geom_type,
format_geom_error,
)
from plotnine_mcp.server import (
preview_data_handler,
list_themes_handler,
export_plot_config_handler,
import_plot_config_handler,
)
def test_data_preview():
"""Test the data preview functionality."""
print("Test 1: Data preview tool...")
# Create inline data source
arguments = {
"data_source": {
"type": "inline",
"data": [
{"x": 1, "y": 2.5, "category": "A"},
{"x": 2, "y": 4.1, "category": "A"},
{"x": 3, "y": 3.8, "category": "B"},
{"x": 4, "y": 5.2, "category": "B"},
{"x": 5, "y": 6.0, "category": "C"},
],
},
"rows": 3,
}
# Run async function
loop = asyncio.get_event_loop()
result = loop.run_until_complete(preview_data_handler(arguments))
assert len(result) == 1
assert "Shape: 5 rows × 3 columns" in result[0].text
assert "Columns:" in result[0].text
print(" ✓ Data preview successful")
print(f" Preview length: {len(result[0].text)} characters")
def test_list_themes():
"""Test the list themes functionality."""
print("\nTest 2: List themes tool...")
loop = asyncio.get_event_loop()
result = loop.run_until_complete(list_themes_handler())
assert len(result) == 1
message = result[0].text
assert "Available Themes" in message
assert "minimal" in message
assert "bw" in message
assert "Customization options:" in message
print(" ✓ List themes successful")
print(f" Listed {len(THEME_MAP)} themes")
def test_column_name_suggestion():
"""Test fuzzy matching for column names."""
print("\nTest 3: Column name fuzzy matching...")
available_columns = ["age", "height", "weight", "category", "value"]
# Test exact typo
suggestion = suggest_column_name("hieght", available_columns)
assert suggestion == "height"
print(f" ✓ 'hieght' → '{suggestion}'")
# Test case difference
suggestion = suggest_column_name("Age", available_columns)
assert suggestion == "age"
print(f" ✓ 'Age' → '{suggestion}'")
# Test partial match
suggestion = suggest_column_name("categoy", available_columns)
assert suggestion == "category"
print(f" ✓ 'categoy' → '{suggestion}'")
# Test format_column_error
error_msg = format_column_error("hieght", available_columns)
assert "Did you mean: 'height'?" in error_msg
assert "Available columns:" in error_msg
print(" ✓ Error message formatting works")
def test_geom_type_suggestion():
"""Test fuzzy matching for geometry types."""
print("\nTest 4: Geom type fuzzy matching...")
available_geoms = list(GEOM_MAP.keys())
# Test typo
suggestion = suggest_geom_type("scater", available_geoms)
# Note: "scater" might not match "point" well, but should work
print(f" ✓ Suggestion for 'scater': {suggestion}")
# Test partial
suggestion = suggest_geom_type("histogram", available_geoms)
assert suggestion == "histogram"
print(f" ✓ 'histogram' → '{suggestion}'")
# Test error formatting
error_msg = format_geom_error("scatterplot", available_geoms)
assert "Unknown geometry type:" in error_msg
assert "Available geometry types:" in error_msg
print(" ✓ Geom error message formatting works")
def test_column_validation():
"""Test that column validation catches errors early."""
print("\nTest 5: Column validation in build_plot...")
# Create test data
data_source = DataSource(
type="inline",
data=[
{"x": 1, "y": 2, "category": "A"},
{"x": 2, "y": 4, "category": "B"},
],
)
data = load_data(data_source)
# Try to use non-existent column
aes_config = Aesthetics(x="x", y="wrong_column")
geom_config = GeomConfig(type="point")
try:
plot = build_plot(data, aes_config, geom_config=geom_config)
assert False, "Should have raised PlotBuildError"
except PlotBuildError as e:
error_msg = str(e)
assert "wrong_column" in error_msg
assert "not found" in error_msg
print(f" ✓ Caught invalid column error")
print(f" Error message: {error_msg[:80]}...")
def test_export_plot_config():
"""Test exporting plot configuration."""
print("\nTest 6: Export plot config...")
config = {
"data_source": {"type": "file", "path": "./data/test.csv"},
"aes": {"x": "date", "y": "value", "color": "category"},
"geom": {"type": "line", "params": {"size": 1.5}},
"theme": {"base": "minimal", "customizations": {"figure_size": [12, 6]}},
"labels": {"title": "Test Plot", "x": "Date", "y": "Value"},
}
arguments = {
"config": config,
"filename": "test_config",
"directory": "./test_output/configs",
}
loop = asyncio.get_event_loop()
result = loop.run_until_complete(export_plot_config_handler(arguments))
assert len(result) == 1
assert "exported successfully" in result[0].text
assert "test_config.json" in result[0].text
# Verify file exists
config_path = Path("./test_output/configs/test_config.json")
assert config_path.exists()
print(f" ✓ Config exported to: {config_path}")
# Verify content
with open(config_path, "r") as f:
saved_config = json.load(f)
assert saved_config["aes"]["x"] == "date"
print(" ✓ Config content is correct")
def test_import_plot_config():
"""Test importing plot configuration."""
print("\nTest 7: Import plot config...")
# First ensure we have a config to import
config = {
"data_source": {
"type": "inline",
"data": [{"x": 1, "y": 2}, {"x": 2, "y": 4}],
},
"aes": {"x": "x", "y": "y"},
"geom": {"type": "point"},
"output": {
"filename": "imported_plot",
"directory": "./test_output",
},
}
# Export it first
export_args = {
"config": config,
"filename": "import_test_config",
"directory": "./test_output/configs",
}
loop = asyncio.get_event_loop()
loop.run_until_complete(export_plot_config_handler(export_args))
# Now import it
import_args = {
"config_path": "./test_output/configs/import_test_config.json",
}
result = loop.run_until_complete(import_plot_config_handler(import_args))
assert len(result) == 1
assert "imported configuration" in result[0].text
print(" ✓ Config imported and plot created")
# Verify the plot was created
plot_path = Path("./test_output/imported_plot.png")
assert plot_path.exists()
print(f" ✓ Plot created from imported config: {plot_path}")
def cleanup():
"""Clean up test output files."""
import shutil
test_output = Path("./test_output")
if test_output.exists():
shutil.rmtree(test_output)
print("\n✓ Cleaned up test output files")
def main():
"""Run all tests."""
print("=" * 60)
print("Running Phase 1 New Features Tests")
print("=" * 60)
try:
test_data_preview()
test_list_themes()
test_column_name_suggestion()
test_geom_type_suggestion()
test_column_validation()
test_export_plot_config()
test_import_plot_config()
print("\n" + "=" * 60)
print("All tests passed! ✓")
print("=" * 60)
except Exception as e:
print(f"\n✗ Test failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
finally:
cleanup()
if __name__ == "__main__":
main()