generated from simonw/click-app-template-repository
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_insert.py
318 lines (288 loc) · 9.34 KB
/
test_insert.py
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import asyncio
from collections import namedtuple
from click.testing import CliRunner
from datasette.app import Datasette
from dclient.cli import cli
import httpx
import json
import pathlib
import pytest
@pytest.fixture
def assert_all_responses_were_requested() -> bool:
return False
@pytest.fixture
def non_mocked_hosts():
# This ensures httpx-mock will not affect Datasette's own
# httpx calls made in the tests by datasette.client:
return ["localhost"]
def test_insert_mocked(httpx_mock, tmpdir):
httpx_mock.add_response(
json={
"ok": True,
"database": "data",
"table": "table1",
"table_url": "http://datasette.example.com/data/table1",
"table_api_url": "http://datasette.example.com/data/table1.json",
"schema": "CREATE TABLE [table1] (...)",
"row_count": 100,
}
)
path = pathlib.Path(tmpdir) / "data.csv"
path.write_text("a,b,c\n1,2,3\n")
runner = CliRunner()
result = runner.invoke(
cli,
[
"insert",
"https://datasette.example.com/data",
"table1",
str(path),
"--csv",
"--token",
"x",
],
catch_exceptions=False,
)
assert result.exit_code == 0
assert result.output == "Inserting rows\n"
request = httpx_mock.get_request()
assert request.headers["authorization"] == "Bearer x"
assert json.loads(request.read()) == {"rows": [{"a": 1, "b": 2, "c": 3}]}
SIMPLE_CSV = "a,b,c\n1,2,3\n"
SIMPLE_TSV = "a\tb\tc\n1\t2\t3\n"
SIMPLE_JSON = json.dumps(
[
{
"a": 1,
"b": 2,
"c": 3,
}
]
)
SIMPLE_JSON_NL = '{"a": 1, "b": 2, "c": 3}\n'
LATIN1_CSV = (
b"date,name,latitude,longitude\n"
b"2020-01-01,Barra da Lagoa,-27.574,-48.422\n"
b"2020-03-04,S\xe3o Paulo,-23.561,-46.645\n"
b"2020-04-05,Salta,-24.793:-65.408"
)
InsertTest = namedtuple(
"InsertTest",
(
"input_data",
"cmd_args",
"table_exists",
"expected_output",
"should_error",
"expected_table_json",
),
)
def make_format_test(content, arg):
return InsertTest(
input_data=content,
# Using --silent to force no display of progress bar, since it won't
# be shown for the JSON formats anyway
cmd_args=["--silent", "--create"] + ([arg] if arg is not None else []),
table_exists=False,
expected_output="",
should_error=False,
expected_table_json=[{"rowid": 1, "a": 1, "b": 2, "c": 3}],
)
@pytest.mark.parametrize(
"input_data,cmd_args,table_exists,expected_output,should_error,expected_table_json",
(
# Auto-detect formats
make_format_test(SIMPLE_CSV, None),
make_format_test(SIMPLE_TSV, None),
make_format_test(SIMPLE_JSON, None),
make_format_test(SIMPLE_JSON_NL, None),
# Explicit formats
make_format_test(SIMPLE_CSV, "--csv"),
make_format_test(SIMPLE_TSV, "--tsv"),
make_format_test(SIMPLE_JSON, "--json"),
make_format_test(SIMPLE_JSON_NL, "--nl"),
# No --create option should error:
InsertTest(
input_data=SIMPLE_CSV,
cmd_args=[],
table_exists=False,
expected_output="Inserting rows\nError: Table not found: table1\n",
should_error=True,
expected_table_json=None,
),
# --no-detect-types
InsertTest(
input_data=SIMPLE_CSV,
cmd_args=["--no-detect-types", "--create"],
table_exists=False,
expected_output="Inserting rows\n",
should_error=False,
expected_table_json=[{"rowid": 1, "a": "1", "b": "2", "c": "3"}],
),
# --encoding - without it this should error:
InsertTest(
input_data=LATIN1_CSV,
cmd_args=["--no-detect-types", "--create", "--csv"],
table_exists=False,
expected_output="Inserting rows\n",
should_error=True,
expected_table_json=None,
),
# --encoding - with it this should work:
InsertTest(
input_data=LATIN1_CSV,
cmd_args=[
"--no-detect-types",
"--create",
"--encoding",
"latin-1",
"--csv",
],
table_exists=False,
expected_output="Inserting rows\n",
should_error=False,
expected_table_json=[
{
"rowid": 1,
"date": "2020-01-01",
"name": "Barra da Lagoa",
"latitude": "-27.574",
"longitude": "-48.422",
},
{
"rowid": 2,
"date": "2020-03-04",
"name": "São Paulo",
"latitude": "-23.561",
"longitude": "-46.645",
},
{
"rowid": 3,
"date": "2020-04-05",
"name": "Salta",
"latitude": "-24.793:-65.408",
"longitude": None,
},
],
),
# Existing table, conflicting pk
InsertTest(
input_data=SIMPLE_CSV,
cmd_args=[],
table_exists=True,
expected_output="Inserting rows\nUNIQUE constraint failed: table1.a\nError: UNIQUE constraint failed: table1.a\n",
should_error=True,
expected_table_json=[{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}],
),
# Existing table, --replace
InsertTest(
input_data="a,b,c\n1,2,4\n",
cmd_args=["--replace"],
table_exists=True,
expected_output="Inserting rows\n",
should_error=False,
expected_table_json=[{"a": 1, "b": 2, "c": 4}, {"a": 4, "b": 5, "c": 6}],
),
# Existing table, --ignore
InsertTest(
input_data="a,b,c\n1,2,4\n",
cmd_args=["--ignore"],
table_exists=True,
expected_output="Inserting rows\n",
should_error=False,
expected_table_json=[{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}],
),
),
)
def test_insert_against_datasette(
httpx_mock,
tmpdir,
input_data,
cmd_args,
table_exists,
expected_output,
should_error,
expected_table_json,
):
ds = Datasette(
metadata={
"permissions": {
"create-table": {"id": "*"},
"insert-row": {"id": "*"},
"update-row": {"id": "*"},
}
}
)
db = ds.add_memory_database("data")
loop = asyncio.get_event_loop()
# Drop all tables in the database each time, because in-memory
# databases persist in between test runs
drop_all_tables(db, loop)
if table_exists:
async def run_table_exists():
await db.execute_write(
"create table table1 (a integer primary key, b integer, c integer)"
)
await db.execute_write(
"insert into table1 (a, b, c) values (1, 2, 3), (4, 5, 6)"
)
loop.run_until_complete(run_table_exists())
token = ds.create_token("actor")
# These are useful with pytest --pdb to see what happened
datasette_requests = []
datasette_responses = []
def custom_response(request: httpx.Request):
# Need to run this in async loop, because dclient itself uses
# sync HTTPX and not async HTTPX
async def run():
datasette_requests.append(request)
response = await ds.client.request(
request.method,
request.url.path,
json=json.loads(request.read()),
headers=request.headers,
)
# Create a fresh response to avoid an error where stream has been consumed
response = httpx.Response(
status_code=response.status_code,
headers=response.headers,
content=response.content,
)
datasette_responses.append(response)
return response
return loop.run_until_complete(run())
httpx_mock.add_callback(custom_response)
path = pathlib.Path(tmpdir) / "data.txt"
if isinstance(input_data, str):
path.write_text(input_data)
else:
path.write_bytes(input_data)
runner = CliRunner()
result = runner.invoke(
cli,
[
"insert",
"http://datasette.example.com/data",
"table1",
str(path),
"--token",
token,
]
+ cmd_args,
)
if not should_error:
assert result.exit_code == 0
else:
assert result.exit_code != 0
assert result.output == expected_output
if expected_table_json:
async def fetch_table():
response = await ds.client.get("/data/table1.json?_shape=array")
return response
response = loop.run_until_complete(fetch_table())
assert response.json() == expected_table_json
def drop_all_tables(db, loop):
async def run():
for table in await db.table_names():
await db.execute_write("drop table {}".format(table))
loop.run_until_complete(run())