aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_utils.py
blob: 19966790cafd75e62be8a0431027210be026d80f (plain) (blame)
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
"""
Testing Nikolas utility functions.
"""

import os
from unittest import mock

import pytest
import lxml.html

from nikola import metadata_extractors
from nikola.plugins.task.sitemap import get_base_path as sitemap_get_base_path
from nikola.post import get_meta
from nikola.utils import (
    TemplateHookRegistry,
    TranslatableSetting,
    demote_headers,
    get_asset_path,
    get_crumbs,
    get_theme_chain,
    get_translation_candidate,
    write_metadata,
    bool_from_meta,
)


def test_getting_metadata_from_content(post):
    post.source_path = "file_with_metadata"
    post.metadata_path = "file_with_metadata.meta"

    file_content = """\
.. title: Nikola needs more tests!
.. slug: write-tests-now
.. date: 2012/09/15 19:52:05
.. tags:
.. link:
.. description:

Post content
"""
    opener_mock = mock.mock_open(read_data=file_content)
    with mock.patch("nikola.post.io.open", opener_mock, create=True):
        meta = get_meta(post, None)[0]

    assert "Nikola needs more tests!" == meta["title"]
    assert "write-tests-now" == meta["slug"]
    assert "2012/09/15 19:52:05" == meta["date"]
    assert "tags" not in meta
    assert "link" not in meta
    assert "description" not in meta


def test_get_title_from_fname(post):
    post.source_path = "file_with_metadata"
    post.metadata_path = "file_with_metadata.meta"

    file_content = """\
.. slug: write-tests-now
.. date: 2012/09/15 19:52:05
.. tags:
.. link:
.. description:
"""
    opener_mock = mock.mock_open(read_data=file_content)
    with mock.patch("nikola.post.io.open", opener_mock, create=True):
        meta = get_meta(post, None)[0]

    assert "file_with_metadata" == meta["title"]
    assert "write-tests-now" == meta["slug"]
    assert "2012/09/15 19:52:05" == meta["date"]
    assert "tags" not in meta
    assert "link" not in meta
    assert "description" not in meta


def test_use_filename_as_slug_fallback(post):
    post.source_path = "Slugify this"
    post.metadata_path = "Slugify this.meta"

    file_content = """\
.. title: Nikola needs more tests!
.. date: 2012/09/15 19:52:05
.. tags:
.. link:
.. description:

Post content
"""
    opener_mock = mock.mock_open(read_data=file_content)
    with mock.patch("nikola.post.io.open", opener_mock, create=True):
        meta = get_meta(post, None)[0]

    assert "Nikola needs more tests!" == meta["title"]
    assert "slugify-this" == meta["slug"]
    assert "2012/09/15 19:52:05" == meta["date"]
    assert "tags" not in meta
    assert "link" not in meta
    assert "description" not in meta


@pytest.mark.parametrize(
    "unslugify, expected_title", [(True, "Dub dub title"), (False, "dub_dub_title")]
)
def test_extracting_metadata_from_filename(post, unslugify, expected_title):
    post.source_path = "2013-01-23-the_slug-dub_dub_title.md"
    post.metadata_path = "2013-01-23-the_slug-dub_dub_title.meta"

    post.config[
        "FILE_METADATA_REGEXP"
    ] = r"(?P<date>\d{4}-\d{2}-\d{2})-(?P<slug>.*)-(?P<title>.*)\.md"
    post.config["FILE_METADATA_UNSLUGIFY_TITLES"] = unslugify

    no_metadata_opener = mock.mock_open(read_data="No metadata in the file!")
    with mock.patch("nikola.post.io.open", no_metadata_opener, create=True):
        meta = get_meta(post, None)[0]

    assert expected_title == meta["title"]
    assert "the_slug" == meta["slug"]
    assert "2013-01-23" == meta["date"]


def test_get_meta_slug_only_from_filename(post):
    post.source_path = "some/path/the_slug.md"
    post.metadata_path = "some/path/the_slug.meta"

    no_metadata_opener = mock.mock_open(read_data="No metadata in the file!")
    with mock.patch("nikola.post.io.open", no_metadata_opener, create=True):
        meta = get_meta(post, None)[0]

    assert "the_slug" == meta["slug"]


