-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_cli.py
More file actions
283 lines (227 loc) · 10.2 KB
/
Copy pathtest_cli.py
File metadata and controls
283 lines (227 loc) · 10.2 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
"""Tests for the json2sql CLI interface."""
import json
from typer.testing import CliRunner
from json2sql.cli import app
runner = CliRunner()
class TestCLIBasic:
"""Basic CLI command tests."""
def test_convert_json_file(self, tmp_path):
"""Convert a simple JSON file to SQL via CLI."""
data = {"name": "Alice", "age": 30}
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps(data))
result = runner.invoke(app, ["convert", str(json_file)])
assert result.exit_code == 0
assert "CREATE TABLE" in result.stdout
assert "INSERT INTO" in result.stdout
assert "'Alice'" in result.stdout
assert "30" in result.stdout
def test_convert_with_table_name(self, tmp_path):
"""Specify custom table name."""
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps({"x": 1}))
result = runner.invoke(app, ["convert", str(json_file), "--table", "my_table"])
assert result.exit_code == 0
assert "CREATE TABLE" in result.stdout
assert "my_table" in result.stdout
def test_convert_with_dialect_mysql(self, tmp_path):
"""Use MySQL dialect via CLI."""
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps({"active": True}))
result = runner.invoke(app, ["convert", str(json_file), "--dialect", "mysql"])
assert result.exit_code == 0
assert "`active` TINYINT(1)" in result.stdout or "`active`" in result.stdout
def test_convert_with_dialect_sqlite(self, tmp_path):
"""Use SQLite dialect via CLI."""
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps({"price": 9.99}))
result = runner.invoke(app, ["convert", str(json_file), "--dialect", "sqlite"])
assert result.exit_code == 0
assert "REAL" in result.stdout
def test_convert_output_file(self, tmp_path):
"""Write SQL to an output file."""
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps({"name": "test"}))
out_file = tmp_path / "out.sql"
result = runner.invoke(
app, ["convert", str(json_file), "--output", str(out_file)]
)
assert result.exit_code == 0
assert out_file.exists()
content = out_file.read_text()
assert "CREATE TABLE" in content
assert "INSERT INTO" in content
def test_convert_with_flatten(self, tmp_path):
"""Flatten nested JSON via CLI."""
data = {"id": 1, "address": {"city": "NYC"}}
json_file = tmp_path / "nested.json"
json_file.write_text(json.dumps(data))
result = runner.invoke(app, ["convert", str(json_file), "--flatten"])
assert result.exit_code == 0
assert "CREATE TABLE" in result.stdout
def test_convert_with_flatten_verbose_output(self, tmp_path):
"""Flatten nested object should produce prefixed column names."""
data = {"id": 1, "address": {"city": "NYC", "zip": "10001"}}
json_file = tmp_path / "nested.json"
json_file.write_text(json.dumps(data))
result = runner.invoke(app, ["convert", str(json_file), "--flatten"])
assert result.exit_code == 0
assert "address_city" in result.stdout
assert "address_zip" in result.stdout
def test_convert_flatten_mixed_nested(self, tmp_path):
"""Flatten with both nested dicts and arrays via CLI."""
data = {
"id": 1,
"profile": {"age": 30},
"tags": [{"name": "dev"}, {"name": "python"}],
}
json_file = tmp_path / "complex.json"
json_file.write_text(json.dumps(data))
result = runner.invoke(app, ["convert", str(json_file), "--flatten"])
assert result.exit_code == 0
assert "profile_age" in result.stdout
def test_convert_schema_only(self, tmp_path):
"""Generate schema-only output (no INSERT)."""
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps([{"name": "Alice", "age": 30}]))
result = runner.invoke(app, ["convert", str(json_file), "--schema-only"])
assert result.exit_code == 0
assert "CREATE TABLE" in result.stdout
assert "INSERT INTO" not in result.stdout
def test_convert_schema_only_with_flatten(self, tmp_path):
"""Schema-only with flatten should still exclude INSERT."""
data = {"id": 1, "address": {"city": "NYC"}, "orders": [{"product": "Widget"}]}
json_file = tmp_path / "nested.json"
json_file.write_text(json.dumps(data))
result = runner.invoke(
app, ["convert", str(json_file), "--schema-only", "--flatten"]
)
assert result.exit_code == 0
assert "CREATE TABLE" in result.stdout
assert "INSERT INTO" not in result.stdout
def test_convert_stdin(self):
"""Read JSON from stdin."""
result = runner.invoke(
app, ["convert"], input=json.dumps({"name": "stdin_test"})
)
assert result.exit_code == 0
assert "'stdin_test'" in result.stdout
def test_convert_empty_stdin_no_input(self):
"""Error when no file and stdin is empty."""
# Simulate no input (isatty = True in CliRunner)
result = runner.invoke(app, ["convert"])
assert result.exit_code == 1
assert "Error" in result.stderr or "Error" in result.stdout
def test_convert_bad_json(self, tmp_path):
"""Error on invalid JSON input."""
json_file = tmp_path / "bad.json"
json_file.write_text("{invalid}")
result = runner.invoke(app, ["convert", str(json_file)])
assert result.exit_code == 1
assert "Error" in result.stderr or "Error" in result.stdout
def test_convert_bad_dialect(self, tmp_path):
"""Error on invalid dialect."""
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps({"x": 1}))
result = runner.invoke(app, ["convert", str(json_file), "--dialect", "oracle"])
assert result.exit_code != 0
def test_convert_file_not_found(self):
"""Error when file does not exist."""
result = runner.invoke(app, ["convert", "nonexistent.json"])
# Typer validates exists=True so it should fail
assert result.exit_code != 0
class TestCLIVersion:
"""Version command tests."""
def test_version(self):
"""Show version."""
result = runner.invoke(app, ["version"])
assert result.exit_code == 0
assert "0.1.1" in result.stdout
def test_version_output_format(self):
"""Version output should include the tool name."""
result = runner.invoke(app, ["version"])
assert result.exit_code == 0
assert "json2sql" in result.stdout
assert "0.1.1" in result.stdout
# Should contain version number but not error messages
assert "Error" not in result.stdout
class TestMCP:
"""MCP command tests."""
def test_mcp_import_error_handled_gracefully(self):
"""Missing click_to_mcp shows a helpful error instead of traceback."""
import builtins
import sys
import unittest.mock as mock
# Remove click_to_mcp from cache so the import statement is executed
old_mod = sys.modules.pop("click_to_mcp", None)
original_import = builtins.__import__
def mock_import(name, *args, **kwargs):
if name == "click_to_mcp":
raise ImportError(f"No module named '{name}'")
return original_import(name, *args, **kwargs)
try:
with mock.patch.object(builtins, "__import__", side_effect=mock_import):
result = runner.invoke(app, ["mcp"])
assert result.exit_code == 1
assert "click_to_mcp" in result.output.lower()
assert "pip install" in result.output.lower()
finally:
if old_mod:
sys.modules["click_to_mcp"] = old_mod
def test_mcp_command_exists(self):
"""mcp command is registered and responds to --help."""
result = runner.invoke(app, ["mcp", "--help"])
assert result.exit_code == 0
assert (
"MCP" in result.stdout
or "Model Context" in result.stdout
or "stdio" in result.stdout
)
class TestCLIErrorHandling:
"""Error handling tests."""
def test_no_args_shows_help(self):
"""Running without args shows help."""
result = runner.invoke(app)
# Typer with no_args_is_help may exit 0 or 2 depending on version
assert (
"Usage:" in result.stdout
or "Usage:" in result.stderr
or "Convert" in result.stdout
or "Convert" in result.stderr
)
def test_convert_array_of_objects(self, tmp_path):
"""Convert array of objects via CLI."""
data = [{"name": "Alice"}, {"name": "Bob"}]
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps(data))
result = runner.invoke(app, ["convert", str(json_file)])
assert result.exit_code == 0
assert "'Alice'" in result.stdout
assert "'Bob'" in result.stdout
def test_convert_empty_array(self, tmp_path):
"""Empty array produces appropriate message."""
json_file = tmp_path / "empty.json"
json_file.write_text("[]")
result = runner.invoke(app, ["convert", str(json_file)])
assert result.exit_code == 0
assert "Empty" in result.stdout
def test_convert_boolean_values(self, tmp_path):
"""Boolean rendering depends on dialect."""
data = {"flag": True, "active": False}
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps(data))
# Postgres
result = runner.invoke(
app, ["convert", str(json_file), "--dialect", "postgres"]
)
assert result.exit_code == 0
assert "TRUE" in result.stdout
assert "FALSE" in result.stdout
def test_convert_null_values(self, tmp_path):
"""NULL values handled."""
data = {"name": None}
json_file = tmp_path / "data.json"
json_file.write_text(json.dumps(data))
result = runner.invoke(app, ["convert", str(json_file)])
assert result.exit_code == 0
assert "NULL" in result.stdout