Debian Codegraph @

tests/test_flask_flatpages.py

raw
1 # coding: utf8
2 """
3 Tests for Flask-FlatPages
4 ~~~~~~~~~~~~~~~~~~~~~~~~~
5
6 :copyright: (c) 2010 by Simon Sapin.
7 :license: BSD, see LICENSE for more details.
8 """
9
10 from __future__ import annotations
11 import datetime
12 import operator
13 import os
14 import shutil
15 import sys
16 import unicodedata
17 import flask
18
19
20 import yaml
21 import pytest
22 from flask import Flask
23 from flask_flatpages import FlatPages, pygments_style_defs
24 from flask_flatpages.imports import PygmentsHtmlFormatter
25 from werkzeug.exceptions import NotFound
26
27
28 utc = datetime.timezone.utc
29 from unittest.mock import patch
30
31
32 @pytest.fixture
33 def default_paths():
34 return set(
35 [
36 "codehilite",
37 "extra",
38 "foo",
39 "foo/bar",
40 "foo/lorem/ipsum",
41 "headerid",
42 "hello",
43 "meta_styles/closing_block_only",
44 "meta_styles/yaml_style",
45 "meta_styles/jekyll_style",
46 "meta_styles/multi_line",
47 "meta_styles/no_meta",
48 "toc",
49 ]
50 )
51
52
53 @pytest.fixture
54 def all_paths(default_paths):
55 return default_paths | {"foo/42/not_a_page", "not_a_page"}
56
57
58 @pytest.fixture
59 def paths_excluding(all_paths):
60 def filtered_paths(*args):
61 paths = all_paths
62 for arg in args:
63 paths = paths.remove(arg)
64 return paths
65
66 return filtered_paths
67
68
69 def _check_auto_reset(pages: FlatPages, should_reset: bool):
70 bar = pages.get("foo/bar")
71 assert bar.body == ""
72
73 filename = os.path.join(pages.root, "foo", "bar.html")
74 with open(filename, "w") as fd:
75 fd.write("\nrewritten")
76
77 # simulate a request (before_request functions are called)
78 # pages.reload() is not call explicitly
79 with flask.current_app.test_request_context():
80 flask.current_app.preprocess_request()
81
82 bar2 = pages.get("foo/bar")
83 if should_reset:
84 assert bar2.body == "rewritten"
85 assert bar2 is not bar
86 else:
87 assert bar2.body == ""
88 assert bar2 is bar
89
90
91 def test_caching(app_with_context, temp_pages):
92 pages = temp_pages(app_with_context)
93 foo = pages.get("foo")
94 bar = pages.get("foo/bar")
95
96 filename = os.path.join(pages.root, "foo", "bar.html")
97 with open(filename, "w") as fd:
98 fd.write("\nrewritten")
99
100 pages.reload()
101
102 foo2 = pages.get("foo")
103 bar2 = pages.get("foo/bar")
104
105 # Page objects are cached and unmodified files (according to the
106 # modification date) are not parsed again.
107 assert foo2 is foo
108 assert bar2 is not bar
109 assert bar2.body != bar.body
110
111
112 def test_configured_auto_reset(app_with_context, temp_pages):
113 app_with_context.config["FLATPAGES_AUTO_RELOAD"] = True
114 pages = temp_pages(app_with_context)
115 _check_auto_reset(pages, True)
116
117
118 def test_configured_no_auto_reset(app_with_context, temp_pages):
119 app_with_context.debug = True
120 app_with_context.config["FLATPAGES_AUTO_RELOAD"] = False
121 pages = temp_pages(app_with_context)
122 _check_auto_reset(pages, should_reset=False)
123
124
125 def test_consistency(app_with_context, flatpages_factory):
126 pages = flatpages_factory(app_with_context)
127 for page in pages:
128 assert pages.get(page.path) is page
129
130
131 def test_debug_auto_reset(app_with_context, temp_pages):
132 app_with_context.debug = True
133 pages = temp_pages(app_with_context)
134 _check_auto_reset(pages, should_reset=True)
135
136
137 def test_default_no_auto_reset(app_with_context, temp_pages):
138 pages = temp_pages(app_with_context)
139 _check_auto_reset(pages, should_reset=False)
140
141
142 @pytest.fixture
143 def pages_with_extension(app_with_context, flatpages_factory):
144 def _initialised_pages(extensions):
145 app_with_context.config["FLATPAGES_EXTENSION"] = extensions
146 flatpages = flatpages_factory(app_with_context)
147 return set(page.path for page in flatpages)
148
149 yield _initialised_pages
150
151
152 def test_extension_sequence(all_paths, pages_with_extension):
153 assert all_paths == pages_with_extension([".html", ".txt"])
154
155
156 def test_extension_comma(all_paths, pages_with_extension):
157 assert all_paths == pages_with_extension(".html,.txt")
158
159
160 def test_extension_set(all_paths, pages_with_extension):
161 assert all_paths == pages_with_extension(set([".html", ".txt"]))
162
163
164 def test_extension_tuple(all_paths, pages_with_extension):
165 assert all_paths == pages_with_extension((".html", ".txt"))
166
167
168 def test_catch_conflicting_paths(app_with_context, temp_pages):
169 app_with_context.config["FLATPAGES_EXTENSION"] = [".html", ".txt"]
170 pages = temp_pages(app_with_context)
171 original_file = os.path.join(pages.root, "hello.html")
172 target_file = os.path.join(pages.root, "hello.txt")
173 shutil.copyfile(original_file, target_file)
174 pages.reload()
175 with pytest.raises(ValueError):
176 pages.get("hello")
177
178
179 def test_case_insensitive(app_with_context, temp_pages, all_paths):
180 app_with_context.config["FLATPAGES_EXTENSION"] = [".html", ".txt"]
181 app_with_context.config["FLATPAGES_CASE_INSENSITIVE"] = True
182 pages = temp_pages(app_with_context)
183 original_file = os.path.join(pages.root, "hello.html")
184 upper_file = os.path.join(pages.root, "Hello.html")
185 txt_file = os.path.join(pages.root, "hello.txt")
186 shutil.move(original_file, upper_file)
187 pages.reload()
188 assert all_paths == set(p.path for p in pages)
189 shutil.copyfile(upper_file, txt_file)
190 pages.reload()
191 with pytest.raises(ValueError):
192 pages.get("hello")
193
194
195 def test_get(app_with_context, flatpages_factory):
196 pages = flatpages_factory(app_with_context)
197 assert pages.get("foo/bar").path == "foo/bar"
198 assert pages.get("nonexistent") == None
199 assert pages.get("nonexistent", 42) == 42
200
201
202 def test_get_or_404(app_with_context, flatpages_factory):
203 pages = flatpages_factory(app_with_context)
204 assert pages.get_or_404("foo/bar").path == "foo/bar"
205 with pytest.raises(NotFound):
206 pages.get_or_404("nonexistant")
207
208
209 def test_iter(app_with_context, flatpages_factory, default_paths):
210 pages = flatpages_factory(app_with_context)
211 assert set(p.path for p in pages) == default_paths
212
213
214 def test_lazy_loading(app_with_context, temp_pages):
215 pages = temp_pages(app_with_context)
216 bar = pages.get("foo/bar")
217 # bar.html is normally empty
218 assert bar.meta == {}
219 assert bar.body == ""
220 filename = os.path.join(pages.root, "foo", "bar.html")
221 # write as pages is already constructed
222 with open(filename, "a") as fd:
223 fd.write("a: b\n\nc")
224 bar = pages.get("foo/bar")
225 assert bar.meta == {}
226 assert bar.body == ""
227 pages.reload()
228 bar = pages.get("foo/bar")
229 # bar was just loaded from the disk
230 assert bar.meta == {"a": "b"}
231 assert bar.body == "c"
232
233
234 def test_markdown(app_with_context, flatpages_factory):
235 pages = flatpages_factory(app_with_context)
236 foo = pages.get("foo")
237 assert foo.body == "Foo *bar*\n"
238 assert foo.html == "<p>Foo <em>bar</em></p>"
239
240
241 def test_instance_relative(tmpdir):
242 source = os.path.join(os.path.dirname(__file__), "pages")
243 dest = os.path.join(tmpdir, "instance", "pages")
244 shutil.copytree(source, dest)
245 app = Flask(__name__, instance_path=os.path.join(tmpdir, "instance"))
246 app.config["FLATPAGES_INSTANCE_RELATIVE"] = True
247 pages = FlatPages(app)
248 with app.app_context():
249 bar = pages.get("foo/bar")
250 assert bar is not None
251
252
253 def test_multiple_instance(app_with_context, temp_pages):
254 """
255 This does a very basic test to see if two instances of FlatPages,
256 one default instance and one with a name, do pick up the different
257 config settings.
258 """
259 app_with_context.debug = True
260 app_with_context.config["FLATPAGES_DUMMY"] = True
261 app_with_context.config["FLATPAGES_FUBAR_DUMMY"] = False
262 p1 = temp_pages(app_with_context)
263 assert p1.config("DUMMY") == app_with_context.config["FLATPAGES_DUMMY"]
264 p2 = temp_pages(app_with_context, "fubar")
265 assert (
266 p2.config("DUMMY") == app_with_context.config["FLATPAGES_FUBAR_DUMMY"]
267 )
268
269
270 def _assert_unicode(pages: FlatPages):
271 hello = pages.get("hello")
272 assert hello.meta == {"title": "世界", "template": "article.html"}
273 assert hello["title"] == "世界"
274 assert hello.body == "Hello, *世界*!\n"
275 # Markdown
276 assert hello.html == "<p>Hello, <em>世界</em>!</p>"
277
278
279 def test_legacy_parser(
280 app_with_context, flatpages_factory, default_paths, mocker
281 ):
282 app_with_context.config["FLATPAGES_LEGACY_META_PARSER"] = True
283 yaml_mock = mocker.Mock(side_effect=ValueError("CannotHappen"))
284 legacy_mock = mocker.Mock(return_value=(dict(), "Foo"))
285 mocker.patch(
286 "flask_flatpages.flatpages.legacy_parser", legacy_mock
287 )
288 mocker.patch(
289 "flask_flatpages.flatpages.libyaml_parser", yaml_mock
290 )
291 pages = flatpages_factory(app_with_context)
292 assert {page.path for page in pages} == default_paths
293 yaml_mock.assert_not_called()
294 assert legacy_mock.call_count == len(list(pages))
295
296
297 def test_other_encoding(app_with_context, flatpages_factory):
298 pages = flatpages_factory(app_with_context)
299 app_with_context.config["FLATPAGES_ENCODING"] = "shift_jis"
300 app_with_context.config["FLATPAGES_ROOT"] = "pages_shift_jis"
301 _assert_unicode(pages)
302
303
304 def test_other_extension(
305 app_with_context, flatpages_factory, all_paths, default_paths
306 ):
307 pages = flatpages_factory(app_with_context)
308 txt_paths = all_paths - default_paths
309 app_with_context.config["FLATPAGES_EXTENSION"] = ".txt"
310 found_paths = {page.path for page in pages}
311 assert found_paths == txt_paths
312 assert found_paths.isdisjoint(default_paths)
313
314
315 def test_other_html_renderer():
316 def body_renderer(body):
317 return body.upper()
318
319 def page_renderer(body, pages, page):
320 return page.body.upper()
321
322 def pages_renderer(body, pages):
323 return pages.get("hello").body.upper()
324
325 renderers = filter(
326 None,
327 (
328 operator.methodcaller("upper"),
329 None,
330 body_renderer,
331 page_renderer,
332 pages_renderer,
333 ),
334 )
335
336 for renderer in renderers:
337 app = Flask(__name__)
338 pages = FlatPages(app)
339 with app.app_context():
340 app.config["FLATPAGES_HTML_RENDERER"] = renderer
341 hello = pages.get("hello")
342 assert hello.body == "Hello, *世界*!\n"
343 # Upper-case, markdown not interpreted
344 assert hello.html == "HELLO, *世界*!\n"
345
346
347 @pytest.mark.skipif(
348 PygmentsHtmlFormatter is None, reason="Pygments not installed"
349 )
350 def test_pygments_style_defs():
351 styles = pygments_style_defs()
352 assert ".codehilite" in styles
353
354
355 def test_reloading(app_with_context, temp_pages):
356 pages = temp_pages(app_with_context)
357 bar = pages.get("foo/bar")
358 # bar.html is normally empty
359 assert bar.meta == {}
360 assert bar.body == ""
361
362 filename = os.path.join(pages.root, "foo", "bar.html")
363 # rewrite already loaded page
364 with open(filename, "w") as fd:
365 # The newline is a separator between the (empty) metadata
366 # and the source 'first'
367 fd.write("\nfirst rewrite")
368
369 bar2 = pages.get("foo/bar")
370 # the disk is not hit again until requested
371 assert bar2.meta == {}
372 assert bar2.body == ""
373 assert bar2 is bar
374
375 # request reloading
376 pages.reload()
377
378 # write again
379 with open(filename, "w") as fd:
380 fd.write("\nsecond rewrite")
381
382 # get another page
383 pages.get("hello")
384
385 # write again
386 with open(filename, "w") as fd:
387 fd.write("\nthird rewrite")
388
389 # All pages are read at once when any is used
390 bar3 = pages.get("foo/bar")
391 assert bar3.meta == {}
392 assert bar3.body == "second rewrite" # not third
393 # Page objects are not reused when a file is re-read.
394 assert bar3 is not bar2
395
396 # Removing does not trigger reloading either
397 os.remove(filename)
398
399 bar4 = pages.get("foo/bar")
400 assert bar4.meta == {}
401 assert bar4.body == "second rewrite"
402 assert bar4 is bar3
403
404 pages.reload()
405
406 bar5 = pages.get("foo/bar")
407 assert bar5 is None
408
409 # Reloading twice does not trigger an exception
410 pages.reload()
411 pages.reload()
412
413
414 def test_unicode(app_with_context, flatpages_factory):
415 pages = flatpages_factory(app_with_context)
416 _assert_unicode(pages)
417
418
419 def test_unicode_filenames(app_with_context, temp_pages, default_paths):
420 def safe_unicode(sequence):
421 if sys.platform != "darwin":
422 return sequence
423 return ''.join(unicodedata.normalize("NFC", item) for item in sequence)
424
425 pages = temp_pages(app_with_context)
426 assert {page.path for page in pages} == default_paths
427
428 os.remove(os.path.join(pages.root, "foo", "lorem", "ipsum.html"))
429 open(os.path.join(pages.root, "Unïcôdé.html"), "w").close()
430 pages.reload()
431
432 assert set(safe_unicode(page.path) for page in pages) == (
433 (default_paths | {"Unïcôdé"}) - {"foo/lorem/ipsum"}
434 )
435
436
437 def test_yaml_meta(app_with_context, flatpages_factory):
438 pages = flatpages_factory(app_with_context)
439 foo = pages.get("foo")
440 assert foo.meta == {
441 "title": "Foo > bar",
442 "created": datetime.date(2010, 12, 11),
443 "updated": datetime.datetime(2015, 2, 9, 10, 59, 0),
444 "updated_iso": datetime.datetime(2015, 2, 9, 10, 59, 0, tzinfo=utc),
445 "versions": [3.14, 42],
446 }
447 assert foo["title"] == "Foo > bar"
448 assert foo["created"] == datetime.date(2010, 12, 11)
449 assert foo["updated"] == datetime.datetime(2015, 2, 9, 10, 59, 0)
450 assert foo["updated_iso"] == datetime.datetime(
451 2015, 2, 9, 10, 59, 0, tzinfo=utc
452 )
453 assert foo["versions"] == [3.14, 42]
454 with pytest.raises(KeyError):
455 foo["nonexistent"]
456
457
458 def test_no_meta(app_with_context, temp_pages):
459 pages = temp_pages(app_with_context)
460 no_meta = pages.get("meta_styles/no_meta")
461 assert no_meta.meta == {}
462 filename = os.path.join(pages.root, "meta_styles", "no_meta.html")
463 with open(filename, "w") as f_:
464 f_.write("\n Hello, there's no metadata here.")
465 pages.reload()
466 no_meta = pages.get("meta_styles/no_meta")
467 assert no_meta.meta == {}
468 with open(filename, "w") as f_:
469 f_.write("---\n---\nHello, there's no metadata here.")
470 pages.reload()
471 no_meta = pages.get("meta_styles/no_meta")
472 assert no_meta.meta == {}
473 with open(filename, "w") as f_:
474 f_.write("---\n...\nHello, there's no metadata here.")
475 pages.reload()
476 no_meta = pages.get("meta_styles/no_meta")
477 assert no_meta.meta == {}
478 with open(filename, "w") as f_:
479 f_.write("#Hello, there's no metadata here.")
480 pages.reload()
481 no_meta = pages.get("meta_styles/no_meta")
482 assert no_meta.meta == {}
483
484
485 def test_meta_closing_only(app_with_context, temp_pages):
486 pages = temp_pages(app_with_context)
487 page = pages.get("meta_styles/closing_block_only")
488 assert page.meta == {"hello": "world"}
489 filename = os.path.join(
490 pages.root, "meta_styles", "closing_block_only.html"
491 )
492 with open(filename, "w") as f:
493 f.write("hello: world\n...\nFoo")
494 pages.reload()
495 page = pages.get("meta_styles/closing_block_only")
496 assert page.meta == {"hello": "world"}
497
498
499 def test_jekyll_style_meta(app_with_context, temp_pages):
500 pages = temp_pages(app_with_context)
501 jekyll_style = pages.get("meta_styles/jekyll_style")
502 assert jekyll_style.meta == {"hello": "world"}
503 assert jekyll_style.body == "Foo"
504 filename = os.path.join(pages.root, "meta_styles", "jekyll_style.html")
505 with open(filename, "r") as f_:
506 lines = f_.readlines()
507 with open(filename, "w") as f_:
508 f_.write("\n".join(lines[1:]))
509 pages.reload()
510 jekyll_style = pages.get("meta_styles/jekyll_style")
511 assert jekyll_style.meta == {"hello": "world"}
512 assert jekyll_style.body == "Foo"
513
514
515 def test_yaml_style_meta(app_with_context, temp_pages):
516 pages = temp_pages(app_with_context)
517 yaml_style = pages.get("meta_styles/yaml_style")
518 yaml_style.meta == {"hello": "world"}
519 yaml_style.body == "Foo"
520 filename = os.path.join(pages.root, "meta_styles", "yaml_style.html")
521 with open(filename, "r") as f_:
522 lines = f_.readlines()
523 with open(filename, "w") as f_:
524 f_.write("\n".join(lines[1:]))
525 pages.reload()
526 yaml_style = pages.get("meta_styles/yaml_style")
527 yaml_style.meta == {"hello": "world"}
528 yaml_style.body == "Foo"
529
530
531 def test_multi_line(app_with_context, flatpages_factory):
532 pages = flatpages_factory(app_with_context)
533 multi_line = pages.get("meta_styles/multi_line")
534 assert multi_line.body == "Foo"
535 assert "multi_line_string" in multi_line.meta
536 assert "\n" in multi_line.meta["multi_line_string"]
537
538
539 def test_parser_error(app_with_context, temp_pages):
540 pages = temp_pages(app_with_context)
541 with open(os.path.join(pages.root, "bad_file_test.html"), "w") as f:
542 f.write("Hello World \u000b")
543 with pytest.raises(yaml.reader.ReaderError, match=r".*bad_file_test.*"):
544 pages.get("bad_file_test")