@pytest.mark.parametrize(
    "level, input_str, expected_output",
    [
        pytest.param(
            0,
            """
     <h1>header 1</h1>
     <h2>header 2</h2>
     <h3>header 3</h3>
     <h4>header 4</h4>
     <h5>header 5</h5>
     <h6>header 6</h6>
     """,
            """
     <h1>header 1</h1>
     <h2>header 2</h2>
     <h3>header 3</h3>
     <h4>header 4</h4>
     <h5>header 5</h5>
     <h6>header 6</h6>
     """,
            id="by zero",
        ),
        pytest.param(
            1,
            """
     <h1>header 1</h1>
     <h2>header 2</h2>
     <h3>header 3</h3>
     <h4>header 4</h4>
     <h5>header 5</h5>
     <h6>header 6</h6>
     """,
            """
     <h2>header 1</h2>
     <h3>header 2</h3>
     <h4>header 3</h4>
     <h5>header 4</h5>
     <h6>header 5</h6>
     <h6>header 6</h6>
     """,
            id="by one",
        ),
        pytest.param(
            2,
            """
     <h1>header 1</h1>
     <h2>header 2</h2>
     <h3>header 3</h3>
     <h4>header 4</h4>
     <h5>header 5</h5>
     <h6>header 6</h6>
     """,
            """
     <h3>header 1</h3>
     <h4>header 2</h4>
     <h5>header 3</h5>
     <h6>header 4</h6>
     <h6>header 5</h6>
     <h6>header 6</h6>
     """,
            id="by two",
        ),
        pytest.param(
            -1,
            """
     <h1>header 1</h1>
     <h2>header 2</h2>
     <h3>header 3</h3>
     <h4>header 4</h4>
     <h5>header 5</h5>
     <h6>header 6</h6>
     """,
            """
     <h1>header 1</h1>
     <h1>header 2</h1>
     <h2>header 3</h2>
     <h3>header 4</h3>
     <h4>header 5</h4>
     <h5>header 6</h5>
     """,
            id="by minus one",
        ),
    ],
)
def test_demoting_headers(level, input_str, expected_output):
    doc = lxml.html.fromstring(input_str)
    outdoc = lxml.html.fromstring(expected_output)
    demote_headers(doc, level)
    assert lxml.html.tostring(outdoc) == lxml.html.tostring(doc)


def test_TranslatableSettingsTest_with_string_input():
    """Test ing translatable settings with string input."""
    inp = "Fancy Blog"
    setting = TranslatableSetting("TestSetting", inp, {"xx": ""})
    setting.default_lang = "xx"
    setting.lang = "xx"

    assert inp == str(setting)
    assert inp == setting()  # no language specified
    assert inp == setting("xx")  # real language specified
    assert inp == setting("zz")  # fake language specified
    assert setting.lang == "xx"
    assert setting.default_lang == "xx"


def test_TranslatableSetting_with_dict_input():
    """Tests for translatable setting with dict input."""
    inp = {"xx": "Fancy Blog", "zz": "Schmancy Blog"}

    setting = TranslatableSetting("TestSetting", inp, {"xx": "", "zz": ""})
    setting.default_lang = "xx"
    setting.lang = "xx"

    assert inp["xx"] == str(setting)
    assert inp["xx"] == setting()  # no language specified
    assert inp["xx"] == setting("xx")  # real language specified
    assert inp["zz"] == setting("zz")  # fake language specified
    assert inp["xx"] == setting("ff")


def test_TranslatableSetting_with_language_change():
    """Test translatable setting with language change along the way."""
    inp = {"xx": "Fancy Blog", "zz": "Schmancy Blog"}

    setting = TranslatableSetting("TestSetting", inp, {"xx": "", "zz": ""})
    setting.default_lang = "xx"
    setting.lang = "xx"

    assert inp["xx"] == str(setting)
    assert inp["xx"] == setting()

    # Change the language.
    # WARNING: DO NOT set lang locally in real code!  Set it globally
    #          instead! (TranslatableSetting.lang = ...)
    # WARNING: TranslatableSetting.lang is used to override the current
    #          locale settings returned by LocaleBorg!  Use with care!
    setting.lang = "zz"

    assert inp["zz"] == str(setting)
    assert inp["zz"] == setting()


