flake8-ed the tests

This commit is contained in:
Alexis Métaireau 2013-03-03 19:44:57 -08:00
commit 20662c2a43
10 changed files with 158 additions and 146 deletions

View file

@ -1,9 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function from __future__ import unicode_literals, print_function
__all__ = [ __all__ = ['get_article', 'unittest', ]
'get_article',
'unittest',
]
import os import os
import re import re
@ -44,14 +41,14 @@ def temporary_folder():
def isplit(s, sep=None): def isplit(s, sep=None):
""" """Behaves like str.split but returns a generator instead of a list.
Behave like str.split but returns a generator instead of a list.
>>> list(isplit('\tUse the force\n')) == '\tUse the force\n'.split() >>> list(isplit('\tUse the force\n')) == '\tUse the force\n'.split()
True True
>>> list(isplit('\tUse the force\n')) == ['Use', 'the', 'force'] >>> list(isplit('\tUse the force\n')) == ['Use', 'the', 'force']
True True
>>> list(isplit('\tUse the force\n', "e")) == '\tUse the force\n'.split("e") >>> (list(isplit('\tUse the force\n', "e"))
== '\tUse the force\n'.split("e"))
True True
>>> list(isplit('Use the force', "e")) == 'Use the force'.split("e") >>> list(isplit('Use the force', "e")) == 'Use the force'.split("e")
True True
@ -76,8 +73,7 @@ def isplit(s, sep=None):
def mute(returns_output=False): def mute(returns_output=False):
""" """Decorate a function that prints to stdout, intercepting the output.
Decorate a function that prints to stdout, intercepting the output.
If "returns_output" is True, the function will return a generator If "returns_output" is True, the function will return a generator
yielding the printed lines instead of the return values. yielding the printed lines instead of the return values.
@ -164,9 +160,7 @@ def get_settings():
class LogCountHandler(BufferingHandler): class LogCountHandler(BufferingHandler):
""" """Capturing and counting logged messages."""
Capturing and counting logged messages.
"""
def __init__(self, capacity=1000): def __init__(self, capacity=1000):
logging.handlers.BufferingHandler.__init__(self, capacity) logging.handlers.BufferingHandler.__init__(self, capacity)
@ -179,8 +173,7 @@ class LogCountHandler(BufferingHandler):
class LoggedTestCase(unittest.TestCase): class LoggedTestCase(unittest.TestCase):
"""A test case that captures log messages """A test case that captures log messages."""
"""
def setUp(self): def setUp(self):
super(LoggedTestCase, self).setUp() super(LoggedTestCase, self).setUp()

View file

