Mango / tests.py

from __future__ import with_statement
import datetime
import imp
import os
import re
import unittest

import pytz

from django.conf import settings
from django.template import Context, Template

import mango
from mango.main import *
from mango.templatetags import mango_extras

document_template = Template('''{% load mango_extras %}{% ifequal meta None %}date: 29 September 2010
time: 1:30am
tags: Markdown, Django, Mango
{% else %}{% for k, v in meta %}{{ k }}: {{ v }}
{% endfor %}{% endifequal %}
{% ifequal title None %}
Introducing Mango
=================
{% else %}
{{ title|h1 }}
{% endifequal %}
{% ifequal body None %}Mango attempts to make blogging fun again.{% else %}{{ body }}{% endifequal %}
''')

def create_document(filename='test.text', context=None):
    filepath = os.path.join(mango.settings.MANGO_PATH, 'examples', filename)
    with open(filepath, 'w') as f:
        f.write(document_template.render(Context(context)))
    document = Document(filepath)
    os.remove(filepath)
    return document


class FileNameTestCase(unittest.TestCase):

    def setUp(self):
        mango.settings.UNIX_DOCUMENTS_PATH = os.path.join(mango.settings.MANGO_PATH, 'examples')

    def test_standard_separator(self):
        urls = create_document('1=test.text').urls
        self.assertEqual((urls['canon']['rel'], urls['short']['rel']), ('/test/', '/1/'))

    def test_deprecated_separator(self):
        urls = create_document('1=>test.text').urls
        self.assertEqual((urls['canon']['rel'], urls['short']['rel']), ('/test/', '/1/'))

    def test_padded_numeric_separator(self):
        self.assertEqual(create_document('01=test.text').urls['short']['rel'], '/1/')

    def test_equals_sign_in_slug(self):
        self.assertEqual(create_document('1=mangoes=tasty.text').urls['canon']['rel'], '/mangoes=tasty/')

    def test_escapement(self):
        self.assertEqual(create_document('=2+2=5.text').urls['canon']['rel'], '/2+2=5/')

    def test_no_extension(self):
        self.assertEqual(create_document('test').urls['canon']['rel'], '/test/')


class TimeZoneTestCase(unittest.TestCase):

    def setUp(self):
        settings.TIME_ZONE = 'Pacific/Auckland'

    def test_converts_to_utc(self):
        self.assertEqual(create_document().datetime.tzinfo, pytz.utc)

    def test_date(self):
        self.assertEqual(create_document().datetime.day, 28)

    def test_hour(self):
        self.assertEqual(create_document().datetime.hour, 12)

    def test_sanity(self):
        tz = pytz.timezone(settings.TIME_ZONE)
        self.assertEqual(create_document().datetime.astimezone(tz),
                tz.localize(datetime.datetime(2010, 9, 29, 1, 30)))


class MetaListsTestCase(unittest.TestCase):

    def test_in_list(self):
        mango.settings.META_LISTS = ('tags',)
        self.assertEqual(create_document().meta['tags'], [u'Markdown', u'Django', u'Mango'])

    def test_not_in_list(self):
        mango.settings.META_LISTS = ()
        self.assertEqual(create_document().meta['tags'], u'Markdown, Django, Mango')

    def test_irregular_spacing(self):
        mango.settings.META_LISTS = ('tags',)
        document = create_document(context={'meta': [('tags', ' Linux,Mac OS X , Windows ')]})
        self.assertEqual(document.meta['tags'], [u'Linux', u'Mac OS X', u'Windows'])


class TemplateFilterTestCase(unittest.TestCase):

    def test_h1(self):
        self.assertEqual(mango_extras.h1(' Mango '), 'Mango\n=====')

    def test_month_zero(self):
        self.assertEqual(mango_extras.month(0), None)

    def test_month_one(self):
        self.assertEqual(mango_extras.month(1), 'January')

    def test_month_twelve(self):
        self.assertEqual(mango_extras.month(12), 'December')


class VideoTestCase(unittest.TestCase):

    def test_youtube(self):
        document = create_document(context={'body': '[Soda Pop Stop](http://www.youtube.com/watch?v=gPbh6Ru7VVM)'})
        self.assertEqual(document.html,
                '<iframe class="youtube" type="text/html" src="http://www.youtube.com/embed/gPbh6Ru7VVM?rel=0"></iframe>\n')


# This code is taken from http://stackoverflow.com/questions/1615406/configure-django-to-find-all-doctests-in-all-modules

# Django already runs these, don't include them again
ALREADY_RUN = ['tests.py', 'models.py']

def find_untested_modules(package):
    """ Gets all modules not already included in Django's test suite """
    files = []
    for f in os.listdir(os.path.dirname(package.__file__)):
        if f.endswith('.py') and os.path.basename(f) not in ALREADY_RUN:
            files.append(re.sub(r'\.py$', '', f))
    return [imp.load_module(f, *imp.find_module(f, package.__path__)) for f in files]

def modules_callables(module):
    return [m for m in dir(module) if callable(getattr(module, m))]

def has_doctest(docstring):
    return '>>>' in docstring

__test__ = {}
for module in find_untested_modules(mango):
    for method in modules_callables(module):
        docstring = str(getattr(module, method).__doc__)
        if has_doctest(docstring):
            print 'Mango found doctest: %s.%s' % (module.__name__, method)

            # import the method itself, so doctest can find it
            _temp = __import__(module.__name__, globals(), locals(), [method])
            locals()[method] = getattr(_temp, method)

            # Django looks in __test__ for doctests to run
            __test__[method] = getattr(module, method)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.