@pytest.mark.parametrize(
    "path, files_folders, expected_path_end",
    [
        (
            "assets/css/nikola_rst.css",
            {"files": ""},  # default files_folders
            "nikola/data/themes/base/assets/css/nikola_rst.css",
        ),
        (
            "assets/css/theme.css",
            {"files": ""},  # default files_folders
            "nikola/data/themes/bootstrap4/assets/css/theme.css",
        ),
        ("nikola.py", {"nikola": ""}, "nikola/nikola.py"),
        ("nikola/nikola.py", {"nikola": "nikola"}, "nikola/nikola.py"),
        ("nikola.py", {"nikola": "nikola"}, None),
    ],
)
def test_get_asset_path(path, files_folders, expected_path_end):
    theme_chain = get_theme_chain("bootstrap4", ["themes"])
    asset_path = get_asset_path(path, theme_chain, files_folders)

    if expected_path_end:
        asset_path = asset_path.replace("\\", "/")
        assert asset_path.endswith(expected_path_end)
    else:
        assert asset_path is None


@pytest.mark.parametrize(
    "path, is_file, expected_crumbs",
    [
        ("galleries", False, [["#", "galleries"]]),
        (
            os.path.join("galleries", "demo"),
            False,
            [["..", "galleries"], ["#", "demo"]],
        ),
        (
            os.path.join("listings", "foo", "bar"),
            True,
            [["..", "listings"], [".", "foo"], ["#", "bar"]],
        ),
    ],
)
def test_get_crumbs(path, is_file, expected_crumbs):
    crumbs = get_crumbs(path, is_file=is_file)
    assert len(crumbs) == len(expected_crumbs)
    for crumb, expected_crumb in zip(crumbs, expected_crumbs):
        assert crumb == expected_crumb


@pytest.mark.parametrize(
    "pattern, path, lang, expected_path",
    [
        ("{path}.{lang}.{ext}", "*.rst", "es", "*.es.rst"),
        ("{path}.{lang}.{ext}", "fancy.post.rst", "es", "fancy.post.es.rst"),
        ("{path}.{lang}.{ext}", "*.es.rst", "es", "*.es.rst"),
        ("{path}.{lang}.{ext}", "*.es.rst", "en", "*.rst"),
        (
            "{path}.{lang}.{ext}",
            "cache/posts/fancy.post.es.html",
            "en",
            "cache/posts/fancy.post.html",
        ),
        (
            "{path}.{lang}.{ext}",
            "cache/posts/fancy.post.html",
            "es",
            "cache/posts/fancy.post.es.html",
        ),
        (
            "{path}.{lang}.{ext}",
            "cache/pages/charts.html",
            "es",
            "cache/pages/charts.es.html",
        ),
        (
            "{path}.{lang}.{ext}",
            "cache/pages/charts.html",
            "en",
            "cache/pages/charts.html",
        ),
        ("{path}.{ext}.{lang}", "*.rst", "es", "*.rst.es"),
        ("{path}.{ext}.{lang}", "*.rst.es", "es", "*.rst.es"),
        ("{path}.{ext}.{lang}", "*.rst.es", "en", "*.rst"),
        (
            "{path}.{ext}.{lang}",
            "cache/posts/fancy.post.html.es",
            "en",
            "cache/posts/fancy.post.html",
        ),
        (
            "{path}.{ext}.{lang}",
            "cache/posts/fancy.post.html",
            "es",
            "cache/posts/fancy.post.html.es",
        ),
    ],
)
def test_get_translation_candidate(pattern, path, lang, expected_path):
    config = {
        "TRANSLATIONS_PATTERN": pattern,
        "DEFAULT_LANG": "en",
        "TRANSLATIONS": {"es": "1", "en": 1},
    }
    assert get_translation_candidate(config, path, lang) == expected_path


def test_TemplateHookRegistry():
    r = TemplateHookRegistry("foo", None)
    r.append("Hello!")
    r.append(lambda x: "Hello " + x + "!", False, "world")
    assert r() == "Hello!\nHello world!"


@pytest.mark.parametrize(
    "base, expected_path",
    [
        ("http://some.site", "/"),
        ("http://some.site/", "/"),
        ("http://some.site/some/sub-path", "/some/sub-path/"),
        ("http://some.site/some/sub-path/", "/some/sub-path/"),
    ],
)
def test_sitemap_get_base_path(base, expected_path):
    assert expected_path == sitemap_get_base_path(base)


@pytest.mark.parametrize(
    "metadata_format, expected_result",
    [
        (
            "nikola",
            """\
.. title: Hello, world!
.. slug: hello-world
.. a: 1
.. b: 2

""",
        ),
        (
            "yaml",
            """\
---
a: '1'
b: '2'
slug: hello-world
title: Hello, world!
---
""",
        ),
    ],
)
def test_write_metadata_with_formats(metadata_format, expected_result):
    """
    Test writing metadata with different formats.

    YAML is expected to be sorted alphabetically.
    Nikola sorts by putting the defaults first and then sorting the rest
    alphabetically.
    """
    data = {"slug": "hello-world", "title": "Hello, world!", "b": "2", "a": "1"}
    assert write_metadata(data, metadata_format) == expected_result