@ -1,6 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals from __future__ import unicode_literals
from datetime import datetime
from sys import platform
from .support import unittest from .support import unittest
from pelican.contents import Page, Article, URLWrapper from pelican.contents import Page, Article, URLWrapper
@ -31,10 +34,8 @@ class TestPage(unittest.TestCase):
} }
def test_use_args(self): def test_use_args(self):
"""Creating a page with arguments passed to the constructor should use # Creating a page with arguments passed to the constructor should use
them to initialise object's attributes. # them to initialise object's attributes.
"""
metadata = {'foo': 'bar', 'foobar': 'baz', 'title': 'foobar', } metadata = {'foo': 'bar', 'foobar': 'baz', 'title': 'foobar', }
page = Page(TEST_CONTENT, metadata=metadata, page = Page(TEST_CONTENT, metadata=metadata,
context={'localsiteurl': ''}) context={'localsiteurl': ''})
@ -44,22 +45,22 @@ class TestPage(unittest.TestCase):
self.assertEqual(page.content, TEST_CONTENT) self.assertEqual(page.content, TEST_CONTENT)
def test_mandatory_properties(self): def test_mandatory_properties(self):
"""If the title is not set, must throw an exception.""" # If the title is not set, must throw an exception.
page = Page('content') page = Page('content')
with self.assertRaises(NameError) as cm: with self.assertRaises(NameError):
page.check_properties() page.check_properties()
page = Page('content', metadata={'title': 'foobar'}) page = Page('content', metadata={'title': 'foobar'})
page.check_properties() page.check_properties()
def test_summary_from_metadata(self): def test_summary_from_metadata(self):
"""If a :summary: metadata is given, it should be used.""" # If a :summary: metadata is given, it should be used
page = Page(**self.page_kwargs) page = Page(**self.page_kwargs)
self.assertEqual(page.summary, TEST_SUMMARY) self.assertEqual(page.summary, TEST_SUMMARY)
def test_summary_max_length(self): def test_summary_max_length(self):
"""If a :SUMMARY_MAX_LENGTH: is set, and there is no other summary, generated summary # If a :SUMMARY_MAX_LENGTH: is set, and there is no other summary,
should not exceed the given length.""" # generated summary should not exceed the given length.
page_kwargs = self._copy_page_kwargs() page_kwargs = self._copy_page_kwargs()
settings = _DEFAULT_CONFIG.copy() settings = _DEFAULT_CONFIG.copy()
page_kwargs['settings'] = settings page_kwargs['settings'] = settings
@ -72,12 +73,12 @@ class TestPage(unittest.TestCase):
self.assertEqual(page.summary, truncate_html_words(TEST_CONTENT, 10)) self.assertEqual(page.summary, truncate_html_words(TEST_CONTENT, 10))
def test_slug(self): def test_slug(self):
"""If a title is given, it should be used to generate the slug.""" # If a title is given, it should be used to generate the slug.
page = Page(**self.page_kwargs) page = Page(**self.page_kwargs)
self.assertEqual(page.slug, 'foo-bar') self.assertEqual(page.slug, 'foo-bar')
def test_defaultlang(self): def test_defaultlang(self):
"""If no lang is given, default to the default one.""" # If no lang is given, default to the default one.
page = Page(**self.page_kwargs) page = Page(**self.page_kwargs)
self.assertEqual(page.lang, _DEFAULT_CONFIG['DEFAULT_LANG']) self.assertEqual(page.lang, _DEFAULT_CONFIG['DEFAULT_LANG'])
@ -87,10 +88,9 @@ class TestPage(unittest.TestCase):
self.assertEqual(page.lang, 'fr') self.assertEqual(page.lang, 'fr')
def test_save_as(self): def test_save_as(self):
"""If a lang is not the default lang, save_as should be set # If a lang is not the default lang, save_as should be set
accordingly. # accordingly.
"""
# if a title is defined, save_as should be set # if a title is defined, save_as should be set
page = Page(**self.page_kwargs) page = Page(**self.page_kwargs)
self.assertEqual(page.save_as, "pages/foo-bar.html") self.assertEqual(page.save_as, "pages/foo-bar.html")
@ -101,8 +101,7 @@ class TestPage(unittest.TestCase):
self.assertEqual(page.save_as, "pages/foo-bar-fr.html") self.assertEqual(page.save_as, "pages/foo-bar-fr.html")
def test_metadata_url_format(self): def test_metadata_url_format(self):
"""Arbitrary metadata should be passed through url_format() # Arbitrary metadata should be passed through url_format()
"""
page = Page(**self.page_kwargs) page = Page(**self.page_kwargs)
self.assertIn('summary', page.url_format.keys()) self.assertIn('summary', page.url_format.keys())
page.metadata['directory'] = 'test-dir' page.metadata['directory'] = 'test-dir'
@ -111,10 +110,7 @@ class TestPage(unittest.TestCase):
self.assertEqual(page.save_as, 'test-dir/foo-bar') self.assertEqual(page.save_as, 'test-dir/foo-bar')
def test_datetime(self): def test_datetime(self):
"""If DATETIME is set to a tuple, it should be used to override LOCALE # If DATETIME is set to a tuple, it should be used to override LOCALE
"""
from datetime import datetime
from sys import platform
dt = datetime(2015, 9, 13) dt = datetime(2015, 9, 13)
page_kwargs = self._copy_page_kwargs() page_kwargs = self._copy_page_kwargs()
@ -126,7 +122,6 @@ class TestPage(unittest.TestCase):
self.assertEqual(page.locale_date, self.assertEqual(page.locale_date,
dt.strftime(_DEFAULT_CONFIG['DEFAULT_DATE_FORMAT'])) dt.strftime(_DEFAULT_CONFIG['DEFAULT_DATE_FORMAT']))
page_kwargs['settings'] = dict([(x, _DEFAULT_CONFIG[x]) for x in page_kwargs['settings'] = dict([(x, _DEFAULT_CONFIG[x]) for x in
_DEFAULT_CONFIG]) _DEFAULT_CONFIG])
@ -154,9 +149,7 @@ class TestPage(unittest.TestCase):
unittest.skip("There is no locale %s in this system." % locale) unittest.skip("There is no locale %s in this system." % locale)
def test_template(self): def test_template(self):
""" # Pages default to page, metadata overwrites
Pages default to page, metadata overwrites
"""
default_page = Page(**self.page_kwargs) default_page = Page(**self.page_kwargs)
self.assertEqual('page', default_page.template) self.assertEqual('page', default_page.template)
page_kwargs = self._copy_page_kwargs() page_kwargs = self._copy_page_kwargs()
@ -177,21 +170,19 @@ class TestPage(unittest.TestCase):
return page_kwargs return page_kwargs
def test_signal(self): def test_signal(self):
"""If a title is given, it should be used to generate the slug.""" # If a title is given, it should be used to generate the slug.
def receiver_test_function(sender, instance): def receiver_test_function(sender, instance):
pass pass
content_object_init.connect(receiver_test_function, sender=Page) content_object_init.connect(receiver_test_function, sender=Page)
page = Page(**self.page_kwargs) Page(**self.page_kwargs)
self.assertTrue(content_object_init.has_receivers_for(Page)) self.assertTrue(content_object_init.has_receivers_for(Page))
class TestArticle(TestPage): class TestArticle(TestPage):
def test_template(self): def test_template(self):
""" # Articles default to article, metadata overwrites
Articles default to article, metadata overwrites
"""
default_article = Article(**self.page_kwargs) default_article = Article(**self.page_kwargs)
self.assertEqual('article', default_article.template) self.assertEqual('article', default_article.template)
article_kwargs = self._copy_page_kwargs() article_kwargs = self._copy_page_kwargs()
@ -202,8 +193,7 @@ class TestArticle(TestPage):
class TestURLWrapper(unittest.TestCase): class TestURLWrapper(unittest.TestCase):
def test_comparisons(self): def test_comparisons(self):
"""URLWrappers are sorted by name # URLWrappers are sorted by name
"""
wrapper_a = URLWrapper(name='first', settings={}) wrapper_a = URLWrapper(name='first', settings={})
wrapper_b = URLWrapper(name='last', settings={}) wrapper_b = URLWrapper(name='last', settings={})
self.assertFalse(wrapper_a > wrapper_b) self.assertFalse(wrapper_a > wrapper_b)

