You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
-diff --git a/pelican/tests/TestPages/bad_page.rst b/pelican/tests/TestPages/bad_page.rst deleted file mode 100644 index bc62948b..00000000 --- a/pelican/tests/TestPages/bad_page.rst +++ /dev/null @@ -1,8 +0,0 @@ -This is a test bad page -####################### - -:status: invalid - -The quick brown fox jumped over the lazy dog's back. - -The status here is invalid, the page should not render. diff --git a/pelican/tests/TestPages/draft_page.rst b/pelican/tests/TestPages/draft_page.rst deleted file mode 100644 index 19ca0646..00000000 --- a/pelican/tests/TestPages/draft_page.rst +++ /dev/null @@ -1,8 +0,0 @@ -This is a test draft page -########################## - -:status: draft - -The quick brown fox . - -This page is a draft. diff --git a/pelican/tests/TestPages/draft_page_markdown.md b/pelican/tests/TestPages/draft_page_markdown.md deleted file mode 100644 index fda71868..00000000 --- a/pelican/tests/TestPages/draft_page_markdown.md +++ /dev/null @@ -1,12 +0,0 @@ -title: This is a markdown test draft page -status: draft - -Test Markdown File Header -========================= - -Used for pelican test ---------------------- - -The quick brown fox . - -This page is a draft \ No newline at end of file diff --git a/pelican/tests/TestPages/draft_page_with_template.rst b/pelican/tests/TestPages/draft_page_with_template.rst deleted file mode 100644 index 9d46e717..00000000 --- a/pelican/tests/TestPages/draft_page_with_template.rst +++ /dev/null @@ -1,11 +0,0 @@ -This is a test draft page with a custom template -################################################# - -:status: draft -:template: custom - -The quick brown fox . - -This page is a draft - -This page has a custom template to be called when rendered diff --git a/pelican/tests/TestPages/hidden_page.rst b/pelican/tests/TestPages/hidden_page.rst deleted file mode 100644 index 57ca329c..00000000 --- a/pelican/tests/TestPages/hidden_page.rst +++ /dev/null @@ -1,8 +0,0 @@ -This is a test hidden page -########################## - -:status: hidden - -The quick brown fox jumped over the lazy dog's back. - -This page is hidden diff --git a/pelican/tests/TestPages/hidden_page_markdown.md b/pelican/tests/TestPages/hidden_page_markdown.md deleted file mode 100644 index 1e532fe7..00000000 --- a/pelican/tests/TestPages/hidden_page_markdown.md +++ /dev/null @@ -1,12 +0,0 @@ -title: This is a markdown test hidden page -status: hidden - -Test Markdown File Header -========================= - -Used for pelican test ---------------------- - -The quick brown fox jumped over the lazy dog's back. - -This page is hidden diff --git a/pelican/tests/TestPages/hidden_page_with_template.rst b/pelican/tests/TestPages/hidden_page_with_template.rst deleted file mode 100644 index 36104a09..00000000 --- a/pelican/tests/TestPages/hidden_page_with_template.rst +++ /dev/null @@ -1,11 +0,0 @@ -This is a test hidden page with a custom template -################################################# - -:status: hidden -:template: custom - -The quick brown fox jumped over the lazy dog's back. - -This page is hidden - -This page has a custom template to be called when rendered diff --git a/pelican/tests/TestPages/page.rst b/pelican/tests/TestPages/page.rst deleted file mode 100644 index 2d13976d..00000000 --- a/pelican/tests/TestPages/page.rst +++ /dev/null @@ -1,4 +0,0 @@ -This is a test page -################### - -The quick brown fox jumped over the lazy dog's back. diff --git a/pelican/tests/TestPages/page_markdown.md b/pelican/tests/TestPages/page_markdown.md deleted file mode 100644 index d5416a6f..00000000 --- a/pelican/tests/TestPages/page_markdown.md +++ /dev/null @@ -1,9 +0,0 @@ -title: This is a markdown test page - -Test Markdown File Header -========================= - -Used for pelican test ---------------------- - -The quick brown fox jumped over the lazy dog's back. diff --git a/pelican/tests/TestPages/page_used_for_sorting_test.rst b/pelican/tests/TestPages/page_used_for_sorting_test.rst deleted file mode 100644 index 40cdc7ea..00000000 --- a/pelican/tests/TestPages/page_used_for_sorting_test.rst +++ /dev/null @@ -1,6 +0,0 @@ -A Page (Test) for sorting -######################### - -:slug: zzzz - -When using title, should be first. When using slug, should be last. diff --git a/pelican/tests/TestPages/page_with_category_and_tag_links.md b/pelican/tests/TestPages/page_with_category_and_tag_links.md deleted file mode 100644 index 6806a570..00000000 --- a/pelican/tests/TestPages/page_with_category_and_tag_links.md +++ /dev/null @@ -1,7 +0,0 @@ -Title: Page with a bunch of links - -My links: - -[Link 1]({tag}マック) - -[Link 2]({category}Yeah) diff --git a/pelican/tests/TestPages/page_with_static_links.md b/pelican/tests/TestPages/page_with_static_links.md deleted file mode 100644 index 1967cfcf..00000000 --- a/pelican/tests/TestPages/page_with_static_links.md +++ /dev/null @@ -1,7 +0,0 @@ -Title: Page with static links - -My links: - -[Link 0]({static}image0.jpg) - -[Link 1]({attach}image1.jpg) diff --git a/pelican/tests/TestPages/page_with_template.rst b/pelican/tests/TestPages/page_with_template.rst deleted file mode 100644 index 9388dc2f..00000000 --- a/pelican/tests/TestPages/page_with_template.rst +++ /dev/null @@ -1,8 +0,0 @@ -This is a test page with a preset template -########################################## - -:template: custom - -The quick brown fox jumped over the lazy dog's back. - -This article has a custom template to be called when rendered diff --git a/pelican/tests/__init__.py b/pelican/tests/__init__.py deleted file mode 100644 index 4605a02b..00000000 --- a/pelican/tests/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -import logging -import warnings - -from pelican.log import log_warnings - -# redirect warnings modulole to use logging instead -log_warnings() - -# setup warnings to log DeprecationWarning's and error on -# warnings in pelican's codebase -warnings.simplefilter("default", DeprecationWarning) -warnings.filterwarnings("error", ".*", Warning, "pelican") - -# Add a NullHandler to silence warning about no available handlers -logging.getLogger().addHandler(logging.NullHandler()) diff --git a/pelican/tests/content/2012-11-29_rst_w_filename_meta#foo-bar.rst b/pelican/tests/content/2012-11-29_rst_w_filename_meta#foo-bar.rst deleted file mode 100644 index 43f05a15..00000000 --- a/pelican/tests/content/2012-11-29_rst_w_filename_meta#foo-bar.rst +++ /dev/null @@ -1,6 +0,0 @@ - -Rst with filename metadata -########################## - -:category: yeah -:author: Alexis Métaireau diff --git a/pelican/tests/content/2012-11-30_md_w_filename_meta#foo-bar.md b/pelican/tests/content/2012-11-30_md_w_filename_meta#foo-bar.md deleted file mode 100644 index cdccfc8a..00000000 --- a/pelican/tests/content/2012-11-30_md_w_filename_meta#foo-bar.md +++ /dev/null @@ -1,6 +0,0 @@ -category: yeah -author: Alexis Métaireau - -Markdown with filename metadata -=============================== - diff --git a/pelican/tests/content/TestCategory/article_with_category.rst b/pelican/tests/content/TestCategory/article_with_category.rst deleted file mode 100644 index 69ffa98b..00000000 --- a/pelican/tests/content/TestCategory/article_with_category.rst +++ /dev/null @@ -1,7 +0,0 @@ -This is an article with category ! -################################## - -:category: yeah -:date: 1970-01-01 - -This article should be in 'yeah' category. diff --git a/pelican/tests/content/TestCategory/article_without_category.rst b/pelican/tests/content/TestCategory/article_without_category.rst deleted file mode 100644 index 4bc5d78d..00000000 --- a/pelican/tests/content/TestCategory/article_without_category.rst +++ /dev/null @@ -1,4 +0,0 @@ -This is an article without category ! -##################################### - -This article should be in 'TestCategory' category. diff --git a/pelican/tests/content/article.rst b/pelican/tests/content/article.rst deleted file mode 100644 index 793e6869..00000000 --- a/pelican/tests/content/article.rst +++ /dev/null @@ -1,6 +0,0 @@ -Article title -############# - -THIS is some content. With some stuff to "typogrify"... - -Now with added support for :abbr:`TLA (three letter acronym)`. diff --git a/pelican/tests/content/article_draft.md b/pelican/tests/content/article_draft.md deleted file mode 100644 index d2235553..00000000 --- a/pelican/tests/content/article_draft.md +++ /dev/null @@ -1,5 +0,0 @@ -Title: Draft article -Date: 2012-10-31 -Status: draft - -This is some content. diff --git a/pelican/tests/content/article_hidden.md b/pelican/tests/content/article_hidden.md deleted file mode 100644 index d449f701..00000000 --- a/pelican/tests/content/article_hidden.md +++ /dev/null @@ -1,5 +0,0 @@ -Title: Hidden article -Date: 2012-10-31 -Status: hidden - -This is some unlisted content. diff --git a/pelican/tests/content/article_with_attributes_containing_double_quotes.html b/pelican/tests/content/article_with_attributes_containing_double_quotes.html deleted file mode 100644 index 7daa5801..00000000 --- a/pelican/tests/content/article_with_attributes_containing_double_quotes.html +++ /dev/null @@ -1,11 +0,0 @@ - -
- - - Ensure that if an attribute value contains a double quote, it is - surrounded with single quotes, otherwise with double quotes. - Span content - Span content - Span content - - diff --git a/pelican/tests/content/article_with_capitalized_metadata.rst b/pelican/tests/content/article_with_capitalized_metadata.rst deleted file mode 100644 index 93ed5b15..00000000 --- a/pelican/tests/content/article_with_capitalized_metadata.rst +++ /dev/null @@ -1,16 +0,0 @@ - -This is a super article ! -######################### - -:TAGS: foo, bar, foobar -:DATE: 2010-12-02 10:14 -:MODIFIED: 2010-12-02 10:20 -:CATEGORY: yeah -:AUTHOR: Alexis Métaireau -:SUMMARY: - Multi-line metadata should be supported - as well as **inline markup** and stuff to "typogrify"... -:CUSTOM_FIELD: http://notmyidea.org -:CUSTOM_FORMATTED_FIELD: - Multi-line metadata should also be supported - as well as *inline markup* and stuff to "typogrify"... diff --git a/pelican/tests/content/article_with_code_block.rst b/pelican/tests/content/article_with_code_block.rst deleted file mode 100644 index 586878cf..00000000 --- a/pelican/tests/content/article_with_code_block.rst +++ /dev/null @@ -1,15 +0,0 @@ -An Article With Code Block To Test Typogrify Ignore -################################################### - -An article with some code - -.. code-block:: python - - x & y - -A block quote: - - x & y - -Normal: -x & y diff --git a/pelican/tests/content/article_with_comments.html b/pelican/tests/content/article_with_comments.html deleted file mode 100644 index 289e4a66..00000000 --- a/pelican/tests/content/article_with_comments.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - Body content - - - diff --git a/pelican/tests/content/article_with_duplicate_tags_authors.md b/pelican/tests/content/article_with_duplicate_tags_authors.md deleted file mode 100644 index 7ab046f9..00000000 --- a/pelican/tests/content/article_with_duplicate_tags_authors.md +++ /dev/null @@ -1,15 +0,0 @@ -Title: Test metadata duplicates -Category: test -Tags: foo, bar, foobar, foo, bar -Authors: Author, First; Author, Second; Author, First -Date: 2010-12-02 10:14 -Modified: 2010-12-02 10:20 -Summary: I have a lot to test - -Test Markdown File Header -========================= - -Used for pelican test ---------------------- - -The quick brown fox jumped over the lazy dog's back. diff --git a/pelican/tests/content/article_with_inline_svg.html b/pelican/tests/content/article_with_inline_svg.html deleted file mode 100644 index 07f97a8a..00000000 --- a/pelican/tests/content/article_with_inline_svg.html +++ /dev/null @@ -1,17 +0,0 @@ - - -Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
- ---Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-
- a = [1, 2, 3]
- b = [4, 5, 6]
- for i in zip(a, b):
- print i
-
-
-Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
diff --git a/pelican/tests/content/wordpress_content_encoded b/pelican/tests/content/wordpress_content_encoded deleted file mode 100644 index da35de3b..00000000 --- a/pelican/tests/content/wordpress_content_encoded +++ /dev/null @@ -1,55 +0,0 @@ -Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum. - - - --Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum. - -Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum. --
-
- a = [1, 2, 3]
- b = [4, 5, 6]
- for i in zip(a, b):
- print i
-
-
-
-Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
-tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
-quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
-consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
-cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
-proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-
diff --git a/pelican/tests/content/wordpressexport.xml b/pelican/tests/content/wordpressexport.xml
deleted file mode 100644
index 9b194e8f..00000000
--- a/pelican/tests/content/wordpressexport.xml
+++ /dev/null
@@ -1,957 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- a = [1, 2, 3]
- b = [4, 5, 6]
- for i in zip(a, b):
- print i
-
-You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
-Article 1
- -Article 2
- -Article 3
- -This is some article, in english
- - read more -Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
This article overrides the listening of the articles under the baz tag.
- - read more -This is a draft article, it should live under the /drafts/ folder and not be -listed anywhere else.
- -This is a draft article, it should live under the /drafts/ folder and not be -listed anywhere else.
- -Some cool stuff!
- -This is some article, in english
- - read more -You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
- read more -Article 1
- - read more -Article 2
- - read more -Article 3
- - read more -Multi-line metadata should be supported -as well as inline markup.
- - read more -After all, why not ? It's pretty simple to do it, and it will allow me to write my blogposts in rst ! -YEAH !
-
-Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
This article overrides the listening of the articles under the baz tag.
- - read more -Et voila du contenu en français
- -After all, why not ? It's pretty simple to do it, and it will allow me to write my blogposts in rst ! -YEAH !
-
-Test page which overrides save_as and url so that this page will be generated -at a custom location.
- -This is great for things like error(404) pages -Anyone can see this page but it's not linked to anywhere!
- -Just an image.
-
-
-
-Ceci est un article, en français.
- -This is some article, in english
- -Multi-line metadata should be supported -as well as inline markup.
- - read more -After all, why not ? It's pretty simple to do it, and it will allow me to write my blogposts in rst ! -YEAH !
-
-This article overrides the listening of the articles under the baz tag.
- -Multi-line metadata should be supported -as well as inline markup.
- - read more -This page overrides the listening of the articles under the oh tag.
- -Some content here !
-And here comes the cool stuff.
-
-
-->>> from ipdb import set_trace ->>> set_trace() --
→ And now try with some utf8 hell: ééé
-Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will have nothing in default.
-formatter = self.options and VARIANTS[self.options.keys()[0]]
-Lovely.
- 8def run(self):
self.assert_has_content()
10 try:
lexer = get_lexer_by_name(self.arguments[0])
12 except ValueError:
# no lexer found - use the text one instead of an exception
14 lexer = TextLexer()
16 if ('linenos' in self.options and
self.options['linenos'] not in ('table', 'inline')):
18 self.options['linenos'] = 'table'
20 for flag in ('nowrap', 'nobackground', 'anchorlinenos'):
if flag in self.options:
22 self.options[flag] = True
24 # noclasses should already default to False, but just in case...
formatter = HtmlFormatter(noclasses=False, **self.options)
26 parsed = highlight('\n'.join(self.content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
Lovely.
-Lovely.
-Even if the default is line numbers, we can override it here
-formatter = self.options and VARIANTS[self.options.keys()[0]]
-Lovely.
-
-
- You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
-
-
-
-
- Article 1
- -
-
- Article 2
- -
-
- Article 3
- -
-
- You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
- read more -There are comments.
-
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
There are comments.
-
-
-
-
-
-
-
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
There are comments.
-
-
-
- This is a draft article, it should live under the /drafts/ folder and not be -listed anywhere else.
- -
-
- This is a draft article, it should live under the /drafts/ folder and not be -listed anywhere else.
- -
-
- Some cool stuff!
- -
-
- You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
- read more -There are comments.
-
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
There are comments.
-
-
-
- Et voila du contenu en français
- -
-
- After all, why not ? It's pretty simple to do it, and it will allow me to write my blogposts in rst ! -YEAH !
-
-
-
- Test page which overrides save_as and url so that this page will be generated -at a custom location.
- -
-
- This is great for things like error(404) pages -Anyone can see this page but it's not linked to anywhere!
- -
-
- Just an image.
-
-
-
-
-
- Ceci est un article, en français.
- -
-
- This is some article, in english
- -
-
-
-
- This article overrides the listening of the articles under the baz tag.
- -
-
-
-
-
-
- This page overrides the listening of the articles under the oh tag.
- -
-
-
-
-
-
- Some content here !
-And here comes the cool stuff.
-
-
-->>> from ipdb import set_trace ->>> set_trace() --
→ And now try with some utf8 hell: ééé
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will have nothing in default.
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
Lovely.
- 8def run(self):
self.assert_has_content()
10 try:
lexer = get_lexer_by_name(self.arguments[0])
12 except ValueError:
# no lexer found - use the text one instead of an exception
14 lexer = TextLexer()
16 if ('linenos' in self.options and
self.options['linenos'] not in ('table', 'inline')):
18 self.options['linenos'] = 'table'
20 for flag in ('nowrap', 'nobackground', 'anchorlinenos'):
if flag in self.options:
22 self.options[flag] = True
24 # noclasses should already default to False, but just in case...
formatter = HtmlFormatter(noclasses=False, **self.options)
26 parsed = highlight('\n'.join(self.content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
Lovely.
-Lovely.
-Even if the default is line numbers, we can override it here
-formatter = self.options and VARIANTS[self.options.keys()[0]]
-Lovely.
-
-
-
-
- You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
- read more -There are comments.
-
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
There are comments.
-
-
-
-
-
-
-
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
There are comments.
-
-
-
- This is a draft article, it should live under the /drafts/ folder and not be -listed anywhere else.
- -
-
- This is a draft article, it should live under the /drafts/ folder and not be -listed anywhere else.
- -
-
- You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
- read more -There are comments.
-
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will …
There are comments.
-
-
-
- Et voila du contenu en français
- -
-
- Test page which overrides save_as and url so that this page will be generated -at a custom location.
- -
-
- This is great for things like error(404) pages -Anyone can see this page but it's not linked to anywhere!
- -
-
- Just an image.
-
-
-
-
-
- Some content here !
-And here comes the cool stuff.
-
-
-->>> from ipdb import set_trace ->>> set_trace() --
→ And now try with some utf8 hell: ééé
-
-
- Or completely awesome. Depends the needs.
-a root-relative link to markdown-article -a file-relative link to markdown-article
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
This will now have a line number in 'custom' since it's the default in -pelican.conf, it will have nothing in default.
-1 | formatter = self.options and VARIANTS[self.options.keys()[0]]
- |
Lovely.
- 8def run(self):
self.assert_has_content()
10 try:
lexer = get_lexer_by_name(self.arguments[0])
12 except ValueError:
# no lexer found - use the text one instead of an exception
14 lexer = TextLexer()
16 if ('linenos' in self.options and
self.options['linenos'] not in ('table', 'inline')):
18 self.options['linenos'] = 'table'
20 for flag in ('nowrap', 'nobackground', 'anchorlinenos'):
if flag in self.options:
22 self.options[flag] = True
24 # noclasses should already default to False, but just in case...
formatter = HtmlFormatter(noclasses=False, **self.options)
26 parsed = highlight('\n'.join(self.content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
Lovely.
-Lovely.
-Even if the default is line numbers, we can override it here
-formatter = self.options and VARIANTS[self.options.keys()[0]]
-Lovely.
-
-
- After all, why not ? It's pretty simple to do it, and it will allow me to write my blogposts in rst ! -YEAH !
-
-
-
- You're mutually oblivious.
-a root-relative link to unbelievable -a file-relative link to unbelievable
-
-
- Article 1
- -
-
- Article 2
- -
-
- Article 3
- -
-
- This is some article, in english
- -
-
- Some cool stuff!
- -
-
- Ceci est un article, en français.
- -
-
-
-
- This article overrides the listening of the articles under the baz tag.
- -
-
-
-
-
-
- This page overrides the listening of the articles under the oh tag.
- -
-
-
-
- -TEST_CONTENT = str(generate_lorem_ipsum(n=1)) -TEST_SUMMARY = generate_lorem_ipsum(n=1, html=False) - - -class TestBase(LoggedTestCase): - - def setUp(self): - super().setUp() - self.old_locale = locale.setlocale(locale.LC_ALL) - locale.setlocale(locale.LC_ALL, 'C') - self.page_kwargs = { - 'content': TEST_CONTENT, - 'context': { - 'localsiteurl': '', - 'generated_content': {}, - 'static_content': {}, - 'static_links': set() - }, - 'metadata': { - 'summary': TEST_SUMMARY, - 'title': 'foo bar', - 'author': Author('Blogger', DEFAULT_CONFIG), - }, - 'source_path': '/path/to/file/foo.ext' - } - self._disable_limit_filter() - - def tearDown(self): - locale.setlocale(locale.LC_ALL, self.old_locale) - self._enable_limit_filter() - - def _disable_limit_filter(self): - from pelican.contents import logger - logger.disable_filter() - - def _enable_limit_filter(self): - from pelican.contents import logger - logger.enable_filter() - - def _copy_page_kwargs(self): - # make a deep copy of page_kwargs - page_kwargs = {key: self.page_kwargs[key] for key in self.page_kwargs} - for key in page_kwargs: - if not isinstance(page_kwargs[key], dict): - break - page_kwargs[key] = { - subkey: page_kwargs[key][subkey] for subkey in page_kwargs[key] - } - - return page_kwargs - - -class TestPage(TestBase): - def test_use_args(self): - # Creating a page with arguments passed to the constructor should use - # them to initialise object's attributes. - metadata = {'foo': 'bar', 'foobar': 'baz', 'title': 'foobar', } - page = Page(TEST_CONTENT, metadata=metadata, - context={'localsiteurl': ''}) - for key, value in metadata.items(): - self.assertTrue(hasattr(page, key)) - self.assertEqual(value, getattr(page, key)) - self.assertEqual(page.content, TEST_CONTENT) - - def test_mandatory_properties(self): - # If the title is not set, must throw an exception. - page = Page('content') - self.assertFalse(page._has_valid_mandatory_properties()) - self.assertLogCountEqual( - count=1, - msg="Skipping .*: could not find information about 'title'", - level=logging.ERROR) - page = Page('content', metadata={'title': 'foobar'}) - self.assertTrue(page._has_valid_mandatory_properties()) - - def test_summary_from_metadata(self): - # If a :summary: metadata is given, it should be used - page = Page(**self.page_kwargs) - self.assertEqual(page.summary, TEST_SUMMARY) - - def test_summary_max_length(self): - # If a :SUMMARY_MAX_LENGTH: is set, and there is no other summary, - # generated summary should not exceed the given length. - page_kwargs = self._copy_page_kwargs() - settings = get_settings() - page_kwargs['settings'] = settings - del page_kwargs['metadata']['summary'] - settings['SUMMARY_MAX_LENGTH'] = None - page = Page(**page_kwargs) - self.assertEqual(page.summary, TEST_CONTENT) - settings['SUMMARY_MAX_LENGTH'] = 10 - page = Page(**page_kwargs) - self.assertEqual(page.summary, truncate_html_words(TEST_CONTENT, 10)) - settings['SUMMARY_MAX_LENGTH'] = 0 - page = Page(**page_kwargs) - self.assertEqual(page.summary, '') - - def test_summary_end_suffix(self): - # If a :SUMMARY_END_SUFFIX: is set, and there is no other summary, - # generated summary should contain the specified marker at the end. - page_kwargs = self._copy_page_kwargs() - settings = get_settings() - page_kwargs['settings'] = settings - del page_kwargs['metadata']['summary'] - settings['SUMMARY_END_SUFFIX'] = 'test_marker' - settings['SUMMARY_MAX_LENGTH'] = 10 - page = Page(**page_kwargs) - self.assertEqual(page.summary, truncate_html_words(TEST_CONTENT, 10, - 'test_marker')) - self.assertIn('test_marker', page.summary) - - def test_summary_get_summary_warning(self): - """calling ._get_summary() should issue a warning""" - page_kwargs = self._copy_page_kwargs() - page = Page(**page_kwargs) - self.assertEqual(page.summary, TEST_SUMMARY) - self.assertEqual(page._get_summary(), TEST_SUMMARY) - self.assertLogCountEqual( - count=1, - msg=r"_get_summary\(\) has been deprecated since 3\.6\.4\. " - "Use the summary decorator instead", - level=logging.WARNING) - - def test_slug(self): - page_kwargs = self._copy_page_kwargs() - settings = get_settings() - page_kwargs['settings'] = settings - settings['SLUGIFY_SOURCE'] = "title" - page = Page(**page_kwargs) - self.assertEqual(page.slug, 'foo-bar') - settings['SLUGIFY_SOURCE'] = "basename" - page = Page(**page_kwargs) - self.assertEqual(page.slug, 'foo') - - # test slug from title with unicode and case - - inputs = ( - # (title, expected, preserve_case, use_unicode) - ('指導書', 'zhi-dao-shu', False, False), - ('指導書', 'Zhi-Dao-Shu', True, False), - ('指導書', '指導書', False, True), - ('指導書', '指導書', True, True), - ('Çığ', 'cig', False, False), - ('Çığ', 'Cig', True, False), - ('Çığ', 'çığ', False, True), - ('Çığ', 'Çığ', True, True), - ) - - settings = get_settings() - page_kwargs = self._copy_page_kwargs() - page_kwargs['settings'] = settings - - for title, expected, preserve_case, use_unicode in inputs: - settings['SLUGIFY_PRESERVE_CASE'] = preserve_case - settings['SLUGIFY_USE_UNICODE'] = use_unicode - page_kwargs['metadata']['title'] = title - page = Page(**page_kwargs) - self.assertEqual(page.slug, expected, - (title, preserve_case, use_unicode)) - - def test_defaultlang(self): - # If no lang is given, default to the default one. - page = Page(**self.page_kwargs) - self.assertEqual(page.lang, DEFAULT_CONFIG['DEFAULT_LANG']) - - # it is possible to specify the lang in the metadata infos - self.page_kwargs['metadata'].update({'lang': 'fr', }) - page = Page(**self.page_kwargs) - self.assertEqual(page.lang, 'fr') - - def test_save_as(self): - # If a lang is not the default lang, save_as should be set - # accordingly. - - # if a title is defined, save_as should be set - page = Page(**self.page_kwargs) - self.assertEqual(page.save_as, "pages/foo-bar.html") - - # if a language is defined, save_as should include it accordingly - self.page_kwargs['metadata'].update({'lang': 'fr', }) - page = Page(**self.page_kwargs) - self.assertEqual(page.save_as, "pages/foo-bar-fr.html") - - def test_relative_source_path(self): - # 'relative_source_path' should be the relative path - # from 'PATH' to 'source_path' - page_kwargs = self._copy_page_kwargs() - - # If 'source_path' is None, 'relative_source_path' should - # also return None - page_kwargs['source_path'] = None - page = Page(**page_kwargs) - self.assertIsNone(page.relative_source_path) - - page_kwargs = self._copy_page_kwargs() - settings = get_settings() - full_path = page_kwargs['source_path'] - - settings['PATH'] = os.path.dirname(full_path) - page_kwargs['settings'] = settings - page = Page(**page_kwargs) - - # if 'source_path' is set, 'relative_source_path' should - # return the relative path from 'PATH' to 'source_path' - self.assertEqual( - page.relative_source_path, - os.path.relpath( - full_path, - os.path.dirname(full_path) - )) - - def test_metadata_url_format(self): - # Arbitrary metadata should be passed through url_format() - page = Page(**self.page_kwargs) - self.assertIn('summary', page.url_format.keys()) - page.metadata['directory'] = 'test-dir' - page.settings = get_settings(PAGE_SAVE_AS='{directory}/{slug}') - self.assertEqual(page.save_as, 'test-dir/foo-bar') - - def test_datetime(self): - # If DATETIME is set to a tuple, it should be used to override LOCALE - dt = datetime.datetime(2015, 9, 13) - - page_kwargs = self._copy_page_kwargs() - - # set its date to dt - page_kwargs['metadata']['date'] = dt - page = Page(**page_kwargs) - - # page.locale_date is a unicode string in both python2 and python3 - dt_date = dt.strftime(DEFAULT_CONFIG['DEFAULT_DATE_FORMAT']) - - self.assertEqual(page.locale_date, dt_date) - page_kwargs['settings'] = get_settings() - - # I doubt this can work on all platforms ... - if platform == "win32": - locale = 'jpn' - else: - locale = 'ja_JP.utf8' - page_kwargs['settings']['DATE_FORMATS'] = {'jp': (locale, - '%Y-%m-%d(%a)')} - page_kwargs['metadata']['lang'] = 'jp' - - import locale as locale_module - try: - page = Page(**page_kwargs) - self.assertEqual(page.locale_date, '2015-09-13(\u65e5)') - except locale_module.Error: - # The constructor of ``Page`` will try to set the locale to - # ``ja_JP.utf8``. But this attempt will failed when there is no - # such locale in the system. You can see which locales there are - # in your system with ``locale -a`` command. - # - # Until we find some other method to test this functionality, we - # will simply skip this test. - unittest.skip("There is no locale %s in this system." % locale) - - def test_template(self): - # Pages default to page, metadata overwrites - default_page = Page(**self.page_kwargs) - self.assertEqual('page', default_page.template) - page_kwargs = self._copy_page_kwargs() - page_kwargs['metadata']['template'] = 'custom' - custom_page = Page(**page_kwargs) - self.assertEqual('custom', custom_page.template) - - def test_signal(self): - def receiver_test_function(sender): - receiver_test_function.has_been_called = True - pass - receiver_test_function.has_been_called = False - - content_object_init.connect(receiver_test_function) - self.assertIn( - receiver_test_function, - content_object_init.receivers_for(Page)) - - self.assertFalse(receiver_test_function.has_been_called) - Page(**self.page_kwargs) - self.assertTrue(receiver_test_function.has_been_called) - - def test_get_content(self): - # Test that the content is updated with the relative links to - # filenames, tags and categories. - settings = get_settings() - args = self.page_kwargs.copy() - args['settings'] = settings - - # Tag - args['content'] = ('A simple test, with a ' - 'link') - page = Page(**args) - content = page.get_content('http://notmyidea.org') - self.assertEqual( - content, - ('A simple test, with a ' - 'link')) - - # Category - args['content'] = ('A simple test, with a ' - 'link') - page = Page(**args) - content = page.get_content('http://notmyidea.org') - self.assertEqual( - content, - ('A simple test, with a ' - 'link')) - - def test_intrasite_link(self): - cls_name = '_DummyArticle' - article = type(cls_name, (object,), {'url': 'article.html'}) - - args = self.page_kwargs.copy() - args['settings'] = get_settings() - args['source_path'] = 'content' - args['context']['generated_content'] = {'article.rst': article} - - # Classic intrasite link via filename - args['content'] = ( - 'A simple test, with a ' - 'link' - ) - content = Page(**args).get_content('http://notmyidea.org') - self.assertEqual( - content, - 'A simple test, with a ' - 'link' - ) - - # fragment - args['content'] = ( - 'A simple test, with a ' - 'link' - ) - content = Page(**args).get_content('http://notmyidea.org') - self.assertEqual( - content, - 'A simple test, with a ' - 'link' - ) - - # query - args['content'] = ( - 'A simple test, with a ' - 'link' - ) - content = Page(**args).get_content('http://notmyidea.org') - self.assertEqual( - content, - 'A simple test, with a ' - 'link' - ) - - # combination - args['content'] = ( - 'A simple test, with a ' - 'link' - ) - content = Page(**args).get_content('http://notmyidea.org') - self.assertEqual( - content, - 'A simple test, with a ' - 'link' - ) - - # also test for summary in metadata - parsed = ( - 'A simple summary test, with a ' - 'link' - ) - linked = ( - 'A simple summary test, with a ' - 'link' - ) - args['settings']['FORMATTED_FIELDS'] = ['summary', 'custom'] - args['metadata']['summary'] = parsed - args['metadata']['custom'] = parsed - args['context']['localsiteurl'] = 'http://notmyidea.org' - p = Page(**args) - # This is called implicitly from all generators and Pelican.run() once - # all files are processed. Here we process just one page so it needs - # to be called explicitly. - p.refresh_metadata_intersite_links() - self.assertEqual(p.summary, linked) - self.assertEqual(p.custom, linked) - - def test_intrasite_link_more(self): - cls_name = '_DummyAsset' - - args = self.page_kwargs.copy() - args['settings'] = get_settings() - args['source_path'] = 'content' - args['context']['static_content'] = { - 'images/poster.jpg': - type(cls_name, (object,), {'url': 'images/poster.jpg'}), - 'assets/video.mp4': - type(cls_name, (object,), {'url': 'assets/video.mp4'}), - 'images/graph.svg': - type(cls_name, (object,), {'url': 'images/graph.svg'}), - } - args['context']['generated_content'] = { - 'reference.rst': - type(cls_name, (object,), {'url': 'reference.html'}), - } - - # video.poster - args['content'] = ( - 'There is a video with poster ' - '' - ) - content = Page(**args).get_content('http://notmyidea.org') - self.assertEqual( - content, - 'There is a video with poster ' - '' - ) - - # object.data - args['content'] = ( - 'There is a svg object ' - '' - ) - content = Page(**args).get_content('http://notmyidea.org') - self.assertEqual( - content, - 'There is a svg object ' - '' - ) - - # blockquote.cite - args['content'] = ( - 'There is a blockquote with cite attribute ' - '
blah blah' - ) - content = Page(**args).get_content('http://notmyidea.org') - self.assertEqual( - content, - 'There is a blockquote with cite attribute ' - '
' - 'blah blah' - '' - ) - - def test_intrasite_link_absolute(self): - """Test that absolute URLs are merged properly.""" - - args = self.page_kwargs.copy() - args['settings'] = get_settings( - STATIC_URL='http://static.cool.site/{path}', - ARTICLE_URL='http://blog.cool.site/{slug}.html') - args['source_path'] = 'content' - args['context']['static_content'] = { - 'images/poster.jpg': - Static('', settings=args['settings'], - source_path='images/poster.jpg'), - } - args['context']['generated_content'] = { - 'article.rst': - Article('', settings=args['settings'], metadata={ - 'slug': 'article', 'title': 'Article'}) - } - - # Article link will go to blog - args['content'] = ( - 'Article' - ) - content = Page(**args).get_content('http://cool.site') - self.assertEqual( - content, - 'Article' - ) - - # Page link will go to the main site - args['content'] = ( - 'Index' - ) - content = Page(**args).get_content('http://cool.site') - self.assertEqual( - content, - 'Index' - ) - - # Image link will go to static - args['content'] = ( - '
'
- )
- content = Page(**args).get_content('http://cool.site')
- self.assertEqual(
- content,
- '
'
- )
-
- def test_intrasite_link_escape(self):
- article = type(
- '_DummyArticle', (object,), {'url': 'article-spaces.html'})
- asset = type(
- '_DummyAsset', (object,), {'url': 'name@example.com'})
-
- args = self.page_kwargs.copy()
- args['settings'] = get_settings()
- args['source_path'] = 'content'
- args['context']['generated_content'] = {'article spaces.rst': article}
- args['context']['static_content'] = {'name@example.com': asset}
-
- expected_output = (
- 'A simple test with a '
- 'link '
- 'file'
- )
-
- # not escaped
- args['content'] = (
- 'A simple test with a '
- 'link '
- 'file'
- )
- content = Page(**args).get_content('http://notmyidea.org')
- self.assertEqual(content, expected_output)
-
- # html escaped
- args['content'] = (
- 'A simple test with a '
- 'link '
- 'file'
- )
- content = Page(**args).get_content('http://notmyidea.org')
- self.assertEqual(content, expected_output)
-
- # url escaped
- args['content'] = (
- 'A simple test with a '
- 'link '
- 'file'
- )
- content = Page(**args).get_content('http://notmyidea.org')
- self.assertEqual(content, expected_output)
-
- # html and url escaped
- args['content'] = (
- 'A simple test with a '
- 'link '
- 'file'
- )
- content = Page(**args).get_content('http://notmyidea.org')
- self.assertEqual(content, expected_output)
-
- def test_intrasite_link_markdown_spaces(self):
- cls_name = '_DummyArticle'
- article = type(cls_name, (object,), {'url': 'article-spaces.html'})
-
- args = self.page_kwargs.copy()
- args['settings'] = get_settings()
- args['source_path'] = 'content'
- args['context']['generated_content'] = {'article spaces.rst': article}
-
- # An intrasite link via filename with %20 as a space
- args['content'] = (
- 'A simple test, with a '
- 'link'
- )
- content = Page(**args).get_content('http://notmyidea.org')
- self.assertEqual(
- content,
- 'A simple test, with a '
- 'link'
- )
-
- def test_intrasite_link_source_and_generated(self):
- """Test linking both to the source and the generated article
- """
- cls_name = '_DummyAsset'
-
- args = self.page_kwargs.copy()
- args['settings'] = get_settings()
- args['source_path'] = 'content'
- args['context']['generated_content'] = {
- 'article.rst': type(cls_name, (object,), {'url': 'article.html'})}
- args['context']['static_content'] = {
- 'article.rst': type(cls_name, (object,), {'url': 'article.rst'})}
-
- args['content'] = (
- 'A simple test, with a link to an'
- 'article and its'
- 'source'
- )
- content = Page(**args).get_content('http://notmyidea.org')
- self.assertEqual(
- content,
- 'A simple test, with a link to an'
- 'article and its'
- 'source'
- )
-
- def test_intrasite_link_to_static_content_with_filename(self):
- """Test linking to a static resource with deprecated {filename}
- """
- cls_name = '_DummyAsset'
-
- args = self.page_kwargs.copy()
- args['settings'] = get_settings()
- args['source_path'] = 'content'
- args['context']['static_content'] = {
- 'poster.jpg':
- type(cls_name, (object,), {'url': 'images/poster.jpg'})}
-
- args['content'] = (
- 'A simple test, with a link to a'
- 'poster'
- )
- content = Page(**args).get_content('http://notmyidea.org')
- self.assertEqual(
- content,
- 'A simple test, with a link to a'
- 'poster'
- )
-
- def test_multiple_authors(self):
- """Test article with multiple authors."""
- args = self.page_kwargs.copy()
- content = Page(**args)
- assert content.authors == [content.author]
- args['metadata'].pop('author')
- args['metadata']['authors'] = [Author('First Author', DEFAULT_CONFIG),
- Author('Second Author', DEFAULT_CONFIG)]
- content = Page(**args)
- assert content.authors
- assert content.author == content.authors[0]
-
-
-class TestArticle(TestBase):
- def test_template(self):
- # Articles default to article, metadata overwrites
- default_article = Article(**self.page_kwargs)
- self.assertEqual('article', default_article.template)
- article_kwargs = self._copy_page_kwargs()
- article_kwargs['metadata']['template'] = 'custom'
- custom_article = Article(**article_kwargs)
- self.assertEqual('custom', custom_article.template)
-
- def test_slugify_category_author(self):
- settings = get_settings()
- settings['SLUG_REGEX_SUBSTITUTIONS'] = [
- (r'C#', 'csharp'),
- (r'[^\w\s-]', ''),
- (r'(?u)\A\s*', ''),
- (r'(?u)\s*\Z', ''),
- (r'[-\s]+', '-'),
- ]
- settings['ARTICLE_URL'] = '{author}/{category}/{slug}/'
- settings['ARTICLE_SAVE_AS'] = '{author}/{category}/{slug}/index.html'
- article_kwargs = self._copy_page_kwargs()
- article_kwargs['metadata']['author'] = Author("O'Brien", settings)
- article_kwargs['metadata']['category'] = Category(
- 'C# & stuff', settings)
- article_kwargs['metadata']['title'] = 'fnord'
- article_kwargs['settings'] = settings
- article = Article(**article_kwargs)
- self.assertEqual(article.url, 'obrien/csharp-stuff/fnord/')
- self.assertEqual(
- article.save_as, 'obrien/csharp-stuff/fnord/index.html')
-
- def test_slugify_with_author_substitutions(self):
- settings = get_settings()
- settings['AUTHOR_REGEX_SUBSTITUTIONS'] = [
- ('Alexander Todorov', 'atodorov'),
- ('Krasimir Tsonev', 'krasimir'),
- (r'[^\w\s-]', ''),
- (r'(?u)\A\s*', ''),
- (r'(?u)\s*\Z', ''),
- (r'[-\s]+', '-'),
- ]
- settings['ARTICLE_URL'] = 'blog/{author}/{slug}/'
- settings['ARTICLE_SAVE_AS'] = 'blog/{author}/{slug}/index.html'
- article_kwargs = self._copy_page_kwargs()
- article_kwargs['metadata']['author'] = Author('Alexander Todorov',
- settings)
- article_kwargs['metadata']['title'] = 'fnord'
- article_kwargs['settings'] = settings
- article = Article(**article_kwargs)
- self.assertEqual(article.url, 'blog/atodorov/fnord/')
- self.assertEqual(article.save_as, 'blog/atodorov/fnord/index.html')
-
- def test_slugify_category_with_dots(self):
- settings = get_settings()
- settings['CATEGORY_REGEX_SUBSTITUTIONS'] = [
- ('Fedora QA', 'fedora.qa'),
- ]
- settings['ARTICLE_URL'] = '{category}/{slug}/'
- article_kwargs = self._copy_page_kwargs()
- article_kwargs['metadata']['category'] = Category('Fedora QA',
- settings)
- article_kwargs['metadata']['title'] = 'This Week in Fedora QA'
- article_kwargs['settings'] = settings
- article = Article(**article_kwargs)
- self.assertEqual(article.url, 'fedora.qa/this-week-in-fedora-qa/')
-
- def test_valid_save_as_detects_breakout(self):
- settings = get_settings()
- article_kwargs = self._copy_page_kwargs()
- article_kwargs['metadata']['slug'] = '../foo'
- article_kwargs['settings'] = settings
- article = Article(**article_kwargs)
- self.assertFalse(article._has_valid_save_as())
-
- def test_valid_save_as_detects_breakout_to_root(self):
- settings = get_settings()
- article_kwargs = self._copy_page_kwargs()
- article_kwargs['metadata']['slug'] = '/foo'
- article_kwargs['settings'] = settings
- article = Article(**article_kwargs)
- self.assertFalse(article._has_valid_save_as())
-
- def test_valid_save_as_passes_valid(self):
- settings = get_settings()
- article_kwargs = self._copy_page_kwargs()
- article_kwargs['metadata']['slug'] = 'foo'
- article_kwargs['settings'] = settings
- article = Article(**article_kwargs)
- self.assertTrue(article._has_valid_save_as())
-
-
-class TestStatic(LoggedTestCase):
-
- def setUp(self):
- super().setUp()
- self.settings = get_settings(
- STATIC_SAVE_AS='{path}',
- STATIC_URL='{path}',
- PAGE_SAVE_AS=os.path.join('outpages', '{slug}.html'),
- PAGE_URL='outpages/{slug}.html')
- self.context = get_context(self.settings)
-
- self.static = Static(content=None, metadata={}, settings=self.settings,
- source_path=posix_join('dir', 'foo.jpg'),
- context=self.context)
-
- self.context['static_content'][self.static.source_path] = self.static
-
- def tearDown(self):
- pass
-
- def test_attach_to_same_dir(self):
- """attach_to() overrides a static file's save_as and url.
- """
- page = Page(
- content="fake page",
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'fakepage.md'))
- self.static.attach_to(page)
-
- expected_save_as = os.path.join('outpages', 'foo.jpg')
- self.assertEqual(self.static.save_as, expected_save_as)
- self.assertEqual(self.static.url, path_to_url(expected_save_as))
-
- def test_attach_to_parent_dir(self):
- """attach_to() preserves dirs inside the linking document dir.
- """
- page = Page(content="fake page", metadata={'title': 'fakepage'},
- settings=self.settings, source_path='fakepage.md')
- self.static.attach_to(page)
-
- expected_save_as = os.path.join('outpages', 'dir', 'foo.jpg')
- self.assertEqual(self.static.save_as, expected_save_as)
- self.assertEqual(self.static.url, path_to_url(expected_save_as))
-
- def test_attach_to_other_dir(self):
- """attach_to() ignores dirs outside the linking document dir.
- """
- page = Page(content="fake page",
- metadata={'title': 'fakepage'}, settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'))
- self.static.attach_to(page)
-
- expected_save_as = os.path.join('outpages', 'foo.jpg')
- self.assertEqual(self.static.save_as, expected_save_as)
- self.assertEqual(self.static.url, path_to_url(expected_save_as))
-
- def test_attach_to_ignores_subsequent_calls(self):
- """attach_to() does nothing when called a second time.
- """
- page = Page(content="fake page",
- metadata={'title': 'fakepage'}, settings=self.settings,
- source_path=os.path.join('dir', 'fakepage.md'))
-
- self.static.attach_to(page)
-
- otherdir_settings = self.settings.copy()
- otherdir_settings.update(dict(
- PAGE_SAVE_AS=os.path.join('otherpages', '{slug}.html'),
- PAGE_URL='otherpages/{slug}.html'))
- otherdir_page = Page(
- content="other page",
- metadata={'title': 'otherpage'},
- settings=otherdir_settings,
- source_path=os.path.join('dir', 'otherpage.md'))
-
- self.static.attach_to(otherdir_page)
-
- otherdir_save_as = os.path.join('otherpages', 'foo.jpg')
- self.assertNotEqual(self.static.save_as, otherdir_save_as)
- self.assertNotEqual(self.static.url, path_to_url(otherdir_save_as))
-
- def test_attach_to_does_nothing_after_save_as_referenced(self):
- """attach_to() does nothing if the save_as was already referenced.
- (For example, by a {static} link an a document processed earlier.)
- """
- original_save_as = self.static.save_as
-
- page = Page(
- content="fake page",
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'fakepage.md'))
- self.static.attach_to(page)
-
- self.assertEqual(self.static.save_as, original_save_as)
- self.assertEqual(self.static.url, path_to_url(original_save_as))
-
- def test_attach_to_does_nothing_after_url_referenced(self):
- """attach_to() does nothing if the url was already referenced.
- (For example, by a {static} link an a document processed earlier.)
- """
- original_url = self.static.url
-
- page = Page(
- content="fake page",
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'fakepage.md'))
- self.static.attach_to(page)
-
- self.assertEqual(self.static.save_as, self.static.source_path)
- self.assertEqual(self.static.url, original_url)
-
- def test_attach_to_does_not_override_an_override(self):
- """attach_to() does not override paths that were overridden elsewhere.
- (For example, by the user with EXTRA_PATH_METADATA)
- """
- customstatic = Static(
- content=None,
- metadata=dict(save_as='customfoo.jpg', url='customfoo.jpg'),
- settings=self.settings,
- source_path=os.path.join('dir', 'foo.jpg'),
- context=self.settings.copy())
-
- page = Page(
- content="fake page",
- metadata={'title': 'fakepage'}, settings=self.settings,
- source_path=os.path.join('dir', 'fakepage.md'))
-
- customstatic.attach_to(page)
-
- self.assertEqual(customstatic.save_as, 'customfoo.jpg')
- self.assertEqual(customstatic.url, 'customfoo.jpg')
-
- def test_attach_link_syntax(self):
- """{attach} link syntax triggers output path override & url replacement.
- """
- html = 'link'
- page = Page(
- content=html,
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertNotEqual(
- content, html,
- "{attach} link syntax did not trigger URL replacement.")
-
- expected_save_as = os.path.join('outpages', 'foo.jpg')
- self.assertEqual(self.static.save_as, expected_save_as)
- self.assertEqual(self.static.url, path_to_url(expected_save_as))
-
- def test_tag_link_syntax(self):
- "{tag} link syntax triggers url replacement."
-
- html = 'link'
- page = Page(
- content=html,
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertNotEqual(content, html)
-
- def test_category_link_syntax(self):
- "{category} link syntax triggers url replacement."
-
- html = 'link'
- page = Page(
- content=html,
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertNotEqual(content, html)
-
- def test_author_link_syntax(self):
- "{author} link syntax triggers url replacement."
-
- html = 'link'
- page = Page(
- content=html,
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertNotEqual(content, html)
-
- def test_index_link_syntax(self):
- "{index} link syntax triggers url replacement."
-
- html = 'link'
- page = Page(
- content=html,
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertNotEqual(content, html)
-
- expected_html = ('link')
- self.assertEqual(content, expected_html)
-
- def test_unknown_link_syntax(self):
- "{unknown} link syntax should trigger warning."
-
- html = 'link'
- page = Page(content=html,
- metadata={'title': 'fakepage'}, settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertEqual(content, html)
- self.assertLogCountEqual(
- count=1,
- msg="Replacement Indicator 'unknown' not recognized, "
- "skipping replacement",
- level=logging.WARNING)
-
- def test_link_to_unknown_file(self):
- "{filename} link to unknown file should trigger warning."
-
- html = 'link'
- page = Page(content=html,
- metadata={'title': 'fakepage'}, settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertEqual(content, html)
- self.assertLogCountEqual(
- count=1,
- msg="Unable to find 'foo', skipping url replacement.",
- level=logging.WARNING)
-
- def test_index_link_syntax_with_spaces(self):
- """{index} link syntax triggers url replacement
- with spaces around the equal sign."""
-
- html = 'link'
- page = Page(
- content=html,
- metadata={'title': 'fakepage'},
- settings=self.settings,
- source_path=os.path.join('dir', 'otherdir', 'fakepage.md'),
- context=self.context)
- content = page.get_content('')
-
- self.assertNotEqual(content, html)
-
- expected_html = ('link')
- self.assertEqual(content, expected_html)
-
- def test_not_save_as_draft(self):
- """Static.save_as is not affected by draft status."""
-
- static = Static(
- content=None,
- metadata=dict(status='draft',),
- settings=self.settings,
- source_path=os.path.join('dir', 'foo.jpg'),
- context=self.settings.copy())
-
- expected_save_as = posixize_path(os.path.join('dir', 'foo.jpg'))
- self.assertEqual(static.status, 'draft')
- self.assertEqual(static.save_as, expected_save_as)
- self.assertEqual(static.url, path_to_url(expected_save_as))
diff --git a/pelican/tests/test_generators.py b/pelican/tests/test_generators.py
deleted file mode 100644
index 0a4a8fdc..00000000
--- a/pelican/tests/test_generators.py
+++ /dev/null
@@ -1,1244 +0,0 @@
-import locale
-import os
-import sys
-from shutil import copy, rmtree
-from tempfile import mkdtemp
-from unittest.mock import MagicMock
-
-from pelican.generators import (ArticlesGenerator, Generator, PagesGenerator,
- PelicanTemplateNotFound, StaticGenerator,
- TemplatePagesGenerator)
-from pelican.tests.support import (can_symlink, get_context, get_settings,
- unittest)
-from pelican.writers import Writer
-
-
-CUR_DIR = os.path.dirname(__file__)
-CONTENT_DIR = os.path.join(CUR_DIR, 'content')
-
-
-class TestGenerator(unittest.TestCase):
- def setUp(self):
- self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, 'C')
- self.settings = get_settings()
- self.settings['READERS'] = {'asc': None}
- self.generator = Generator(self.settings.copy(), self.settings,
- CUR_DIR, self.settings['THEME'], None)
-
- def tearDown(self):
- locale.setlocale(locale.LC_ALL, self.old_locale)
-
- def test_include_path(self):
- self.settings['IGNORE_FILES'] = {'ignored1.rst', 'ignored2.rst'}
-
- filename = os.path.join(CUR_DIR, 'content', 'article.rst')
- include_path = self.generator._include_path
- self.assertTrue(include_path(filename))
- self.assertTrue(include_path(filename, extensions=('rst',)))
- self.assertFalse(include_path(filename, extensions=('md',)))
-
- ignored_file = os.path.join(CUR_DIR, 'content', 'ignored1.rst')
- self.assertFalse(include_path(ignored_file))
-
- def test_get_files_exclude(self):
- """Test that Generator.get_files() properly excludes directories.
- """
- # We use our own Generator so we can give it our own content path
- generator = Generator(
- context=self.settings.copy(),
- settings=self.settings,
- path=os.path.join(CUR_DIR, 'nested_content'),
- theme=self.settings['THEME'], output_path=None)
-
- filepaths = generator.get_files(paths=['maindir'])
- found_files = {os.path.basename(f) for f in filepaths}
- expected_files = {'maindir.md', 'subdir.md'}
- self.assertFalse(
- expected_files - found_files,
- "get_files() failed to find one or more files")
-
- # Test string as `paths` argument rather than list
- filepaths = generator.get_files(paths='maindir')
- found_files = {os.path.basename(f) for f in filepaths}
- expected_files = {'maindir.md', 'subdir.md'}
- self.assertFalse(
- expected_files - found_files,
- "get_files() failed to find one or more files")
-
- filepaths = generator.get_files(paths=[''], exclude=['maindir'])
- found_files = {os.path.basename(f) for f in filepaths}
- self.assertNotIn(
- 'maindir.md', found_files,
- "get_files() failed to exclude a top-level directory")
- self.assertNotIn(
- 'subdir.md', found_files,
- "get_files() failed to exclude a subdir of an excluded directory")
-
- filepaths = generator.get_files(
- paths=[''],
- exclude=[os.path.join('maindir', 'subdir')])
- found_files = {os.path.basename(f) for f in filepaths}
- self.assertNotIn(
- 'subdir.md', found_files,
- "get_files() failed to exclude a subdirectory")
-
- filepaths = generator.get_files(paths=[''], exclude=['subdir'])
- found_files = {os.path.basename(f) for f in filepaths}
- self.assertIn(
- 'subdir.md', found_files,
- "get_files() excluded a subdirectory by name, ignoring its path")
-
- def test_custom_jinja_environment(self):
- """
- Test that setting the JINJA_ENVIRONMENT
- properly gets set from the settings config
- """
- settings = get_settings()
- comment_start_string = 'abc'
- comment_end_string = '/abc'
- settings['JINJA_ENVIRONMENT'] = {
- 'comment_start_string': comment_start_string,
- 'comment_end_string': comment_end_string
- }
- generator = Generator(settings.copy(), settings,
- CUR_DIR, settings['THEME'], None)
- self.assertEqual(comment_start_string,
- generator.env.comment_start_string)
- self.assertEqual(comment_end_string,
- generator.env.comment_end_string)
-
- def test_theme_overrides(self):
- """
- Test that the THEME_TEMPLATES_OVERRIDES configuration setting is
- utilized correctly in the Generator.
- """
- override_dirs = (os.path.join(CUR_DIR, 'theme_overrides', 'level1'),
- os.path.join(CUR_DIR, 'theme_overrides', 'level2'))
- self.settings['THEME_TEMPLATES_OVERRIDES'] = override_dirs
- generator = Generator(
- context=self.settings.copy(),
- settings=self.settings,
- path=CUR_DIR,
- theme=self.settings['THEME'],
- output_path=None)
-
- filename = generator.get_template('article').filename
- self.assertEqual(override_dirs[0], os.path.dirname(filename))
- self.assertEqual('article.html', os.path.basename(filename))
-
- filename = generator.get_template('authors').filename
- self.assertEqual(override_dirs[1], os.path.dirname(filename))
- self.assertEqual('authors.html', os.path.basename(filename))
-
- filename = generator.get_template('taglist').filename
- self.assertEqual(os.path.join(self.settings['THEME'], 'templates'),
- os.path.dirname(filename))
- self.assertNotIn(os.path.dirname(filename), override_dirs)
- self.assertEqual('taglist.html', os.path.basename(filename))
-
- def test_simple_prefix(self):
- """
- Test `!simple` theme prefix.
- """
- filename = self.generator.get_template('!simple/authors').filename
- expected_path = os.path.join(
- os.path.dirname(CUR_DIR), 'themes', 'simple', 'templates')
- self.assertEqual(expected_path, os.path.dirname(filename))
- self.assertEqual('authors.html', os.path.basename(filename))
-
- def test_theme_prefix(self):
- """
- Test `!theme` theme prefix.
- """
- filename = self.generator.get_template('!theme/authors').filename
- expected_path = os.path.join(
- os.path.dirname(CUR_DIR), 'themes', 'notmyidea', 'templates')
- self.assertEqual(expected_path, os.path.dirname(filename))
- self.assertEqual('authors.html', os.path.basename(filename))
-
- def test_bad_prefix(self):
- """
- Test unknown/bad theme prefix throws exception.
- """
- self.assertRaises(PelicanTemplateNotFound, self.generator.get_template,
- '!UNKNOWN/authors')
-
-
-class TestArticlesGenerator(unittest.TestCase):
-
- @classmethod
- def setUpClass(cls):
- settings = get_settings()
- settings['DEFAULT_CATEGORY'] = 'Default'
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- settings['READERS'] = {'asc': None}
- settings['CACHE_CONTENT'] = False
- context = get_context(settings)
-
- cls.generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- cls.generator.generate_context()
- cls.articles = cls.distill_articles(cls.generator.articles)
- cls.drafts = cls.distill_articles(cls.generator.drafts)
- cls.hidden_articles = cls.distill_articles(cls.generator.hidden_articles)
-
- def setUp(self):
- self.temp_cache = mkdtemp(prefix='pelican_cache.')
-
- def tearDown(self):
- rmtree(self.temp_cache)
-
- @staticmethod
- def distill_articles(articles):
- return [[article.title, article.status, article.category.name,
- article.template] for article in articles]
-
- def test_generate_feeds(self):
- settings = get_settings()
- settings['CACHE_PATH'] = self.temp_cache
- generator = ArticlesGenerator(
- context=settings, settings=settings,
- path=None, theme=settings['THEME'], output_path=None)
- writer = MagicMock()
- generator.generate_feeds(writer)
- writer.write_feed.assert_called_with([], settings,
- 'feeds/all.atom.xml',
- 'feeds/all.atom.xml')
-
- generator = ArticlesGenerator(
- context=settings, settings=get_settings(FEED_ALL_ATOM=None),
- path=None, theme=settings['THEME'], output_path=None)
- writer = MagicMock()
- generator.generate_feeds(writer)
- self.assertFalse(writer.write_feed.called)
-
- def test_generate_feeds_override_url(self):
- settings = get_settings()
- settings['CACHE_PATH'] = self.temp_cache
- settings['FEED_ALL_ATOM_URL'] = 'feeds/atom/all/'
- generator = ArticlesGenerator(
- context=settings, settings=settings,
- path=None, theme=settings['THEME'], output_path=None)
- writer = MagicMock()
- generator.generate_feeds(writer)
- writer.write_feed.assert_called_with([], settings,
- 'feeds/all.atom.xml',
- 'feeds/atom/all/')
-
- def test_generate_context(self):
- articles_expected = [
- ['Article title', 'published', 'Default', 'article'],
- ['Article with markdown and summary metadata multi', 'published',
- 'Default', 'article'],
- ['Article with markdown and nested summary metadata', 'published',
- 'Default', 'article'],
- ['Article with markdown and summary metadata single', 'published',
- 'Default', 'article'],
- ['Article with markdown containing footnotes', 'published',
- 'Default', 'article'],
- ['Article with template', 'published', 'Default', 'custom'],
- ['Metadata tags as list!', 'published', 'Default', 'article'],
- ['Rst with filename metadata', 'published', 'yeah', 'article'],
- ['One -, two --, three --- dashes!', 'published', 'Default',
- 'article'],
- ['One -, two --, three --- dashes!', 'published', 'Default',
- 'article'],
- ['Test Markdown extensions', 'published', 'Default', 'article'],
- ['Test markdown File', 'published', 'test', 'article'],
- ['Test md File', 'published', 'test', 'article'],
- ['Test mdown File', 'published', 'test', 'article'],
- ['Test metadata duplicates', 'published', 'test', 'article'],
- ['Test mkd File', 'published', 'test', 'article'],
- ['This is a super article !', 'published', 'Yeah', 'article'],
- ['This is a super article !', 'published', 'Yeah', 'article'],
- ['Article with Nonconformant HTML meta tags', 'published',
- 'Default', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'yeah', 'article'],
- ['This is a super article !', 'published', 'Default', 'article'],
- ['Article with an inline SVG', 'published', 'Default', 'article'],
- ['This is an article with category !', 'published', 'yeah',
- 'article'],
- ['This is an article with multiple authors!', 'published',
- 'Default', 'article'],
- ['This is an article with multiple authors!', 'published',
- 'Default', 'article'],
- ['This is an article with multiple authors in list format!',
- 'published', 'Default', 'article'],
- ['This is an article with multiple authors in lastname, '
- 'firstname format!', 'published', 'Default', 'article'],
- ['This is an article without category !', 'published', 'Default',
- 'article'],
- ['This is an article without category !', 'published',
- 'TestCategory', 'article'],
- ['An Article With Code Block To Test Typogrify Ignore',
- 'published', 'Default', 'article'],
- ['マックOS X 10.8でパイソンとVirtualenvをインストールと設定',
- 'published', '指導書', 'article'],
- ]
- self.assertEqual(sorted(articles_expected), sorted(self.articles))
-
- def test_articles_draft(self):
- draft_articles_expected = [
- ['Draft article', 'draft', 'Default', 'article'],
- ]
- self.assertEqual(sorted(draft_articles_expected), sorted(self.drafts))
-
- def test_articles_hidden(self):
- hidden_articles_expected = [
- ['Hidden article', 'hidden', 'Default', 'article'],
- ]
- self.assertEqual(sorted(hidden_articles_expected), sorted(self.hidden_articles))
-
- def test_generate_categories(self):
- # test for name
- # categories are grouped by slug; if two categories have the same slug
- # but different names they will be grouped together, the first one in
- # terms of process order will define the name for that category
- categories = [cat.name for cat, _ in self.generator.categories]
- categories_alternatives = (
- sorted(['Default', 'TestCategory', 'Yeah', 'test', '指導書']),
- sorted(['Default', 'TestCategory', 'yeah', 'test', '指導書']),
- )
- self.assertIn(sorted(categories), categories_alternatives)
- # test for slug
- categories = [cat.slug for cat, _ in self.generator.categories]
- categories_expected = ['default', 'testcategory', 'yeah', 'test',
- 'zhi-dao-shu']
- self.assertEqual(sorted(categories), sorted(categories_expected))
-
- def test_do_not_use_folder_as_category(self):
- settings = get_settings()
- settings['DEFAULT_CATEGORY'] = 'Default'
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- settings['USE_FOLDER_AS_CATEGORY'] = False
- settings['CACHE_PATH'] = self.temp_cache
- settings['READERS'] = {'asc': None}
- context = get_context(settings)
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- # test for name
- # categories are grouped by slug; if two categories have the same slug
- # but different names they will be grouped together, the first one in
- # terms of process order will define the name for that category
- categories = [cat.name for cat, _ in generator.categories]
- categories_alternatives = (
- sorted(['Default', 'Yeah', 'test', '指導書']),
- sorted(['Default', 'yeah', 'test', '指導書']),
- )
- self.assertIn(sorted(categories), categories_alternatives)
- # test for slug
- categories = [cat.slug for cat, _ in generator.categories]
- categories_expected = ['default', 'yeah', 'test', 'zhi-dao-shu']
- self.assertEqual(sorted(categories), sorted(categories_expected))
-
- def test_direct_templates_save_as_url_default(self):
-
- settings = get_settings()
- settings['CACHE_PATH'] = self.temp_cache
- context = get_context(settings)
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=None, theme=settings['THEME'], output_path=None)
- write = MagicMock()
- generator.generate_direct_templates(write)
- write.assert_called_with("archives.html",
- generator.get_template("archives"), context,
- articles=generator.articles,
- dates=generator.dates, blog=True,
- template_name='archives',
- page_name='archives', url="archives.html")
-
- def test_direct_templates_save_as_url_modified(self):
-
- settings = get_settings()
- settings['DIRECT_TEMPLATES'] = ['archives']
- settings['ARCHIVES_SAVE_AS'] = 'archives/index.html'
- settings['ARCHIVES_URL'] = 'archives/'
- settings['CACHE_PATH'] = self.temp_cache
- generator = ArticlesGenerator(
- context=settings, settings=settings,
- path=None, theme=settings['THEME'], output_path=None)
- write = MagicMock()
- generator.generate_direct_templates(write)
- write.assert_called_with("archives/index.html",
- generator.get_template("archives"), settings,
- articles=generator.articles,
- dates=generator.dates, blog=True,
- template_name='archives',
- page_name='archives/index',
- url="archives/")
-
- def test_direct_templates_save_as_false(self):
-
- settings = get_settings()
- settings['DIRECT_TEMPLATES'] = ['archives']
- settings['ARCHIVES_SAVE_AS'] = False
- settings['CACHE_PATH'] = self.temp_cache
- generator = ArticlesGenerator(
- context=settings, settings=settings,
- path=None, theme=settings['THEME'], output_path=None)
- write = MagicMock()
- generator.generate_direct_templates(write)
- self.assertEqual(write.call_count, 0)
-
- def test_per_article_template(self):
- """
- Custom template articles get the field but standard/unset are None
- """
- custom_template = ['Article with template', 'published', 'Default',
- 'custom']
- standard_template = ['This is a super article !', 'published', 'Yeah',
- 'article']
- self.assertIn(custom_template, self.articles)
- self.assertIn(standard_template, self.articles)
-
- def test_period_in_timeperiod_archive(self):
- """
- Test that the context of a generated period_archive is passed
- 'period' : a tuple of year, month, day according to the time period
- """
- old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, 'C')
- settings = get_settings()
-
- settings['YEAR_ARCHIVE_SAVE_AS'] = 'posts/{date:%Y}/index.html'
- settings['YEAR_ARCHIVE_URL'] = 'posts/{date:%Y}/'
- settings['CACHE_PATH'] = self.temp_cache
- context = get_context(settings)
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- write = MagicMock()
- generator.generate_period_archives(write)
- dates = [d for d in generator.dates if d.date.year == 1970]
- articles = [d for d in generator.articles if d.date.year == 1970]
- self.assertEqual(len(dates), 1)
- # among other things it must have at least been called with this
- context["period"] = (1970,)
- context["period_num"] = (1970,)
- write.assert_called_with("posts/1970/index.html",
- generator.get_template("period_archives"),
- context, blog=True, articles=articles,
- dates=dates, template_name='period_archives',
- url="posts/1970/",
- all_articles=generator.articles)
-
- settings['MONTH_ARCHIVE_SAVE_AS'] = \
- 'posts/{date:%Y}/{date:%b}/index.html'
- settings['MONTH_ARCHIVE_URL'] = \
- 'posts/{date:%Y}/{date:%b}/'
- context = get_context(settings)
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- write = MagicMock()
- generator.generate_period_archives(write)
- dates = [d for d in generator.dates
- if d.date.year == 1970 and d.date.month == 1]
- articles = [d for d in generator.articles
- if d.date.year == 1970 and d.date.month == 1]
- self.assertEqual(len(dates), 1)
- context["period"] = (1970, "January")
- context["period_num"] = (1970, 1)
- # among other things it must have at least been called with this
- write.assert_called_with("posts/1970/Jan/index.html",
- generator.get_template("period_archives"),
- context, blog=True, articles=articles,
- dates=dates, template_name='period_archives',
- url="posts/1970/Jan/",
- all_articles=generator.articles)
-
- settings['DAY_ARCHIVE_SAVE_AS'] = \
- 'posts/{date:%Y}/{date:%b}/{date:%d}/index.html'
- settings['DAY_ARCHIVE_URL'] = \
- 'posts/{date:%Y}/{date:%b}/{date:%d}/'
- context = get_context(settings)
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- write = MagicMock()
- generator.generate_period_archives(write)
- dates = [
- d for d in generator.dates if
- d.date.year == 1970 and
- d.date.month == 1 and
- d.date.day == 1
- ]
- articles = [
- d for d in generator.articles if
- d.date.year == 1970 and
- d.date.month == 1 and
- d.date.day == 1
- ]
- self.assertEqual(len(dates), 1)
- context["period"] = (1970, "January", 1)
- context["period_num"] = (1970, 1, 1)
- # among other things it must have at least been called with this
- write.assert_called_with("posts/1970/Jan/01/index.html",
- generator.get_template("period_archives"),
- context, blog=True, articles=articles,
- dates=dates, template_name='period_archives',
- url="posts/1970/Jan/01/",
- all_articles=generator.articles)
- locale.setlocale(locale.LC_ALL, old_locale)
-
- def test_nonexistent_template(self):
- """Attempt to load a non-existent template"""
- settings = get_settings()
- context = get_context(settings)
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=None, theme=settings['THEME'], output_path=None)
- self.assertRaises(Exception, generator.get_template, "not_a_template")
-
- def test_generate_authors(self):
- """Check authors generation."""
- authors = [author.name for author, _ in self.generator.authors]
- authors_expected = sorted(
- ['Alexis Métaireau', 'Author, First', 'Author, Second',
- 'First Author', 'Second Author'])
- self.assertEqual(sorted(authors), authors_expected)
- # test for slug
- authors = [author.slug for author, _ in self.generator.authors]
- authors_expected = ['alexis-metaireau', 'author-first',
- 'author-second', 'first-author', 'second-author']
- self.assertEqual(sorted(authors), sorted(authors_expected))
-
- def test_standard_metadata_in_default_metadata(self):
- settings = get_settings()
- settings['CACHE_CONTENT'] = False
- settings['DEFAULT_CATEGORY'] = 'Default'
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- settings['DEFAULT_METADATA'] = (('author', 'Blogger'),
- # category will be ignored in favor of
- # DEFAULT_CATEGORY
- ('category', 'Random'),
- ('tags', 'general, untagged'))
- context = get_context(settings)
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
-
- authors = sorted([author.name for author, _ in generator.authors])
- authors_expected = sorted(['Alexis Métaireau', 'Blogger',
- 'Author, First', 'Author, Second',
- 'First Author', 'Second Author'])
- self.assertEqual(authors, authors_expected)
-
- categories = sorted([category.name
- for category, _ in generator.categories])
- categories_expected = [
- sorted(['Default', 'TestCategory', 'yeah', 'test', '指導書']),
- sorted(['Default', 'TestCategory', 'Yeah', 'test', '指導書'])]
- self.assertIn(categories, categories_expected)
-
- tags = sorted([tag.name for tag in generator.tags])
- tags_expected = sorted(['bar', 'foo', 'foobar', 'general', 'untagged',
- 'パイソン', 'マック'])
- self.assertEqual(tags, tags_expected)
-
- def test_article_order_by(self):
- settings = get_settings()
- settings['DEFAULT_CATEGORY'] = 'Default'
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- settings['ARTICLE_ORDER_BY'] = 'title'
- context = get_context(settings)
-
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
-
- expected = [
- 'An Article With Code Block To Test Typogrify Ignore',
- 'Article title',
- 'Article with Nonconformant HTML meta tags',
- 'Article with an inline SVG',
- 'Article with markdown and nested summary metadata',
- 'Article with markdown and summary metadata multi',
- 'Article with markdown and summary metadata single',
- 'Article with markdown containing footnotes',
- 'Article with template',
- 'Metadata tags as list!',
- 'One -, two --, three --- dashes!',
- 'One -, two --, three --- dashes!',
- 'Rst with filename metadata',
- 'Test Markdown extensions',
- 'Test markdown File',
- 'Test md File',
- 'Test mdown File',
- 'Test metadata duplicates',
- 'Test mkd File',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is a super article !',
- 'This is an article with category !',
- ('This is an article with multiple authors in lastname, '
- 'firstname format!'),
- 'This is an article with multiple authors in list format!',
- 'This is an article with multiple authors!',
- 'This is an article with multiple authors!',
- 'This is an article without category !',
- 'This is an article without category !',
- 'マックOS X 10.8でパイソンとVirtualenvをインストールと設定']
-
- articles = [article.title for article in generator.articles]
- self.assertEqual(articles, expected)
-
- # reversed title
- settings = get_settings()
- settings['DEFAULT_CATEGORY'] = 'Default'
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- settings['ARTICLE_ORDER_BY'] = 'reversed-title'
- context = get_context(settings)
-
- generator = ArticlesGenerator(
- context=context, settings=settings,
- path=CONTENT_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
-
- articles = [article.title for article in generator.articles]
- self.assertEqual(articles, list(reversed(expected)))
-
-
-class TestPageGenerator(unittest.TestCase):
- # Note: Every time you want to test for a new field; Make sure the test
- # pages in "TestPages" have all the fields Add it to distilled in
- # distill_pages Then update the assertEqual in test_generate_context
- # to match expected
-
- def setUp(self):
- self.temp_cache = mkdtemp(prefix='pelican_cache.')
-
- def tearDown(self):
- rmtree(self.temp_cache)
-
- def distill_pages(self, pages):
- return [[page.title, page.status, page.template] for page in pages]
-
- def test_generate_context(self):
- settings = get_settings()
- settings['CACHE_PATH'] = self.temp_cache
- settings['PAGE_PATHS'] = ['TestPages'] # relative to CUR_DIR
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- context = get_context(settings)
-
- generator = PagesGenerator(
- context=context, settings=settings,
- path=CUR_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- pages = self.distill_pages(generator.pages)
- hidden_pages = self.distill_pages(generator.hidden_pages)
- draft_pages = self.distill_pages(generator.draft_pages)
-
- pages_expected = [
- ['This is a test page', 'published', 'page'],
- ['This is a markdown test page', 'published', 'page'],
- ['This is a test page with a preset template', 'published',
- 'custom'],
- ['Page with a bunch of links', 'published', 'page'],
- ['Page with static links', 'published', 'page'],
- ['A Page (Test) for sorting', 'published', 'page'],
- ]
- hidden_pages_expected = [
- ['This is a test hidden page', 'hidden', 'page'],
- ['This is a markdown test hidden page', 'hidden', 'page'],
- ['This is a test hidden page with a custom template', 'hidden',
- 'custom'],
- ]
- draft_pages_expected = [
- ['This is a test draft page', 'draft', 'page'],
- ['This is a markdown test draft page', 'draft', 'page'],
- ['This is a test draft page with a custom template', 'draft',
- 'custom'],
- ]
-
- self.assertEqual(sorted(pages_expected), sorted(pages))
- self.assertEqual(
- sorted(pages_expected),
- sorted(self.distill_pages(generator.context['pages'])))
- self.assertEqual(sorted(hidden_pages_expected), sorted(hidden_pages))
- self.assertEqual(sorted(draft_pages_expected), sorted(draft_pages))
- self.assertEqual(
- sorted(hidden_pages_expected),
- sorted(self.distill_pages(generator.context['hidden_pages'])))
- self.assertEqual(
- sorted(draft_pages_expected),
- sorted(self.distill_pages(generator.context['draft_pages'])))
-
- def test_generate_sorted(self):
- settings = get_settings()
- settings['PAGE_PATHS'] = ['TestPages'] # relative to CUR_DIR
- settings['CACHE_PATH'] = self.temp_cache
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- context = get_context(settings)
-
- # default sort (filename)
- pages_expected_sorted_by_filename = [
- ['This is a test page', 'published', 'page'],
- ['This is a markdown test page', 'published', 'page'],
- ['A Page (Test) for sorting', 'published', 'page'],
- ['Page with a bunch of links', 'published', 'page'],
- ['Page with static links', 'published', 'page'],
- ['This is a test page with a preset template', 'published',
- 'custom'],
- ]
- generator = PagesGenerator(
- context=context, settings=settings,
- path=CUR_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- pages = self.distill_pages(generator.pages)
- self.assertEqual(pages_expected_sorted_by_filename, pages)
-
- # sort by title
- pages_expected_sorted_by_title = [
- ['A Page (Test) for sorting', 'published', 'page'],
- ['Page with a bunch of links', 'published', 'page'],
- ['Page with static links', 'published', 'page'],
- ['This is a markdown test page', 'published', 'page'],
- ['This is a test page', 'published', 'page'],
- ['This is a test page with a preset template', 'published',
- 'custom'],
- ]
- settings['PAGE_ORDER_BY'] = 'title'
- context = get_context(settings)
- generator = PagesGenerator(
- context=context.copy(), settings=settings,
- path=CUR_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- pages = self.distill_pages(generator.pages)
- self.assertEqual(pages_expected_sorted_by_title, pages)
-
- # sort by title reversed
- pages_expected_sorted_by_title = [
- ['This is a test page with a preset template', 'published',
- 'custom'],
- ['This is a test page', 'published', 'page'],
- ['This is a markdown test page', 'published', 'page'],
- ['Page with static links', 'published', 'page'],
- ['Page with a bunch of links', 'published', 'page'],
- ['A Page (Test) for sorting', 'published', 'page'],
- ]
- settings['PAGE_ORDER_BY'] = 'reversed-title'
- context = get_context(settings)
- generator = PagesGenerator(
- context=context, settings=settings,
- path=CUR_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- pages = self.distill_pages(generator.pages)
- self.assertEqual(pages_expected_sorted_by_title, pages)
-
- def test_tag_and_category_links_on_generated_pages(self):
- """
- Test to ensure links of the form {tag}tagname and {category}catname
- are generated correctly on pages
- """
- settings = get_settings()
- settings['PAGE_PATHS'] = ['TestPages'] # relative to CUR_DIR
- settings['CACHE_PATH'] = self.temp_cache
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- context = get_context(settings)
-
- generator = PagesGenerator(
- context=context, settings=settings,
- path=CUR_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
- pages_by_title = {p.title: p for p in generator.pages}
-
- test_content = pages_by_title['Page with a bunch of links'].content
- self.assertIn('', test_content)
- self.assertIn('', test_content)
-
- def test_static_and_attach_links_on_generated_pages(self):
- """
- Test to ensure links of the form {static}filename and {attach}filename
- are included in context['static_links']
- """
- settings = get_settings()
- settings['PAGE_PATHS'] = ['TestPages/page_with_static_links.md']
- settings['CACHE_PATH'] = self.temp_cache
- settings['DEFAULT_DATE'] = (1970, 1, 1)
- context = get_context(settings)
-
- generator = PagesGenerator(
- context=context, settings=settings,
- path=CUR_DIR, theme=settings['THEME'], output_path=None)
- generator.generate_context()
-
- self.assertIn('pelican/tests/TestPages/image0.jpg',
- context['static_links'])
- self.assertIn('pelican/tests/TestPages/image1.jpg',
- context['static_links'])
-
-
-class TestTemplatePagesGenerator(unittest.TestCase):
-
- TEMPLATE_CONTENT = "foo: {{ foo }}"
-
- def setUp(self):
- self.temp_content = mkdtemp(prefix='pelicantests.')
- self.temp_output = mkdtemp(prefix='pelicantests.')
- self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, 'C')
-
- def tearDown(self):
- rmtree(self.temp_content)
- rmtree(self.temp_output)
- locale.setlocale(locale.LC_ALL, self.old_locale)
-
- def test_generate_output(self):
-
- settings = get_settings()
- settings['STATIC_PATHS'] = ['static']
- settings['TEMPLATE_PAGES'] = {
- 'template/source.html': 'generated/file.html'
- }
-
- generator = TemplatePagesGenerator(
- context={'foo': 'bar'}, settings=settings,
- path=self.temp_content, theme='', output_path=self.temp_output)
-
- # create a dummy template file
- template_dir = os.path.join(self.temp_content, 'template')
- template_path = os.path.join(template_dir, 'source.html')
- os.makedirs(template_dir)
- with open(template_path, 'w') as template_file:
- template_file.write(self.TEMPLATE_CONTENT)
-
- writer = Writer(self.temp_output, settings=settings)
- generator.generate_output(writer)
-
- output_path = os.path.join(self.temp_output, 'generated', 'file.html')
-
- # output file has been generated
- self.assertTrue(os.path.exists(output_path))
-
- # output content is correct
- with open(output_path) as output_file:
- self.assertEqual(output_file.read(), 'foo: bar')
-
-
-class TestStaticGenerator(unittest.TestCase):
-
- def setUp(self):
- self.content_path = os.path.join(CUR_DIR, 'mixed_content')
- self.temp_content = mkdtemp(prefix='testcontent.')
- self.temp_output = mkdtemp(prefix='testoutput.')
- self.settings = get_settings()
- self.settings['PATH'] = self.temp_content
- self.settings['STATIC_PATHS'] = ["static"]
- self.settings['OUTPUT_PATH'] = self.temp_output
- os.mkdir(os.path.join(self.temp_content, "static"))
- self.startfile = os.path.join(self.temp_content,
- "static", "staticfile")
- self.endfile = os.path.join(self.temp_output, "static", "staticfile")
- self.generator = StaticGenerator(
- context=get_context(),
- settings=self.settings,
- path=self.temp_content,
- theme="",
- output_path=self.temp_output,
- )
-
- def tearDown(self):
- rmtree(self.temp_content)
- rmtree(self.temp_output)
-
- def set_ancient_mtime(self, path, timestamp=1):
- os.utime(path, (timestamp, timestamp))
-
- def test_theme_static_paths_dirs(self):
- """Test that StaticGenerator properly copies also files mentioned in
- TEMPLATE_STATIC_PATHS, not just directories."""
- settings = get_settings(PATH=self.content_path)
- context = get_context(settings, staticfiles=[])
-
- StaticGenerator(
- context=context, settings=settings,
- path=settings['PATH'], output_path=self.temp_output,
- theme=settings['THEME']).generate_output(None)
-
- # The content of dirs listed in THEME_STATIC_PATHS (defaulting to
- # "static") is put into the output
- self.assertTrue(os.path.isdir(os.path.join(self.temp_output,
- "theme/css/")))
- self.assertTrue(os.path.isdir(os.path.join(self.temp_output,
- "theme/fonts/")))
-
- def test_theme_static_paths_files(self):
- """Test that StaticGenerator properly copies also files mentioned in
- TEMPLATE_STATIC_PATHS, not just directories."""
- settings = get_settings(
- PATH=self.content_path,
- THEME_STATIC_PATHS=['static/css/fonts.css', 'static/fonts/'],)
- context = get_context(settings, staticfiles=[])
-
- StaticGenerator(
- context=context, settings=settings,
- path=settings['PATH'], output_path=self.temp_output,
- theme=settings['THEME']).generate_output(None)
-
- # Only the content of dirs and files listed in THEME_STATIC_PATHS are
- # put into the output, not everything from static/
- self.assertFalse(os.path.isdir(os.path.join(self.temp_output,
- "theme/css/")))
- self.assertFalse(os.path.isdir(os.path.join(self.temp_output,
- "theme/fonts/")))
-
- self.assertTrue(os.path.isfile(os.path.join(
- self.temp_output, "theme/Yanone_Kaffeesatz_400.eot")))
- self.assertTrue(os.path.isfile(os.path.join(
- self.temp_output, "theme/Yanone_Kaffeesatz_400.svg")))
- self.assertTrue(os.path.isfile(os.path.join(
- self.temp_output, "theme/Yanone_Kaffeesatz_400.ttf")))
- self.assertTrue(os.path.isfile(os.path.join(
- self.temp_output, "theme/Yanone_Kaffeesatz_400.woff")))
- self.assertTrue(os.path.isfile(os.path.join(
- self.temp_output, "theme/Yanone_Kaffeesatz_400.woff2")))
- self.assertTrue(os.path.isfile(os.path.join(self.temp_output,
- "theme/font.css")))
- self.assertTrue(os.path.isfile(os.path.join(self.temp_output,
- "theme/fonts.css")))
-
- def test_static_excludes(self):
- """Test that StaticGenerator respects STATIC_EXCLUDES.
- """
- settings = get_settings(
- STATIC_EXCLUDES=['subdir'],
- PATH=self.content_path,
- STATIC_PATHS=[''],)
- context = get_context(settings)
-
- StaticGenerator(
- context=context, settings=settings,
- path=settings['PATH'], output_path=self.temp_output,
- theme=settings['THEME']).generate_context()
-
- staticnames = [os.path.basename(c.source_path)
- for c in context['staticfiles']]
-
- self.assertNotIn(
- 'subdir_fake_image.jpg', staticnames,
- "StaticGenerator processed a file in a STATIC_EXCLUDES directory")
- self.assertIn(
- 'fake_image.jpg', staticnames,
- "StaticGenerator skipped a file that it should have included")
-
- def test_static_exclude_sources(self):
- """Test that StaticGenerator respects STATIC_EXCLUDE_SOURCES.
- """
-
- settings = get_settings(
- STATIC_EXCLUDE_SOURCES=True,
- PATH=self.content_path,
- PAGE_PATHS=[''],
- STATIC_PATHS=[''],
- CACHE_CONTENT=False,)
- context = get_context(settings)
-
- for generator_class in (PagesGenerator, StaticGenerator):
- generator_class(
- context=context, settings=settings,
- path=settings['PATH'], output_path=self.temp_output,
- theme=settings['THEME']).generate_context()
-
- staticnames = [os.path.basename(c.source_path)
- for c in context['staticfiles']]
-
- self.assertFalse(
- any(name.endswith(".md") for name in staticnames),
- "STATIC_EXCLUDE_SOURCES=True failed to exclude a markdown file")
-
- settings.update(STATIC_EXCLUDE_SOURCES=False)
- context = get_context(settings)
-
- for generator_class in (PagesGenerator, StaticGenerator):
- generator_class(
- context=context, settings=settings,
- path=settings['PATH'], output_path=self.temp_output,
- theme=settings['THEME']).generate_context()
-
- staticnames = [os.path.basename(c.source_path)
- for c in context['staticfiles']]
-
- self.assertTrue(
- any(name.endswith(".md") for name in staticnames),
- "STATIC_EXCLUDE_SOURCES=False failed to include a markdown file")
-
- def test_static_links(self):
- """Test that StaticGenerator uses files in static_links
- """
- settings = get_settings(
- STATIC_EXCLUDES=['subdir'],
- PATH=self.content_path,
- STATIC_PATHS=[],)
- context = get_context(settings)
- context['static_links'] |= {'short_page.md', 'subdir_fake_image.jpg'}
-
- StaticGenerator(
- context=context, settings=settings,
- path=settings['PATH'], output_path=self.temp_output,
- theme=settings['THEME']).generate_context()
-
- staticfiles_names = [
- os.path.basename(c.source_path) for c in context['staticfiles']]
-
- static_content_names = [
- os.path.basename(c) for c in context['static_content']]
-
- self.assertIn(
- 'short_page.md', staticfiles_names,
- "StaticGenerator skipped a file that it should have included")
- self.assertIn(
- 'short_page.md', static_content_names,
- "StaticGenerator skipped a file that it should have included")
- self.assertIn(
- 'subdir_fake_image.jpg', staticfiles_names,
- "StaticGenerator skipped a file that it should have included")
- self.assertIn(
- 'subdir_fake_image.jpg', static_content_names,
- "StaticGenerator skipped a file that it should have included")
-
- def test_copy_one_file(self):
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- self.generator.generate_context()
- self.generator.generate_output(None)
- with open(self.endfile) as f:
- self.assertEqual(f.read(), "staticcontent")
-
- def test_file_update_required_when_dest_does_not_exist(self):
- staticfile = MagicMock()
- staticfile.source_path = self.startfile
- staticfile.save_as = self.endfile
- with open(staticfile.source_path, "w") as f:
- f.write("a")
- update_required = self.generator._file_update_required(staticfile)
- self.assertTrue(update_required)
-
- def test_dest_and_source_mtimes_are_equal(self):
- staticfile = MagicMock()
- staticfile.source_path = self.startfile
- staticfile.save_as = self.endfile
- self.settings['STATIC_CHECK_IF_MODIFIED'] = True
- with open(staticfile.source_path, "w") as f:
- f.write("a")
- os.mkdir(os.path.join(self.temp_output, "static"))
- copy(staticfile.source_path, staticfile.save_as)
- isnewer = self.generator._source_is_newer(staticfile)
- self.assertFalse(isnewer)
-
- def test_source_is_newer(self):
- staticfile = MagicMock()
- staticfile.source_path = self.startfile
- staticfile.save_as = self.endfile
- with open(staticfile.source_path, "w") as f:
- f.write("a")
- os.mkdir(os.path.join(self.temp_output, "static"))
- copy(staticfile.source_path, staticfile.save_as)
- self.set_ancient_mtime(staticfile.save_as)
- isnewer = self.generator._source_is_newer(staticfile)
- self.assertTrue(isnewer)
-
- def test_skip_file_when_source_is_not_newer(self):
- self.settings['STATIC_CHECK_IF_MODIFIED'] = True
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- os.mkdir(os.path.join(self.temp_output, "static"))
- with open(self.endfile, "w") as f:
- f.write("staticcontent")
- expected = os.path.getmtime(self.endfile)
- self.set_ancient_mtime(self.startfile)
- self.generator.generate_context()
- self.generator.generate_output(None)
- self.assertEqual(os.path.getmtime(self.endfile), expected)
-
- def test_dont_link_by_default(self):
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- self.generator.generate_context()
- self.generator.generate_output(None)
- self.assertFalse(os.path.samefile(self.startfile, self.endfile))
-
- def test_output_file_is_linked_to_source(self):
- self.settings['STATIC_CREATE_LINKS'] = True
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- self.generator.generate_context()
- self.generator.generate_output(None)
- self.assertTrue(os.path.samefile(self.startfile, self.endfile))
-
- def test_output_file_exists_and_is_newer(self):
- self.settings['STATIC_CREATE_LINKS'] = True
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- os.mkdir(os.path.join(self.temp_output, "static"))
- with open(self.endfile, "w") as f:
- f.write("othercontent")
- self.generator.generate_context()
- self.generator.generate_output(None)
- self.assertTrue(os.path.samefile(self.startfile, self.endfile))
-
- @unittest.skipUnless(can_symlink(), 'No symlink privilege')
- def test_can_symlink_when_hardlink_not_possible(self):
- self.settings['STATIC_CREATE_LINKS'] = True
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- os.mkdir(os.path.join(self.temp_output, "static"))
- self.generator.fallback_to_symlinks = True
- self.generator.generate_context()
- self.generator.generate_output(None)
- self.assertTrue(os.path.islink(self.endfile))
-
- @unittest.skipUnless(can_symlink(), 'No symlink privilege')
- def test_existing_symlink_is_considered_up_to_date(self):
- self.settings['STATIC_CREATE_LINKS'] = True
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- os.mkdir(os.path.join(self.temp_output, "static"))
- os.symlink(self.startfile, self.endfile)
- staticfile = MagicMock()
- staticfile.source_path = self.startfile
- staticfile.save_as = self.endfile
- requires_update = self.generator._file_update_required(staticfile)
- self.assertFalse(requires_update)
-
- @unittest.skipUnless(can_symlink(), 'No symlink privilege')
- def test_invalid_symlink_is_overwritten(self):
- self.settings['STATIC_CREATE_LINKS'] = True
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- os.mkdir(os.path.join(self.temp_output, "static"))
- os.symlink("invalid", self.endfile)
- staticfile = MagicMock()
- staticfile.source_path = self.startfile
- staticfile.save_as = self.endfile
- requires_update = self.generator._file_update_required(staticfile)
- self.assertTrue(requires_update)
- self.generator.fallback_to_symlinks = True
- self.generator.generate_context()
- self.generator.generate_output(None)
- self.assertTrue(os.path.islink(self.endfile))
-
- # os.path.realpath is broken on Windows before python3.8 for symlinks.
- # This is a (ugly) workaround.
- # see: https://bugs.python.org/issue9949
- if os.name == 'nt' and sys.version_info < (3, 8):
- def get_real_path(path):
- return os.readlink(path) if os.path.islink(path) else path
- else:
- get_real_path = os.path.realpath
-
- self.assertEqual(get_real_path(self.endfile),
- get_real_path(self.startfile))
-
- def test_delete_existing_file_before_mkdir(self):
- with open(self.startfile, "w") as f:
- f.write("staticcontent")
- with open(os.path.join(self.temp_output, "static"), "w") as f:
- f.write("This file should be a directory")
- self.generator.generate_context()
- self.generator.generate_output(None)
- self.assertTrue(
- os.path.isdir(os.path.join(self.temp_output, "static")))
- self.assertTrue(os.path.isfile(self.endfile))
-
-
-class TestJinja2Environment(unittest.TestCase):
-
- def setUp(self):
- self.temp_content = mkdtemp(prefix='pelicantests.')
- self.temp_output = mkdtemp(prefix='pelicantests.')
- self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, 'C')
-
- def tearDown(self):
- rmtree(self.temp_content)
- rmtree(self.temp_output)
- locale.setlocale(locale.LC_ALL, self.old_locale)
-
- def _test_jinja2_helper(self, additional_settings, content, expected):
- settings = get_settings()
- settings['STATIC_PATHS'] = ['static']
- settings['TEMPLATE_PAGES'] = {
- 'template/source.html': 'generated/file.html'
- }
- settings.update(additional_settings)
-
- generator = TemplatePagesGenerator(
- context={'foo': 'foo', 'bar': 'bar'}, settings=settings,
- path=self.temp_content, theme='', output_path=self.temp_output)
-
- # create a dummy template file
- template_dir = os.path.join(self.temp_content, 'template')
- template_path = os.path.join(template_dir, 'source.html')
- os.makedirs(template_dir)
- with open(template_path, 'w') as template_file:
- template_file.write(content)
-
- writer = Writer(self.temp_output, settings=settings)
- generator.generate_output(writer)
-
- output_path = os.path.join(self.temp_output, 'generated', 'file.html')
-
- # output file has been generated
- self.assertTrue(os.path.exists(output_path))
-
- # output content is correct
- with open(output_path) as output_file:
- self.assertEqual(output_file.read(), expected)
-
- def test_jinja2_filter(self):
- """JINJA_FILTERS adds custom filters to Jinja2 environment"""
- content = 'foo: {{ foo|custom_filter }}, bar: {{ bar|custom_filter }}'
- settings = {'JINJA_FILTERS': {'custom_filter': lambda x: x.upper()}}
- expected = 'foo: FOO, bar: BAR'
-
- self._test_jinja2_helper(settings, content, expected)
-
- def test_jinja2_test(self):
- """JINJA_TESTS adds custom tests to Jinja2 environment"""
- content = 'foo {{ foo is custom_test }}, bar {{ bar is custom_test }}'
- settings = {'JINJA_TESTS': {'custom_test': lambda x: x == 'bar'}}
- expected = 'foo False, bar True'
-
- self._test_jinja2_helper(settings, content, expected)
-
- def test_jinja2_global(self):
- """JINJA_GLOBALS adds custom globals to Jinja2 environment"""
- content = '{{ custom_global }}'
- settings = {'JINJA_GLOBALS': {'custom_global': 'foobar'}}
- expected = 'foobar'
-
- self._test_jinja2_helper(settings, content, expected)
-
- def test_jinja2_extension(self):
- """JINJA_ENVIRONMENT adds extensions to Jinja2 environment"""
- content = '{% set stuff = [] %}{% do stuff.append(1) %}{{ stuff }}'
- settings = {'JINJA_ENVIRONMENT': {'extensions': ['jinja2.ext.do']}}
- expected = '[1]'
-
- self._test_jinja2_helper(settings, content, expected)
diff --git a/pelican/tests/test_importer.py b/pelican/tests/test_importer.py
deleted file mode 100644
index 76feb9ce..00000000
--- a/pelican/tests/test_importer.py
+++ /dev/null
@@ -1,453 +0,0 @@
-import locale
-import os
-import re
-from posixpath import join as posix_join
-
-from pelican.settings import DEFAULT_CONFIG
-from pelican.tests.support import (mute, skipIfNoExecutable, temporary_folder,
- unittest)
-from pelican.tools.pelican_import import (blogger2fields, build_header,
- build_markdown_header,
- decode_wp_content,
- download_attachments, fields2pelican,
- get_attachments, wp2fields)
-from pelican.utils import path_to_file_url, slugify
-
-CUR_DIR = os.path.abspath(os.path.dirname(__file__))
-BLOGGER_XML_SAMPLE = os.path.join(CUR_DIR, 'content', 'bloggerexport.xml')
-WORDPRESS_XML_SAMPLE = os.path.join(CUR_DIR, 'content', 'wordpressexport.xml')
-WORDPRESS_ENCODED_CONTENT_SAMPLE = os.path.join(CUR_DIR,
- 'content',
- 'wordpress_content_encoded')
-WORDPRESS_DECODED_CONTENT_SAMPLE = os.path.join(CUR_DIR,
- 'content',
- 'wordpress_content_decoded')
-
-try:
- from bs4 import BeautifulSoup
-except ImportError:
- BeautifulSoup = False # NOQA
-
-try:
- import bs4.builder._lxml as LXML
-except ImportError:
- LXML = False
-
-
-@skipIfNoExecutable(['pandoc', '--version'])
-@unittest.skipUnless(BeautifulSoup, 'Needs BeautifulSoup module')
-class TestBloggerXmlImporter(unittest.TestCase):
-
- def setUp(self):
- self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, 'C')
- self.posts = blogger2fields(BLOGGER_XML_SAMPLE)
-
- def tearDown(self):
- locale.setlocale(locale.LC_ALL, self.old_locale)
-
- def test_recognise_kind_and_title(self):
- """Check that importer only outputs pages, articles and comments,
- that these are correctly identified and that titles are correct.
- """
- test_posts = list(self.posts)
- kinds = {x[8] for x in test_posts}
- self.assertEqual({'page', 'article', 'comment'}, kinds)
- page_titles = {x[0] for x in test_posts if x[8] == 'page'}
- self.assertEqual({'Test page', 'Test page 2'}, page_titles)
- article_titles = {x[0] for x in test_posts if x[8] == 'article'}
- self.assertEqual({'Black as Egypt\'s Night', 'The Steel Windpipe'},
- article_titles)
- comment_titles = {x[0] for x in test_posts if x[8] == 'comment'}
- self.assertEqual({'Mishka, always a pleasure to read your '
- 'adventures!...'},
- comment_titles)
-
- def test_recognise_status_with_correct_filename(self):
- """Check that importerer outputs only statuses 'published' and 'draft',
- that these are correctly identified and that filenames are correct.
- """
- test_posts = list(self.posts)
- statuses = {x[7] for x in test_posts}
- self.assertEqual({'published', 'draft'}, statuses)
-
- draft_filenames = {x[2] for x in test_posts if x[7] == 'draft'}
- # draft filenames are id-based
- self.assertEqual({'page-4386962582497458967',
- 'post-1276418104709695660'}, draft_filenames)
-
- published_filenames = {x[2] for x in test_posts if x[7] == 'published'}
- # published filenames are url-based, except comments
- self.assertEqual({'the-steel-windpipe',
- 'test-page',
- 'post-5590533389087749201'}, published_filenames)
-
-
-@skipIfNoExecutable(['pandoc', '--version'])
-@unittest.skipUnless(BeautifulSoup, 'Needs BeautifulSoup module')
-class TestWordpressXmlImporter(unittest.TestCase):
-
- def setUp(self):
- self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, 'C')
- self.posts = wp2fields(WORDPRESS_XML_SAMPLE)
- self.custposts = wp2fields(WORDPRESS_XML_SAMPLE, True)
-
- def tearDown(self):
- locale.setlocale(locale.LC_ALL, self.old_locale)
-
- def test_ignore_empty_posts(self):
- self.assertTrue(self.posts)
- for (title, content, fname, date, author,
- categ, tags, status, kind, format) in self.posts:
- self.assertTrue(title.strip())
-
- def test_recognise_page_kind(self):
- """ Check that we recognise pages in wordpress, as opposed to posts """
- self.assertTrue(self.posts)
- # Collect (title, filename, kind) of non-empty posts recognised as page
- pages_data = []
- for (title, content, fname, date, author,
- categ, tags, status, kind, format) in self.posts:
- if kind == 'page':
- pages_data.append((title, fname))
- self.assertEqual(2, len(pages_data))
- self.assertEqual(('Page', 'contact'), pages_data[0])
- self.assertEqual(('Empty Page', 'empty'), pages_data[1])
-
- def test_dirpage_directive_for_page_kind(self):
- silent_f2p = mute(True)(fields2pelican)
- test_post = filter(lambda p: p[0].startswith("Empty Page"), self.posts)
- with temporary_folder() as temp:
- fname = list(silent_f2p(test_post, 'markdown',
- temp, dirpage=True))[0]
- self.assertTrue(fname.endswith('pages%sempty.md' % os.path.sep))
-
- def test_dircat(self):
- silent_f2p = mute(True)(fields2pelican)
- test_posts = []
- for post in self.posts:
- # check post kind
- if len(post[5]) > 0: # Has a category
- test_posts.append(post)
- with temporary_folder() as temp:
- fnames = list(silent_f2p(test_posts, 'markdown',
- temp, dircat=True))
- subs = DEFAULT_CONFIG['SLUG_REGEX_SUBSTITUTIONS']
- index = 0
- for post in test_posts:
- name = post[2]
- category = slugify(post[5][0], regex_subs=subs, preserve_case=True)
- name += '.md'
- filename = os.path.join(category, name)
- out_name = fnames[index]
- self.assertTrue(out_name.endswith(filename))
- index += 1
-
- def test_unless_custom_post_all_items_should_be_pages_or_posts(self):
- self.assertTrue(self.posts)
- pages_data = []
- for (title, content, fname, date, author, categ,
- tags, status, kind, format) in self.posts:
- if kind == 'page' or kind == 'article':
- pass
- else:
- pages_data.append((title, fname))
- self.assertEqual(0, len(pages_data))
-
- def test_recognise_custom_post_type(self):
- self.assertTrue(self.custposts)
- cust_data = []
- for (title, content, fname, date, author, categ,
- tags, status, kind, format) in self.custposts:
- if kind == 'article' or kind == 'page':
- pass
- else:
- cust_data.append((title, kind))
- self.assertEqual(3, len(cust_data))
- self.assertEqual(
- ('A custom post in category 4', 'custom1'),
- cust_data[0])
- self.assertEqual(
- ('A custom post in category 5', 'custom1'),
- cust_data[1])
- self.assertEqual(
- ('A 2nd custom post type also in category 5', 'custom2'),
- cust_data[2])
-
- def test_custom_posts_put_in_own_dir(self):
- silent_f2p = mute(True)(fields2pelican)
- test_posts = []
- for post in self.custposts:
- # check post kind
- if post[8] == 'article' or post[8] == 'page':
- pass
- else:
- test_posts.append(post)
- with temporary_folder() as temp:
- fnames = list(silent_f2p(test_posts, 'markdown',
- temp, wp_custpost=True))
- index = 0
- for post in test_posts:
- name = post[2]
- kind = post[8]
- name += '.md'
- filename = os.path.join(kind, name)
- out_name = fnames[index]
- self.assertTrue(out_name.endswith(filename))
- index += 1
-
- def test_custom_posts_put_in_own_dir_and_catagory_sub_dir(self):
- silent_f2p = mute(True)(fields2pelican)
- test_posts = []
- for post in self.custposts:
- # check post kind
- if post[8] == 'article' or post[8] == 'page':
- pass
- else:
- test_posts.append(post)
- with temporary_folder() as temp:
- fnames = list(silent_f2p(test_posts, 'markdown', temp,
- wp_custpost=True, dircat=True))
- subs = DEFAULT_CONFIG['SLUG_REGEX_SUBSTITUTIONS']
- index = 0
- for post in test_posts:
- name = post[2]
- kind = post[8]
- category = slugify(post[5][0], regex_subs=subs, preserve_case=True)
- name += '.md'
- filename = os.path.join(kind, category, name)
- out_name = fnames[index]
- self.assertTrue(out_name.endswith(filename))
- index += 1
-
- def test_wp_custpost_true_dirpage_false(self):
- # pages should only be put in their own directory when dirpage = True
- silent_f2p = mute(True)(fields2pelican)
- test_posts = []
- for post in self.custposts:
- # check post kind
- if post[8] == 'page':
- test_posts.append(post)
- with temporary_folder() as temp:
- fnames = list(silent_f2p(test_posts, 'markdown', temp,
- wp_custpost=True, dirpage=False))
- index = 0
- for post in test_posts:
- name = post[2]
- name += '.md'
- filename = os.path.join('pages', name)
- out_name = fnames[index]
- self.assertFalse(out_name.endswith(filename))
-
- def test_can_toggle_raw_html_code_parsing(self):
- test_posts = list(self.posts)
-
- def r(f):
- with open(f, encoding='utf-8') as infile:
- return infile.read()
- silent_f2p = mute(True)(fields2pelican)
-
- with temporary_folder() as temp:
-
- rst_files = (r(f) for f
- in silent_f2p(test_posts, 'markdown', temp))
- self.assertTrue(any('
Comments !
- - - -