-
Notifications
You must be signed in to change notification settings - Fork 308
/
test_serve.py
626 lines (531 loc) · 21 KB
/
test_serve.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
from __future__ import annotations
import inspect
import os
import shutil
import sys
from pathlib import Path
from urllib.parse import parse_qsl
from urllib.parse import urljoin
from urllib.parse import urlparse
import flask
import pytest
from werkzeug.exceptions import NotFound
from lektor.admin.context import LektorContext
from lektor.admin.modules import livereload
from lektor.admin.modules import serve
from lektor.admin.webui import LektorApp
from lektor.admin.webui import LektorInfo
from lektor.assets import Asset
from lektor.builder import Artifact
from lektor.buildfailures import FailureController
from lektor.db import Record
from lektor.environment import Environment
from lektor.project import Project
@pytest.fixture(scope="session")
def dummy_app():
app = flask.Flask("lektor.admin")
app.config["SERVER_NAME"] = "example.org"
return app
@pytest.fixture
def dummy_app_context(dummy_app):
with dummy_app.app_context():
yield
def make_tooldrawer_config(
edit_url: str | None = None, artifact: Artifact | None = None
) -> serve.TooldrawerConfig:
return serve.TooldrawerConfig(
editUrl=edit_url,
livereloadConfig=serve.LivereloadConfig.from_artifact(artifact),
)
@pytest.mark.parametrize(
"html_text, expect_at_tail",
[
("<html><head></head><body></body></html>", False),
("<html>\n<head>\n </head>\n<body>\n</body>\n</html>", False),
("<html><head></ head ><body></body></html>", False),
("<html><head></HeAd><body></body></html>", False),
("<html></html>", True),
("<html><header></header><body></body></html>", True),
],
)
@pytest.mark.usefixtures("dummy_app_context")
def test_inject_tooldrawer(html_text, expect_at_tail):
eof_mark = "---EOF---"
config = make_tooldrawer_config("http://example.com/EDIT_URL")
rewritten = serve._inject_tooldrawer(f"{html_text}{eof_mark}".encode(), config)
html, _, tail = rewritten.decode("utf-8").rpartition(eof_mark)
if expect_at_tail:
assert config.editUrl in tail
assert config.editUrl not in html
else:
assert config.editUrl not in tail
assert config.editUrl in html
@pytest.mark.usefixtures("dummy_app_context")
def test_inject_tooldrawer_adds_livereload(dummy_app, make_dummy_artifact):
# Exercises a bug: the injected HTML includes backslash escapes within JSON
# strings. re.sub(pat, repl, s) doesn't work in that case, as it treats backslashes
# in repl specially. This results in an exception: "re.error: bad escape \u at
# position [...]"
dummy_app.register_blueprint(livereload.bp)
artifact = make_dummy_artifact(artifact_name="ARTIFACT_NAME")
config = make_tooldrawer_config("EDIT_URL", artifact)
assert b"ARTIFACT_NAME" in serve._inject_tooldrawer(
html=b"", tooldrawer_config=config
)
@pytest.mark.usefixtures("dummy_app_context")
def test_inject_tooldrawer_unicode_escapes():
config = make_tooldrawer_config("http://example.com/EDIT_URL?path=/foo&alt=de")
assert b"TOOLDRAWER_CONFIG" in serve._inject_tooldrawer(b"", config)
@pytest.fixture
def make_dummy_artifact(tmp_path):
def make_dummy_artifact(
artifact_name="test",
content="<html><head></head><body></body></html>",
):
path = tmp_path / f"{artifact_name}.html"
if content is not None:
path.write_text(content)
return Artifact(
build_state=None, # bogus
artifact_name=artifact_name,
dst_filename=str(path),
sources=[],
)
return make_dummy_artifact
@pytest.mark.usefixtures("dummy_app_context")
def test_send_html_for_editing(tmp_path, make_dummy_artifact):
artifact = make_dummy_artifact()
config = make_tooldrawer_config("EDIT_URL", artifact)
resp = serve._send_html_for_editing(artifact, config)
assert resp.mimetype == "text/html"
# pylint: disable=unsupported-membership-test
assert "EDIT_URL" in resp.get_data(True)
@pytest.mark.usefixtures("dummy_app_context")
def test_send_html_for_editing_etag_depends_on_edit_url(tmp_path, make_dummy_artifact):
artifact = make_dummy_artifact()
resp1 = serve._send_html_for_editing(artifact, make_tooldrawer_config("EDIT_URL1"))
resp2 = serve._send_html_for_editing(artifact, make_tooldrawer_config("EDIT_URL2"))
assert resp2.headers["ETag"] != resp1.headers["ETag"]
resp3 = serve._send_html_for_editing(artifact, make_tooldrawer_config("EDIT_URL1"))
assert resp3.headers["ETag"] == resp1.headers["ETag"]
@pytest.mark.usefixtures("dummy_app_context")
def test_send_html_for_editing_etag_depends_on_artifact_name(
tmp_path, make_dummy_artifact
):
artifact1 = make_dummy_artifact("test1")
artifact2 = make_dummy_artifact("test2")
resp1 = serve._send_html_for_editing(
artifact1, make_tooldrawer_config("EDIT_URL", artifact1)
)
resp2 = serve._send_html_for_editing(
artifact1, make_tooldrawer_config("EDIT_URL", artifact2)
)
assert resp2.headers["ETag"] != resp1.headers["ETag"]
resp3 = serve._send_html_for_editing(
artifact1, make_tooldrawer_config("EDIT_URL", artifact1)
)
assert resp3.headers["ETag"] == resp1.headers["ETag"]
def test_send_html_for_editing_raises_404(tmp_path, make_dummy_artifact):
artifact = make_dummy_artifact(content=None)
with pytest.raises(NotFound):
serve._send_html_for_editing(artifact, "EDIT_URL")
@pytest.mark.parametrize(
"filename, mimetype",
[
("junk.html", "text/html"),
("test.HTM", "text/html"),
("test.txt", "text/plain"),
("test.foo", "application/octet-stream"),
],
)
def test_deduce_mimetype(filename, mimetype):
assert serve._deduce_mimetype(filename) == mimetype
def test_checked_send_file(tmp_path, dummy_app):
filename = tmp_path / "file"
filename.write_text("content")
with dummy_app.test_request_context():
resp = serve._checked_send_file(filename, "image/png")
assert resp.headers["Content-Type"] == "image/png"
def test_checked_send_file_raises_404(tmp_path, dummy_app):
with dummy_app.test_request_context():
with pytest.raises(NotFound):
serve._checked_send_file(tmp_path / "missing.txt", "text/plain")
################################################################
def write_text(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(inspect.cleandoc(text))
@pytest.fixture(scope="module")
def project_path(tmp_path_factory, data_path):
"""Make our own private copy of the demo-project"""
demo = data_path / "demo-project"
path = tmp_path_factory.mktemp("test_serve") / "demo-project"
shutil.copytree(demo, path)
# Add a page which will fail to build
write_text(
path / "content/extra/build-failure/contents.lr",
"""
_model: page
---
title: Build Failure
---
_template: missing.html
""",
)
# Add a page which will build to a *.txt file
write_text(
path / "content/extra/test.txt/contents.lr",
"""
_model: page
---
title: Text File
""",
)
return path
@pytest.fixture
def output_path(tmp_path):
output_path = tmp_path / "output_path"
output_path.mkdir()
return output_path
@pytest.fixture(params=[None, ["FLAG"]])
def flag(request):
return request.param
@pytest.fixture
def app(output_path, project_path, flag):
project = Project.from_path(project_path)
env = Environment(project, load_plugins=False)
lektor_info = LektorInfo(env, output_path, extra_flags=flag)
app = LektorApp(lektor_info)
app.register_blueprint(serve.bp, url_prefix="/")
app.add_url_rule("/ADMIN/EDIT", "url.edit", build_only=True)
return app
################################################################
class TestArtifactServer:
# pylint: disable=no-self-use
@pytest.fixture
def a_s(self, app):
lektor_context = LektorContext._make(app.lektor_info)
return serve.ArtifactServer(lektor_context)
@pytest.fixture
def pad(self, app):
return app.lektor_info.env.new_pad()
@pytest.fixture
def failure_controller(self, pad, output_path):
return FailureController(pad, output_path)
@pytest.fixture
def failed_artifact(self, mocker, failure_controller):
artifact_name = "failed/index.html"
try:
raise RuntimeError("Failure")
except Exception:
failure_controller.store_failure(artifact_name, sys.exc_info())
try:
yield mocker.NonCallableMock(name="Artifact", artifact_name=artifact_name)
finally:
failure_controller.clear_failure(artifact_name)
@pytest.mark.parametrize(
"url_path, source_path",
[
("", "/"),
("index.html", "/"),
("de/", "/"),
("de/index.html", "/"),
("extra/", "/extra"),
("extra/index.html", "/extra"),
("de/extra/", "/extra"),
("de/extra/index.html", "/extra"),
("extra/long/path/", "/extra/slash-slug"),
("blog", "/blog@1"),
("blog/2015/12/post1/", "/blog/post1"),
("de/blog/", "/blog@1"),
("extra/container", "/extra/container"),
],
)
def test_resolve_url_path(self, a_s, url_path, source_path):
source = a_s.resolve_url_path(url_path)
assert isinstance(source, Record)
assert source.path == source_path
@pytest.mark.parametrize(
"url_path",
[
"static/demo.css",
"dir_with_index_html/",
"dir_with_index_htm/",
"static/",
],
)
def test_resolve_url_path_to_asset(self, a_s, url_path, project_path):
asset_path = project_path / "assets"
source = a_s.resolve_url_path(url_path)
assert isinstance(source, Asset)
assert Path(source.source_filename) == asset_path / url_path
@pytest.mark.parametrize(
"url_path",
[
"missing",
"dir_with_index_html/index.htm",
"dir_with_index_htm/index.html",
"static/index.html",
],
)
def test_resolve_url_path_raises_404(self, a_s, url_path):
with pytest.raises(NotFound):
a_s.resolve_url_path(url_path)
@pytest.mark.parametrize(
"dir_name, index_name",
[
("dir_with_index_html", "index.html"),
("dir_with_index_htm", "index.htm"),
],
)
def test_resolve_directory_index(self, a_s, pad, dir_name, index_name):
directory = pad.asset_root.get_child(dir_name)
index = a_s.resolve_directory_index(directory)
assert index.name == index_name
def test_resolve_directory_index_raises_404(self, a_s, pad):
directory = pad.asset_root.get_child("static")
with pytest.raises(NotFound):
a_s.resolve_directory_index(directory)
@pytest.mark.parametrize(
"url_path, artifact_name, failing",
[
("de/extra/", "de/extra/index.html", False),
("dir_with_index_html/", None, False),
("dir_with_index_htm/", None, False),
("dir_with_index_html/index.html", "dir_with_index_html/index.html", False),
("dir_with_index_htm/index.htm", "dir_with_index_htm/index.htm", False),
("static/", None, False),
("/extra/build-failure", "extra/build-failure/index.html", True),
("/extra/file.ext", "extra/file.ext", False),
],
)
def test_build_primary_artifact(self, a_s, url_path, artifact_name, failing):
source = a_s.resolve_url_path(url_path)
assert source is not None
if artifact_name is None:
with pytest.raises(NotFound):
a_s.build_primary_artifact(source)
else:
artifact, failure = a_s.build_primary_artifact(source)
assert artifact.artifact_name == artifact_name
assert (failure is not None) == failing
def test_build_primary_artifact_raises_404(self, a_s, pad):
source = pad.get("/extra/container") # has _hidden = yes
assert source is not None
with pytest.raises(NotFound):
a_s.build_primary_artifact(source)
@pytest.mark.parametrize("edit_url", [None, "EDIT_URL"])
def test_handle_build_failure(self, app, a_s, mocker, edit_url):
failure = mocker.NonCallableMock(
name="BuildFailure",
data={k: k.upper() for k in ("artifact", "exception", "traceback")},
)
with app.test_request_context("failing/"):
resp = a_s.handle_build_failure(failure, make_tooldrawer_config(edit_url))
assert resp.status_code == 200
assert "TRACEBACK" in resp.get_data(True)
if edit_url is not None:
assert edit_url in resp.get_data(True)
@pytest.mark.parametrize(
"path, kw, expect",
[
("/blog", {"page_num": 1}, {("path", "/blog")}),
("/extra", {"alt": "de"}, {("path", "/extra"), ("alt", "de")}),
("/extra", {"alt": "en"}, {("path", "/extra")}),
],
)
def test_get_edit_url(self, a_s, app, pad, path, kw, expect):
source = pad.get(path, **kw)
with app.test_request_context(path):
edit_url = a_s.get_edit_url(source)
if expect is None:
assert edit_url is None
else:
url = urlparse(edit_url)
assert url.path == "/ADMIN/EDIT"
assert set(parse_qsl(url.query)) == expect
@pytest.mark.parametrize(
"url_path, location",
[
("extra", "extra/"),
("dir_with_index_html", "dir_with_index_html/"),
],
)
def test_serve_artifact_adds_slash(self, a_s, app, url_path, location):
with app.test_request_context(f"/{url_path}"):
resp = a_s.serve_artifact(url_path)
assert resp.status_code in (301, 308)
assert resp.location == location
@pytest.mark.parametrize(
"url_path, mimetype, is_editable",
[
("projects/coffee/", "text/html", True), # Page
("extra/test.txt", "text/plain", False), # non-HTML Page
("hello.txt", "text/plain", False), # Attachment
# Check that build-failure report has edit pencil
("extra/build-failure/", "text/html", True), # Failing build
# Asset file
("static/demo.css", "text/css", False),
# Page with hidden parent
("extra/container/a/", "text/html", True),
# Asset file with hidden parent
("extra/container/hello.txt", "text/plain", False),
# Asset directories with index.{htm,html}
("dir_with_index_html/", "text/html", False),
("dir_with_index_htm/", "text/html", False),
("dir_with_index_html/index.html", "text/html", False),
("dir_with_index_htm/index.htm", "text/html", False),
],
)
def test_serve_artifact_serves_artifact(
self, a_s, app, url_path, mimetype, is_editable
):
with app.test_request_context(f"/{url_path}"):
resp = a_s.serve_artifact(url_path)
assert resp.status_code == 200
assert resp.mimetype == mimetype
data = b"".join(resp.get_app_iter(flask.request.environ)).decode("utf-8")
assert ("/ADMIN/EDIT?" in data) == is_editable
@pytest.mark.parametrize(
"url_path",
[
"test@192.jpg", # sub-artifact — no resolvable to source object
"extra/container/", # hidden page
"static/", # Asset directory without index.html
"dir_with_index_html/index.htm",
"dir_with_index_htm/index.html",
],
)
def test_serve_artifact_raises_404(self, a_s, app, url_path):
with app.test_request_context(f"/{url_path}"):
with pytest.raises(NotFound):
a_s.serve_artifact(url_path)
################################################################
def test_serve_artifact(app):
with app.test_request_context("/static/demo.css"):
resp = serve.serve_artifact("static/demo.css")
assert resp.status_code == 200
assert resp.mimetype == "text/css"
def test_serve_file(output_path, app):
filename = output_path / "test.txt"
filename.write_text("content")
with app.test_request_context("/test.txt"):
resp = serve.serve_file("test.txt")
content = b"".join(resp.get_app_iter(flask.request.environ))
assert resp.mimetype == "text/plain"
assert content == b"content"
@pytest.mark.parametrize("output_path", [Path("relative")])
def test_serve_file_with_relative_output_path(output_path, app, tmp_path):
# This excercises a bug having to do with serving files when
# Lektor is given a relative output directory.
#
# E.g. via `lektor server -O outdir`
#
save_cwd = os.getcwd()
os.chdir(tmp_path)
try:
output_path.mkdir()
test_serve_file(output_path, app)
finally:
os.chdir(save_cwd)
@pytest.mark.parametrize("index_html", ["index.html", "index.htm"])
def test_serve_file_dir_handling(output_path, app, index_html):
filename = output_path / "adir" / index_html
filename.parent.mkdir()
filename.write_text("index")
with app.test_request_context("/adir"):
resp = serve.serve_file("adir")
assert resp.status_code in (301, 308)
assert resp.location == "adir/"
with app.test_request_context("/adir/"):
resp = serve.serve_file("adir/")
content = b"".join(resp.get_app_iter(flask.request.environ))
assert resp.status_code == 200
assert content == b"index"
@pytest.mark.parametrize(
"path",
[
"missing",
"example/container", # hidden page
"adir/", # no adir/index.{html,htm} exists
"adir/../top.txt", # ".." not allowed in path
"../adir/index.txt", # points outside of output_path
"adir/index.txt/../index.txt",
"adir/index.txt/../../top.txt",
"adir/index.txt/../../adir/index.txt",
],
)
def test_serve_file_raises_404(output_path, app, path):
not_an_index = output_path / "adir/index.txt"
not_an_index.parent.mkdir()
not_an_index.write_text("non-index")
output_path.joinpath("top.txt").write_text("top")
with app.test_request_context(path):
with pytest.raises(NotFound):
serve.serve_file(path)
################################################################
@pytest.mark.parametrize(
"path, status, mimetype, content",
[
("/hello.txt", 200, "text/plain", "Hello I am an Attachment"),
("/missing/", 404, "text/html", "The requested URL was not found"),
("/extra/container/", 404, "text/html", "Record is hidden"),
],
)
def test_serve(app, path, status, mimetype, content):
with app.test_client() as c:
resp = c.get(path)
assert resp.status_code == status
assert resp.mimetype == mimetype
assert content in resp.get_data(True)
def test_serve_from_file(app, output_path):
filename = output_path / "sub-artifact.txt"
filename.write_text("sub-artifact")
with app.test_client() as c:
resp = c.get("/sub-artifact.txt")
assert resp.status_code == 200
assert resp.mimetype == "text/plain"
@pytest.mark.parametrize(
"path_info, base_url, location",
[
("/extra", "http://example.org/pfx/", "http://example.org/pfx/extra/"),
(
"/dir_with_index_html?qs",
"http://localhost/",
"http://localhost/dir_with_index_html/?qs",
),
(
"/projects/coffee",
"http://localhost/pfx/",
"http://localhost/pfx/projects/coffee/",
),
("/adir", "http://localhost/", "http://localhost/adir/"),
("/adir/bdir", "http://localhost/", "http://localhost/adir/bdir/"),
],
)
def test_serve_add_slash_redirect_integration(
app, output_path, path_info, base_url, location
):
output_path.joinpath("adir/bdir").mkdir(parents=True)
with app.test_client() as c:
resp = c.get(path_info, base_url=base_url)
assert resp.status_code in (301, 308)
# Be careful to accept either absolute or relative URLs in resp.location
# See https://httpwg.org/specs/rfc7231.html#header.location
request_url = urljoin(base_url, path_info.lstrip("/"))
assert urljoin(request_url, resp.location) == location
@pytest.fixture
def scratch_app(scratch_env, output_path):
lektor_info = LektorInfo(scratch_env, output_path)
app = LektorApp(lektor_info)
app.register_blueprint(serve.bp, url_prefix="/")
app.add_url_rule("/ADMIN/EDIT", "url.edit", build_only=True)
return app
def test_serve_custom_404(scratch_app, scratch_project_data):
custom_404 = scratch_project_data / "assets/404.html"
custom_404.parent.mkdir(exist_ok=True)
custom_404.write_text("custom 404")
with scratch_app.test_client() as c:
resp = c.get("/missing.txt")
assert resp.status_code == 404
assert resp.mimetype == "text/html"
assert resp.get_data(True) == "custom 404"