View file

@ -58,7 +58,8 @@ class TestArticlesGenerator(unittest.TestCase):
settings['THEME'], None, settings['MARKUP']) settings['THEME'], None, settings['MARKUP'])
writer = MagicMock() writer = MagicMock()
generator.generate_feeds(writer) generator.generate_feeds(writer)
writer.write_feed.assert_called_with([], settings, 'feeds/all.atom.xml') writer.write_feed.assert_called_with([], settings,
'feeds/all.atom.xml')
generator = ArticlesGenerator(settings, {'FEED_ALL_ATOM': None}, None, generator = ArticlesGenerator(settings, {'FEED_ALL_ATOM': None}, None,
settings['THEME'], None, None) settings['THEME'], None, None)
@ -72,16 +73,21 @@ class TestArticlesGenerator(unittest.TestCase):
articles = self.distill_articles(generator.articles) articles = self.distill_articles(generator.articles)
articles_expected = [ articles_expected = [
['Article title', 'published', 'Default', 'article'], ['Article title', 'published', 'Default', 'article'],
['Article with markdown and summary metadata single', 'published', 'Default', 'article'], ['Article with markdown and summary metadata single', 'published',
['Article with markdown and summary metadata multi', 'published', 'Default', 'article'], 'Default', 'article'],
['Article with markdown and summary metadata multi', 'published',
'Default', 'article'],
['Article with template', 'published', 'Default', 'custom'], ['Article with template', 'published', 'Default', 'custom'],
['Test md File', 'published', 'test', 'article'], ['Test md File', 'published', 'test', 'article'],
['Rst with filename metadata', 'published', 'yeah', 'article'], ['Rst with filename metadata', 'published', 'yeah', 'article'],
['Test Markdown extensions', 'published', 'Default', 'article'], ['Test Markdown extensions', 'published', 'Default', 'article'],
['This is a super article !', 'published', 'Yeah', 'article'], ['This is a super article !', 'published', 'Yeah', 'article'],
['This is an article with category !', 'published', 'yeah', 'article'], ['This is an article with category !', 'published', 'yeah',
['This is an article without category !', 'published', 'Default', 'article'], 'article'],
['This is an article without category !', 'published', 'TestCategory', 'article'], ['This is an article without category !', 'published', 'Default',
'article'],
['This is an article without category !', 'published',
'TestCategory', 'article'],
['This is a super article !', 'published', 'yeah', 'article'] ['This is a super article !', 'published', 'yeah', 'article']
] ]
self.assertItemsEqual(articles_expected, articles) self.assertItemsEqual(articles_expected, articles)
@ -90,7 +96,8 @@ class TestArticlesGenerator(unittest.TestCase):
generator = self.get_populated_generator() generator = self.get_populated_generator()
categories = [cat.name for cat, _ in generator.categories] categories = [cat.name for cat, _ in generator.categories]
categories_expected = ['Default', 'TestCategory', 'Yeah', 'test', 'yeah'] categories_expected = ['Default', 'TestCategory', 'Yeah', 'test',
'yeah']
self.assertEquals(categories, categories_expected) self.assertEquals(categories, categories_expected)
def test_do_not_use_folder_as_category(self): def test_do_not_use_folder_as_category(self):
@ -153,18 +160,19 @@ class TestArticlesGenerator(unittest.TestCase):
""" """
generator = self.get_populated_generator() generator = self.get_populated_generator()
articles = self.distill_articles(generator.articles) articles = self.distill_articles(generator.articles)
custom_template = ['Article with template', 'published', 'Default', 'custom'] custom_template = ['Article with template', 'published', 'Default',
standard_template = ['This is a super article !', 'published', 'Yeah', 'article'] 'custom']
standard_template = ['This is a super article !', 'published', 'Yeah',
'article']
self.assertIn(custom_template, articles) self.assertIn(custom_template, articles)
self.assertIn(standard_template, articles) self.assertIn(standard_template, articles)
class TestPageGenerator(unittest.TestCase): class TestPageGenerator(unittest.TestCase):
""" # Note: Every time you want to test for a new field; Make sure the test
Every time you want to test for a new field; # pages in "TestPages" have all the fields Add it to distilled in
Make sure the test pages in "TestPages" have all the fields # distill_pages Then update the assertItemsEqual in test_generate_context
Add it to distilled in distill_pages # to match expected
Then update the assertItemsEqual in test_generate_context to match expected
"""
def distill_pages(self, pages): def distill_pages(self, pages):
distilled = [] distilled = []
@ -192,12 +200,14 @@ class TestPageGenerator(unittest.TestCase):
pages_expected = [ pages_expected = [
['This is a test page', 'published', 'page'], ['This is a test page', 'published', 'page'],
['This is a markdown test page', 'published', 'page'], ['This is a markdown test page', 'published', 'page'],
['This is a test page with a preset template', 'published', 'custom'] ['This is a test page with a preset template', 'published',
'custom']
] ]
hidden_pages_expected = [ hidden_pages_expected = [
['This is a test hidden page', 'hidden', 'page'], ['This is a test hidden page', 'hidden', 'page'],
['This is a markdown 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'] ['This is a test hidden page with a custom template', 'hidden',
'custom']
] ]
self.assertItemsEqual(pages_expected, pages) self.assertItemsEqual(pages_expected, pages)

