-
Notifications
You must be signed in to change notification settings - Fork 308
/
test_api.py
507 lines (429 loc) · 14.7 KB
/
test_api.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import os
from inspect import cleandoc
from io import BytesIO
from operator import itemgetter
from pathlib import Path
from urllib.parse import urlencode
import pytest
from lektor.admin import WebAdmin
from lektor.admin.context import LektorContext
from lektor.admin.utils import eventstream
from lektor.builder import Builder
from lektor.constants import PRIMARY_ALT
from lektor.db import Database
from lektor.editor import EditorSession
from lektor.environment import Environment
from lektor.project import Project
from lektor.publisher import PublishError
def write_text(path, text):
path.parent.mkdir(exist_ok=True)
path.write_text(cleandoc(text))
@pytest.fixture
def scratch_project_data(scratch_project_data):
write_text(
scratch_project_data / "content/page/contents.lr",
"""
_model: page
---
title: A Page
""",
)
return scratch_project_data
@pytest.fixture
def scratch_client(scratch_env, scratch_project):
webadmin = WebAdmin(scratch_env, output_path=scratch_project.tree)
with webadmin.test_client() as client:
yield client
@pytest.fixture
def scratch_content_path(scratch_project):
return Path(scratch_project.tree) / "content"
@pytest.fixture(scope="session")
def project_path(data_path):
return data_path / "demo-project"
@pytest.fixture(scope="session")
def webadmin(tmp_path_factory, project_path):
project = Project.from_path(project_path)
env = Environment(project, load_plugins=False)
output_path = tmp_path_factory.mktemp("webadmin-output")
pad = Database(env).new_pad()
builder = Builder(pad, output_path)
builder.update_all_source_infos()
app = WebAdmin(env, output_path=output_path)
return app
@pytest.fixture
def test_client(webadmin):
with webadmin.test_client() as client:
yield client
def test_recordinfo_children_sort_limited_alts(test_client):
# This exercises the bug described in #962, namely that
# if a page has a child that only has content in a subset of the
# configured alts, get_record_info throws an exception.
data = test_client.get("/admin/api/recordinfo?path=/projects").get_json()
child_data = data["children"]
assert list(sorted(child_data, key=itemgetter("label"))) == child_data
def test_eventstream_yield_bytes():
count = 0
@eventstream
def testfunc():
yield "string"
yield 5
for data in testfunc().response: # pylint: disable=no-member
count += 1
assert isinstance(data, bytes)
assert count >= 2
@pytest.mark.parametrize(
"endpoint, params, invalid",
[
("recordinfo", {}, {"path"}),
("previewinfo", {"path": "/", "alt": "BAD"}, {"alt"}),
],
)
def test_invalid_params(test_client, endpoint, params, invalid):
resp = test_client.get(f"/admin/api/{endpoint}?{urlencode(params)}")
assert resp.status_code == 400
error = resp.get_json()["error"]
assert error["title"] == "Invalid parameters"
assert set(error["messages"].keys()) == invalid
def test_recordinfo(test_client):
resp = test_client.get("/admin/api/recordinfo?path=%2F")
assert resp.status_code == 200
data = resp.get_json()
assert any(att["id"] == "hello.txt" for att in data["attachments"])
assert any(page["id"] == "blog" for page in data["children"])
assert any(alt["alt"] == "de" for alt in data["alts"])
def test_delete_field(scratch_client, scratch_content_path):
# None in page data means to delete the field
# Test that that works
contents_lr = scratch_content_path / "contents.lr"
assert "\nbody:" in contents_lr.read_text()
resp = scratch_client.put(
"/admin/api/rawrecord?path=%2F", json={"path": "/", "data": {"body": None}}
)
assert resp.status_code == 200
assert "\nbody:" not in contents_lr.read_text()
def test_get_path_info(test_client):
resp = test_client.get("/admin/api/pathinfo?path=%2Fblog%2Fpost2")
assert resp.get_json() == {
"segments": [
{
"can_have_children": True,
"exists": True,
"id": "",
"label_i18n": {"en": "Welcome"},
"path": "/",
},
{
"can_have_children": True,
"exists": True,
"id": "blog",
"label_i18n": {"en": "Blog"},
"path": "/blog",
},
{
"can_have_children": True,
"exists": True,
"id": "post2",
"label_i18n": {"en": "Post 2"},
"path": "/blog/post2",
},
],
}
@pytest.mark.parametrize(
"path, expect",
[
(
"/blog/post1/hello.txt",
{
"exists": True,
"url": "/blog/2015/12/post1/hello.txt",
"is_hidden": False,
},
),
(
"/extra/container",
{
"exists": True,
"url": "/extra/container/",
"is_hidden": True,
},
),
(
"/missing",
{
"exists": False,
"url": None,
"is_hidden": True,
},
),
],
)
def test_previewinfo(test_client, path, expect):
resp = test_client.get(f"/admin/api/previewinfo?{urlencode({'path': path})}")
assert resp.status_code == 200
assert resp.get_json() == expect
@pytest.mark.parametrize("use_json", [True, False])
@pytest.mark.parametrize("lang", ["en", None])
def test_find(test_client, use_json, lang):
# Test that we can pass params in JSON body, rather than in the query
params = {"q": "hello", "alt": "_primary", "lang": lang}
if use_json:
resp = test_client.post("/admin/api/find", json=params)
else:
resp = test_client.post(f"/admin/api/find?{urlencode(params)}")
assert resp.status_code == 200
results = resp.get_json()["results"]
assert any(result["title"] == "Hello" for result in results)
assert len(results) == 1
@pytest.mark.parametrize(
"path, alt, srcfile",
[
("/projects/bagpipe", "de", "projects/bagpipe/contents+de.lr"),
("/hello.txt", "de", "hello.txt"),
],
)
def test_browsefs(test_client, mocker, project_path, path, alt, srcfile):
launch = mocker.patch("click.launch")
params = {"path": path, "alt": alt}
resp = test_client.post("/admin/api/browsefs", json=params)
assert resp.status_code == 200
assert resp.get_json()["okay"]
assert launch.mock_calls == [
mocker.call(str(project_path / "content" / srcfile), locate=True),
]
@pytest.mark.parametrize(
"path, alt, can_have_children",
[
("/test.jpg", "de", False),
("/projects", "de", True),
],
)
def test_get_new_record_info(test_client, path, alt, can_have_children):
params = {"path": path, "alt": alt}
resp = test_client.get(f"/admin/api/newrecord?{urlencode(params)}")
assert resp.status_code == 200
data = resp.get_json()
assert data["can_have_children"] is bool(can_have_children)
@pytest.mark.parametrize(
"path, alt, can_upload",
[
("/test.jpg", "de", False),
("/projects", "de", True),
],
)
def test_get_new_attachment_info(test_client, path, alt, can_upload):
params = {"path": path}
resp = test_client.get(f"/admin/api/newattachment?{urlencode(params)}")
assert resp.status_code == 200
data = resp.get_json()
assert data["can_upload"] is bool(can_upload)
def test_upload_new_attachment(scratch_client, scratch_content_path):
params = {
"path": "/page",
"file": (BytesIO(b"foo data"), "foo.txt"),
}
resp = scratch_client.post("/admin/api/newattachment", data=params)
assert resp.status_code == 200
assert not resp.get_json()["bad_upload"]
dstpath = scratch_content_path / "page/foo.txt"
assert dstpath.read_bytes() == b"foo data"
@pytest.mark.parametrize(
"path, alt",
[
("/test.txt", PRIMARY_ALT),
("/missing", PRIMARY_ALT),
("/missing", "de"),
],
)
def test_upload_new_attachment_failure(scratch_client, scratch_content_path, path, alt):
scratch_content_path.joinpath("test.txt").write_bytes(b"test")
params = {
"path": path,
"alt": alt,
"file": (BytesIO(b"foo data"), "foo.txt"),
}
resp = scratch_client.post("/admin/api/newattachment", data=params)
assert resp.status_code == 200
assert resp.get_json()["bad_upload"]
dstpath = scratch_content_path / "test.txt/foo.txt"
assert not dstpath.exists()
@pytest.mark.parametrize(
"path, id, expect, creates",
[
(
"/page",
"new",
{"valid_id": True, "exists": False, "path": "/page/new"},
"page/new/contents.lr",
),
("/page", ".new", {"valid_id": False, "exists": False, "path": None}, None),
("/", "page", {"valid_id": True, "exists": True, "path": "/page"}, None),
],
)
def test_add_new_record(scratch_client, scratch_project, path, id, expect, creates):
def tree_files():
return {
Path(dirpath, filename)
for (dirpath, dirnames, filenames) in os.walk(scratch_project.tree)
for filename in filenames
}
orig_tree_files = tree_files()
params = {"path": path, "id": id, "data": {}}
resp = scratch_client.post("/admin/api/newrecord", json=params)
assert resp.status_code == 200
assert resp.get_json() == expect
new_files = tree_files() - orig_tree_files
if creates is None:
assert len(new_files) == 0
else:
assert new_files == {Path(scratch_project.tree, "content", creates)}
@pytest.mark.parametrize(
"path, id",
[
# Ensure that attempts to create records outside of the `content` subtree fail.
# (Reported by Riku Bamba)
("/../../templates", ""),
],
)
def test_add_new_record_bad_request(scratch_client, scratch_project, path, id):
params = {"path": path, "id": id, "data": {}}
resp = scratch_client.post("/admin/api/newrecord", json=params)
assert resp.status_code == 400
assert resp.get_json() == {
"error": {
"title": "Invalid parameters",
"messages": {"path": ["Invalid value."]},
},
}
@pytest.mark.parametrize(
"delete_master, expect", [("1", True), (True, True), ("0", False), (False, False)]
)
def test_delete_record(scratch_client, mocker, delete_master, expect):
delete = mocker.patch.object(EditorSession, "delete")
params = {"path": "/myobj", "delete_master": delete_master}
resp = scratch_client.post("/admin/api/deleterecord", json=params)
assert resp.status_code == 200
assert delete.mock_calls == [
mocker.call(delete_master=expect),
]
@pytest.mark.parametrize(
"url_path, expect",
[
(
"/blog/2015/12/post1/hello.txt",
{
"exists": True,
"path": "/blog/post1/hello.txt",
"alt": PRIMARY_ALT,
},
),
(
"/missing",
{
"exists": False,
"path": None,
"alt": None,
},
),
(
"/static/demo.css", # non-Records do not exist
{
"exists": False,
"path": None,
"alt": None,
},
),
],
)
def test_match_url(test_client, url_path, expect):
params = {"url_path": url_path}
resp = test_client.get(f"/admin/api/matchurl?{urlencode(params)}")
assert resp.status_code == 200
assert resp.get_json() == expect
def test_get_raw_records(test_client):
resp = test_client.get("/admin/api/rawrecord?path=%2F")
assert resp.status_code == 200
data = resp.get_json()
assert data["data"]["title"] == "Welcome"
assert "datamodel" in data
def test_servers(test_client):
resp = test_client.get("/admin/api/servers")
assert resp.status_code == 200
assert any(server["id"] == "production" for server in resp.get_json()["servers"])
def test_build(test_client, webadmin, mocker):
builder = mocker.patch.object(LektorContext, "builder")
resp = test_client.post("/admin/api/build")
assert resp.status_code == 200
data = resp.get_json()
assert data["okay"]
assert builder.mock_calls == [
mocker.call.build_all(),
mocker.call.prune(),
]
def test_clean(test_client, webadmin, mocker):
builder = mocker.patch.object(LektorContext, "builder")
resp = test_client.post("/admin/api/clean")
assert resp.status_code == 200
data = resp.get_json()
assert data["okay"]
assert mocker.call.prune(all=True) in builder.mock_calls
@pytest.mark.xfail(reason="FIXME")
def test_publish_requires_post(test_client, mocker):
# See https://github.com/lektor/lektor/issues/1006
resp = test_client.get("/admin/api/publish?server=unknown")
assert resp.status_code == 405
def test_publish(test_client, mocker):
def dummy_publish(env, target, output_path, credentials=None, **extra):
yield "line1"
raise PublishError("wups")
mocker.patch("lektor.admin.modules.api.publish", side_effect=dummy_publish)
resp = test_client.get("/admin/api/publish?server=production")
assert resp.status_code == 200
assert list(resp.response) == [
b'data: {"msg": "line1"}\n\n',
b'data: {"msg": "Error: wups"}\n\n',
b"data: null\n\n",
]
@pytest.mark.parametrize(
"params",
[
{"server": "bogus"},
{},
],
)
def test_publish_bad_params(test_client, params):
resp = test_client.get(f"/admin/api/publish?{urlencode(params)}")
assert resp.status_code == 400
assert "server" in resp.get_json()["error"]["messages"]
def test_ping(test_client):
resp = test_client.get("/admin/api/ping")
assert resp.status_code == 200
data = resp.get_json()
assert data["okay"]
@pytest.mark.parametrize(
"url",
[
"/missing.txt",
"/admin/missing.txt",
"/admin/api/missing.txt",
"/admin/api/edit/missing.txt",
],
)
def test_missing_files(test_client, url):
resp = test_client.get(url)
assert resp.status_code == 404
@pytest.mark.parametrize(
"url, allowed",
[
("/", {"GET"}),
("/admin/api/recordinfo?path=%2F", {"GET"}),
("/admin/api/clean", {"POST"}),
("/admin/api/rawrecord", {"GET", "PUT"}),
],
)
@pytest.mark.parametrize("method", ["GET", "POST", "PUT"])
def test_allowed_methods(test_client, method, url, allowed):
if method not in allowed:
extra_allowed = {"OPTIONS", "HEAD"} if "GET" in allowed else {"OPTIONS"}
resp = test_client.open(url, method=method)
assert resp.status_code == 405
assert set(resp.allow) == allowed | extra_allowed