def test_write_metadata_with_format_toml():
    """
    Test writing metadata in TOML format.

    TOML is sorted randomly in Python 3.5 or older and by insertion
    order since Python 3.6.
    """
    data = {"slug": "hello-world", "title": "Hello, world!", "b": "2", "a": "1"}

    toml = write_metadata(data, "toml")
    assert toml.startswith("+++\n")
    assert toml.endswith("+++\n")
    assert 'slug = "hello-world"' in toml
    assert 'title = "Hello, world!"' in toml
    assert 'b = "2"' in toml
    assert 'a = "1"' in toml


@pytest.mark.parametrize(
    "wrap, expected_result",
    [
        (
            False,
            """\
.. title: Hello, world!
.. slug: hello-world

""",
        ),
        (
            True,
            """\
<!--
.. title: Hello, world!
.. slug: hello-world
-->

""",
        ),
        (
            ("111", "222"),
            """\
111
.. title: Hello, world!
.. slug: hello-world
222

""",
        ),
    ],
)
def test_write_metadata_comment_wrap(wrap, expected_result):
    data = {"title": "Hello, world!", "slug": "hello-world"}
    assert write_metadata(data, "nikola", wrap) == expected_result


@pytest.mark.parametrize(
    "metadata_format, expected_results",
    [
        (
            "rest_docinfo",
            [
                """=============
Hello, world!
=============

:slug: hello-world
"""
            ],
        ),
        (
            "markdown_meta",
            [
                """title: Hello, world!
slug: hello-world

""",
                """slug: hello-world
title: Hello, world!

""",
            ],
        ),
    ],
)
def test_write_metadata_compiler(metadata_format, expected_results):
    """
    Test writing metadata with different formats.

    We test for multiple results because some compilers might produce
    unordered output.
    """
    data = {"title": "Hello, world!", "slug": "hello-world"}
    assert write_metadata(data, metadata_format) in expected_results


@pytest.mark.parametrize(
    "post_format, expected_metadata",
    [
        ("rest", "==\nxx\n==\n\n"),
        ("markdown", "title: xx\n\n"),
        ("html", ".. title: xx\n\n"),
    ],
)
def test_write_metadata_pelican_detection(post, post_format, expected_metadata):
    post.name = post_format

    data = {"title": "xx"}
    assert write_metadata(data, "pelican", compiler=post) == expected_metadata


def test_write_metadata_pelican_detection_default():
    data = {"title": "xx"}
    assert write_metadata(data, "pelican", compiler=None) == ".. title: xx\n\n"


def test_write_metadata_from_site(post):
    post.config = {"METADATA_FORMAT": "yaml"}
    data = {"title": "xx"}
    assert write_metadata(data, site=post) == "---\ntitle: xx\n---\n"


def test_write_metadata_default(post):
    data = {"title": "xx"}
    assert write_metadata(data) == ".. title: xx\n\n"


@pytest.mark.parametrize("arg", ["foo", "filename_regex"])
def test_write_metadata_fallbacks(post, arg):
    data = {"title": "xx"}
    assert write_metadata(data, arg) == ".. title: xx\n\n"


@pytest.mark.parametrize("value, expected", [
    ("true", True),
    ("True", True),
    ("TRUE", True),
    ("yes", True),
    ("Yes", True),
    ("YES", True),
    ("false", False),
    ("False", False),
    ("FALSE", False),
    ("no", False),
    ("No", False),
    ("NO", False),
    ("1", True),
    (1, True),
    ("0", False),
    (0, False),
    ("0", False),
    (True, True),
    (False, False),
    ("unknown", "F"),
    (None, "B"),
    ("", "B"),
])
def test_bool_from_meta(value, expected):
    meta = {"key": value}
    assert bool_from_meta(meta, "key", "F", "B") == expected


@pytest.fixture
def post():
    return FakePost()


class FakePost:
    default_lang = "en"
    metadata_extractors_by = metadata_extractors.default_metadata_extractors_by()
    config = {
        "TRANSLATIONS_PATTERN": "{path}.{lang}.{ext}",
        "TRANSLATIONS": {"en": "./"},
        "DEFAULT_LANG": "en",
    }

    def __init__(self):
        metadata_extractors.load_defaults(self, self.metadata_extractors_by)