View file

@ -56,5 +56,6 @@ class TestWordpressXmlImporter(unittest.TestCase):
post = test_posts[0] post = test_posts[0]
title = post[0] title = post[0]
self.assertTrue(title, "A normal post with some <html> entities in the title. You can't miss them.") self.assertTrue(title, "A normal post with some <html> entities in the"
" title. You can't miss them.")
self.assertTrue('&' not in title) self.assertTrue('&' not in title)

View file

@ -10,11 +10,11 @@ from pelican.plugins import gzip_cache
from .test_contents import TEST_CONTENT, TEST_SUMMARY from .test_contents import TEST_CONTENT, TEST_SUMMARY
from .support import unittest, temporary_folder from .support import unittest, temporary_folder
class TestGzipCache(unittest.TestCase): class TestGzipCache(unittest.TestCase):
'''Unit tests for the gzip cache plugin'''
def test_should_compress(self): def test_should_compress(self):
'''Test that some filetypes should compress and others shouldn't.''' # Some filetypes should compress and others shouldn't.
self.assertTrue(gzip_cache.should_compress('foo.html')) self.assertTrue(gzip_cache.should_compress('foo.html'))
self.assertTrue(gzip_cache.should_compress('bar.css')) self.assertTrue(gzip_cache.should_compress('bar.css'))
self.assertTrue(gzip_cache.should_compress('baz.js')) self.assertTrue(gzip_cache.should_compress('baz.js'))
@ -26,16 +26,17 @@ class TestGzipCache(unittest.TestCase):
self.assertFalse(gzip_cache.should_compress('foo.mov')) self.assertFalse(gzip_cache.should_compress('foo.mov'))
def test_creates_gzip_file(self): def test_creates_gzip_file(self):
'''Test that a file matching the input filename with a .gz extension is # A file matching the input filename with a .gz extension is created.
created.'''
# The plugin walks over the output content after the finalized signal # The plugin walks over the output content after the finalized signal
# so it is safe to assume that the file exists (otherwise walk would # so it is safe to assume that the file exists (otherwise walk would
# not report it). Therefore, create a dummy file to use. # not report it). Therefore, create a dummy file to use.
with temporary_folder() as tempdir: with temporary_folder() as tempdir:
(_, a_html_filename) = tempfile.mkstemp(suffix='.html', dir=tempdir) _, a_html_filename = tempfile.mkstemp(suffix='.html', dir=tempdir)
gzip_cache.create_gzip_file(a_html_filename) gzip_cache.create_gzip_file(a_html_filename)
self.assertTrue(os.path.exists(a_html_filename + '.gz')) self.assertTrue(os.path.exists(a_html_filename + '.gz'))
class TestSummary(unittest.TestCase): class TestSummary(unittest.TestCase):
def setUp(self): def setUp(self):
super(TestSummary, self).setUp() super(TestSummary, self).setUp()

View file

@ -24,8 +24,8 @@ class RstReaderTest(unittest.TestCase):
'category': 'yeah', 'category': 'yeah',
'author': 'Alexis Métaireau', 'author': 'Alexis Métaireau',
'title': 'This is a super article !', 'title': 'This is a super article !',
'summary': '<p class="first last">Multi-line metadata should be'\ 'summary': '<p class="first last">Multi-line metadata should be'
' supported\nas well as <strong>inline'\ ' supported\nas well as <strong>inline'
' markup</strong>.</p>\n', ' markup</strong>.</p>\n',
'date': datetime.datetime(2010, 12, 2, 10, 14), 'date': datetime.datetime(2010, 12, 2, 10, 14),
'tags': ['foo', 'bar', 'foobar'], 'tags': ['foo', 'bar', 'foobar'],
@ -64,8 +64,8 @@ class RstReaderTest(unittest.TestCase):
content, metadata = readers.read_file( content, metadata = readers.read_file(
_path('2012-11-29_rst_w_filename_meta#foo-bar.rst'), _path('2012-11-29_rst_w_filename_meta#foo-bar.rst'),
settings={ settings={
'FILENAME_METADATA': '(?P<date>\d{4}-\d{2}-\d{2})_' \ 'FILENAME_METADATA': '(?P<date>\d{4}-\d{2}-\d{2})_'
'_(?P<Slug>.*)' \ '_(?P<Slug>.*)'
'#(?P<MyMeta>.*)-(?P<author>.*)' '#(?P<MyMeta>.*)-(?P<author>.*)'
}) })
expected = { expected = {
@ -82,19 +82,21 @@ class RstReaderTest(unittest.TestCase):
def test_article_metadata_key_lowercase(self): def test_article_metadata_key_lowercase(self):
"""Keys of metadata should be lowercase.""" """Keys of metadata should be lowercase."""
reader = readers.RstReader({}) reader = readers.RstReader({})
content, metadata = reader.read(_path('article_with_uppercase_metadata.rst')) content, metadata = reader.read(
_path('article_with_uppercase_metadata.rst'))
self.assertIn('category', metadata, "Key should be lowercase.") self.assertIn('category', metadata, 'Key should be lowercase.')
self.assertEquals('Yeah', metadata.get('category'), "Value keeps cases.") self.assertEquals('Yeah', metadata.get('category'),
'Value keeps case.')
def test_typogrify(self): def test_typogrify(self):
# if nothing is specified in the settings, the content should be # if nothing is specified in the settings, the content should be
# unmodified # unmodified
content, _ = readers.read_file(_path('article.rst')) content, _ = readers.read_file(_path('article.rst'))
expected = "<p>This is some content. With some stuff to "\ expected = ('<p>This is some content. With some stuff to '
"&quot;typogrify&quot;.</p>\n<p>Now with added "\ '&quot;typogrify&quot;.</p>\n<p>Now with added '
'support for <abbr title="three letter acronym">'\ 'support for <abbr title="three letter acronym">'
'TLA</abbr>.</p>\n' 'TLA</abbr>.</p>\n')
self.assertEqual(content, expected) self.assertEqual(content, expected)
@ -102,10 +104,10 @@ class RstReaderTest(unittest.TestCase):
# otherwise, typogrify should be applied # otherwise, typogrify should be applied
content, _ = readers.read_file(_path('article.rst'), content, _ = readers.read_file(_path('article.rst'),
settings={'TYPOGRIFY': True}) settings={'TYPOGRIFY': True})
expected = "<p>This is some content. With some stuff to&nbsp;"\ expected = ('<p>This is some content. With some stuff to&nbsp;'
"&#8220;typogrify&#8221;.</p>\n<p>Now with added "\ '&#8220;typogrify&#8221;.</p>\n<p>Now with added '
'support for <abbr title="three letter acronym">'\ 'support for <abbr title="three letter acronym">'
'<span class="caps">TLA</span></abbr>.</p>\n' '<span class="caps">TLA</span></abbr>.</p>\n')
self.assertEqual(content, expected) self.assertEqual(content, expected)
except ImportError: except ImportError:
@ -159,7 +161,8 @@ class MdReaderTest(unittest.TestCase):
@unittest.skipUnless(readers.Markdown, "markdown isn't installed") @unittest.skipUnless(readers.Markdown, "markdown isn't installed")
def test_article_with_markdown_markup_extension(self): def test_article_with_markdown_markup_extension(self):
# test to ensure the markdown markup extension is being processed as expected # test to ensure the markdown markup extension is being processed as
# expected
content, metadata = readers.read_file( content, metadata = readers.read_file(
_path('article_with_markdown_markup_extensions.md'), _path('article_with_markdown_markup_extensions.md'),
settings={'MD_EXTENSIONS': ['toc', 'codehilite', 'extra']}) settings={'MD_EXTENSIONS': ['toc', 'codehilite', 'extra']})
@ -218,15 +221,19 @@ class MdReaderTest(unittest.TestCase):
for key, value in expected.items(): for key, value in expected.items():
self.assertEquals(value, metadata[key], key) self.assertEquals(value, metadata[key], key)
class AdReaderTest(unittest.TestCase): class AdReaderTest(unittest.TestCase):
@unittest.skipUnless(readers.asciidoc, "asciidoc isn't installed") @unittest.skipUnless(readers.asciidoc, "asciidoc isn't installed")
def test_article_with_asc_extension(self): def test_article_with_asc_extension(self):
# test to ensure the asc extension is being processed by the correct reader # Ensure the asc extension is being processed by the correct reader
reader = readers.AsciiDocReader({}) reader = readers.AsciiDocReader({})
content, metadata = reader.read(_path('article_with_asc_extension.asc')) content, metadata = reader.read(
expected = '<hr>\n<h2><a name="_used_for_pelican_test"></a>Used for pelican test</h2>\n'\ _path('article_with_asc_extension.asc'))
'<p>The quick brown fox jumped over the lazy dog&#8217;s back.</p>\n' expected = ('<hr>\n<h2><a name="_used_for_pelican_test">'
'</a>Used for pelican test</h2>\n'
'<p>The quick brown fox jumped over'
' the lazy dog&#8217;s back.</p>\n')
self.assertEqual(content, expected) self.assertEqual(content, expected)
expected = { expected = {
'category': 'Blog', 'category': 'Blog',
@ -239,7 +246,6 @@ class AdReaderTest(unittest.TestCase):
for key, value in expected.items(): for key, value in expected.items():
self.assertEquals(value, metadata[key], key) self.assertEquals(value, metadata[key], key)
expected = { expected = {
'category': 'Blog', 'category': 'Blog',
'author': 'Author O. Article', 'author': 'Author O. Article',
@ -254,13 +260,16 @@ class AdReaderTest(unittest.TestCase):
@unittest.skipUnless(readers.asciidoc, "asciidoc isn't installed") @unittest.skipUnless(readers.asciidoc, "asciidoc isn't installed")
def test_article_with_asc_options(self): def test_article_with_asc_options(self):
# test to ensure the ASCIIDOC_OPTIONS is being used # test to ensure the ASCIIDOC_OPTIONS is being used
reader = readers.AsciiDocReader(dict(ASCIIDOC_OPTIONS=["-a revision=1.0.42"])) reader = readers.AsciiDocReader(
dict(ASCIIDOC_OPTIONS=["-a revision=1.0.42"]))
content, metadata = reader.read(_path('article_with_asc_options.asc')) content, metadata = reader.read(_path('article_with_asc_options.asc'))
expected = '<hr>\n<h2><a name="_used_for_pelican_test"></a>Used for pelican test</h2>\n'\ expected = ('<hr>\n<h2><a name="_used_for_pelican_test"></a>Used for'
'<p>version 1.0.42</p>\n'\ ' pelican test</h2>\n<p>version 1.0.42</p>\n'
'<p>The quick brown fox jumped over the lazy dog&#8217;s back.</p>\n' '<p>The quick brown fox jumped over the lazy'
' dog&#8217;s back.</p>\n')
self.assertEqual(content, expected) self.assertEqual(content, expected)
class HTMLReaderTest(unittest.TestCase): class HTMLReaderTest(unittest.TestCase):
def test_article_with_comments(self): def test_article_with_comments(self):
reader = readers.HTMLReader({}) reader = readers.HTMLReader({})
@ -297,10 +306,10 @@ class HTMLReaderTest(unittest.TestCase):
for key, value in expected.items(): for key, value in expected.items():
self.assertEquals(value, metadata[key], key) self.assertEquals(value, metadata[key], key)
def test_article_with_null_attributes(self): def test_article_with_null_attributes(self):
reader = readers.HTMLReader({}) reader = readers.HTMLReader({})
content, metadata = reader.read(_path('article_with_null_attributes.html')) content, metadata = reader.read(
_path('article_with_null_attributes.html'))
self.assertEquals(''' self.assertEquals('''
Ensure that empty attributes are copied properly. Ensure that empty attributes are copied properly.
@ -310,7 +319,8 @@ class HTMLReaderTest(unittest.TestCase):
def test_article_metadata_key_lowercase(self): def test_article_metadata_key_lowercase(self):
"""Keys of metadata should be lowercase.""" """Keys of metadata should be lowercase."""
reader = readers.HTMLReader({}) reader = readers.HTMLReader({})
content, metadata = reader.read(_path('article_with_uppercase_metadata.html')) content, metadata = reader.read(
self.assertIn('category', metadata, "Key should be lowercase.") _path('article_with_uppercase_metadata.html'))
self.assertEquals('Yeah', metadata.get('category'), "Value keeps cases.") self.assertIn('category', metadata, 'Key should be lowercase.')
self.assertEquals('Yeah', metadata.get('category'),
'Value keeps cases.')

View file

@ -3,7 +3,8 @@ from __future__ import unicode_literals, print_function
import copy import copy
from os.path import dirname, abspath, join from os.path import dirname, abspath, join
from pelican.settings import read_settings, configure_settings, _DEFAULT_CONFIG, DEFAULT_THEME from pelican.settings import (read_settings, configure_settings,
_DEFAULT_CONFIG, DEFAULT_THEME)
from .support import unittest from .support import unittest
@ -35,7 +36,7 @@ class TestSettingsConfiguration(unittest.TestCase):
"""providing no file should return the default values.""" """providing no file should return the default values."""
settings = read_settings(None) settings = read_settings(None)
expected = copy.deepcopy(_DEFAULT_CONFIG) expected = copy.deepcopy(_DEFAULT_CONFIG)
expected["FEED_DOMAIN"] = '' #This is added by configure settings expected['FEED_DOMAIN'] = '' # Added by configure settings
self.maxDiff = None self.maxDiff = None
self.assertDictEqual(settings, expected) self.assertDictEqual(settings, expected)

View file

@ -17,7 +17,8 @@ class TestUtils(LoggedTestCase):
@utils.deprecated_attribute( @utils.deprecated_attribute(
old='_old_attribute', new='_new_attribute', old='_old_attribute', new='_new_attribute',
since=(3, 1, 0), remove=(4, 1, 3)) since=(3, 1, 0), remove=(4, 1, 3))
def _old_attribute(): return None def _old_attribute():
return None
def test_deprecated_attribute(self): def test_deprecated_attribute(self):
value = self._old_attribute value = self._old_attribute
@ -60,8 +61,10 @@ class TestUtils(LoggedTestCase):
('this is a test', 'this-is-a-test'), ('this is a test', 'this-is-a-test'),
('this → is ← a ↑ test', 'this-is-a-test'), ('this → is ← a ↑ test', 'this-is-a-test'),
('this--is---a test', 'this-is-a-test'), ('this--is---a test', 'this-is-a-test'),
('unicode測試許功蓋你看到了嗎', 'unicodece-shi-xu-gong-gai-ni-kan-dao-liao-ma'), ('unicode測試許功蓋你看到了嗎',
('大飯原発4号機、18日夜起動へ', 'da-fan-yuan-fa-4hao-ji-18ri-ye-qi-dong-he'),) 'unicodece-shi-xu-gong-gai-ni-kan-dao-liao-ma'),
('大飯原発4号機、18日夜起動へ',
'da-fan-yuan-fa-4hao-ji-18ri-ye-qi-dong-he'),)
for value, expected in samples: for value, expected in samples:
self.assertEquals(utils.slugify(value), expected) self.assertEquals(utils.slugify(value), expected)
@ -122,7 +125,8 @@ class TestUtils(LoggedTestCase):
shutil.rmtree(empty_path, True) shutil.rmtree(empty_path, True)
def test_clean_output_dir(self): def test_clean_output_dir(self):
test_directory = os.path.join(os.path.dirname(__file__), 'clean_output') test_directory = os.path.join(os.path.dirname(__file__),
'clean_output')
content = os.path.join(os.path.dirname(__file__), 'content') content = os.path.join(os.path.dirname(__file__), 'content')
shutil.copytree(content, test_directory) shutil.copytree(content, test_directory)
utils.clean_output_dir(test_directory) utils.clean_output_dir(test_directory)
@ -131,12 +135,14 @@ class TestUtils(LoggedTestCase):
shutil.rmtree(test_directory) shutil.rmtree(test_directory)
def test_clean_output_dir_not_there(self): def test_clean_output_dir_not_there(self):
test_directory = os.path.join(os.path.dirname(__file__), 'does_not_exist') test_directory = os.path.join(os.path.dirname(__file__),
'does_not_exist')
utils.clean_output_dir(test_directory) utils.clean_output_dir(test_directory)
self.assertTrue(not os.path.exists(test_directory)) self.assertTrue(not os.path.exists(test_directory))
def test_clean_output_dir_is_file(self): def test_clean_output_dir_is_file(self):
test_directory = os.path.join(os.path.dirname(__file__), 'this_is_a_file') test_directory = os.path.join(os.path.dirname(__file__),
'this_is_a_file')
f = open(test_directory, 'w') f = open(test_directory, 'w')
f.write('') f.write('')
f.close() f.close()

View file

@ -45,8 +45,8 @@ class TestWebAssets(unittest.TestCase):
def check_link_tag(self, css_file, html_file): def check_link_tag(self, css_file, html_file):
"""Check the presence of `css_file` in `html_file`.""" """Check the presence of `css_file` in `html_file`."""
link_tag = '<link rel="stylesheet" href="{css_file}">'.\ link_tag = ('<link rel="stylesheet" href="{css_file}">'
format(css_file=css_file) .format(css_file=css_file))
html = open(html_file).read() html = open(html_file).read()
self.assertRegexpMatches(html, link_tag) self.assertRegexpMatches(html, link_tag)
@ -94,8 +94,8 @@ class TestWebAssetsAbsoluteURLS(TestWebAssets):
def test_absolute_url(self): def test_absolute_url(self):
"""Look in the output files for the link tag with absolute url.""" """Look in the output files for the link tag with absolute url."""
css_file = 'http://localhost/theme/gen/style.{0}.min.css'.\ css_file = ('http://localhost/theme/gen/style.{0}.min.css'
format(CSS_HASH) .format(CSS_HASH))
html_files = ['index.html', 'archives.html', html_files = ['index.html', 'archives.html',
'this-is-an-article-with-category.html'] 'this-is-an-article-with-category.html']
for f in html_files: for f in html_files: