Skip to content

Commit

Permalink
Fixes #6
Browse files Browse the repository at this point in the history
With tests.
  • Loading branch information
jMyles committed Oct 7, 2012
1 parent c120fe7 commit 02eead8
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 26 deletions.
14 changes: 9 additions & 5 deletions coldbrew/__init__.py
@@ -1,8 +1,12 @@
from coldbrew.exceptions import ColdBrewCompileError
from coldbrew.cache import get_cache_key, get_hexdigest, get_hashed_mtime
import subprocess
import shlex
from django.conf import settings
import logging
import os
import shlex
import subprocess

logger = logging.getLogger("coffeescript")

def get_string_from_path(source_file_path):
source_file = open(source_file_path)
Expand All @@ -25,9 +29,9 @@ def compile(coffeescript_string):
logger.error(errors)

if settings.COLDBREW_FAIL_LOUD:
raise ColdBrewCompileError('Compiling %s \n\n %s' % (full_path, errors))
return False, errors
else:
return errors
return True, errors

if out:
return out.decode("utf-8")
return True, out.decode("utf-8")
5 changes: 4 additions & 1 deletion coldbrew/exceptions.py
@@ -1,2 +1,5 @@
class ColdBrewCompileError(SyntaxError):
pass
def __init__(self, location, error):
self.coffee_error_location = location
self.error = error
super(ColdBrewCompileError, self).__init__('Compiling %s \n\n %s' % (location, error))
28 changes: 19 additions & 9 deletions coldbrew/templatetags/coldbrew.py
@@ -1,23 +1,28 @@
from ..cache import get_cache_key, get_hexdigest, get_hashed_mtime
from ..exceptions import ColdBrewCompileError
from .. import compile, get_string_from_path
from ..exceptions import ColdBrewCompileError
from django.conf import settings
from django.core.cache import cache
from django.template.base import Library, Node
import logging
import os


import os

logger = logging.getLogger("coffeescript")
register = Library()


class InlineCoffeescriptNode(Node):

def __init__(self, nodelist):
self.nodelist = nodelist


def compile(self, source):
quiet, compile_result = compile(source)

if not quiet:
raise ColdBrewCompileError("Inline", compile_result)
else:
return compile_result

def render(self, context):
output = self.nodelist.render(context)

Expand All @@ -26,7 +31,7 @@ def render(self, context):
cached = cache.get(cache_key, None)
if cached is not None:
return cached
output = compile(output)
output = self.compile(output)
cache.set(cache_key, output, settings.COFFEESCRIPT_CACHE_TIMEOUT)
return output
else:
Expand Down Expand Up @@ -62,12 +67,17 @@ def coffeescript(source_file_path):


coffeescript_string = get_string_from_path(full_path)
compiled_javascript = compile(coffeescript_string)


quiet, compile_result = compile(coffeescript_string)

if not quiet:
raise ColdBrewCompileError(full_path, compile_result)

if not os.path.exists(output_directory):
os.makedirs(output_directory)
compiled_file = open(output_path, "w+")
compiled_file.write(compiled_javascript)
compiled_file.write(compile_result)
compiled_file.close()

# Remove old files
Expand Down
20 changes: 20 additions & 0 deletions coldbrew/tests/__init__.py
@@ -0,0 +1,20 @@
import logging

class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""

def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)

def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())

def reset(self):
self.messages = {
'debug': [],
'info': [],
'warning': [],
'error': [],
'critical': [],
}
2 changes: 2 additions & 0 deletions coldbrew/tests/media/bad_template.html
@@ -0,0 +1,2 @@
{% load coldbrew %}
{% coffeescript "scripts/test-error.coffee" %}
10 changes: 10 additions & 0 deletions coldbrew/tests/media/bad_template_inline.html
@@ -0,0 +1,10 @@
{% load coldbrew %}


{% inlinecoffeescript %}

console.log "Hello, World"
world = "hello"
mojo = "bad"

{% endinlinecoffeescript %}
2 changes: 2 additions & 0 deletions coldbrew/tests/media/scripts/test-error.coffee
@@ -0,0 +1,2 @@
world = "hello"
mojo = "bad" # Bad indentation
14 changes: 12 additions & 2 deletions coldbrew/tests/test_settings.py
Expand Up @@ -3,6 +3,7 @@
import sys



STATIC_ROOT = MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
COFFEESCRIPT_LOCATION = STATIC_ROOT

Expand All @@ -18,14 +19,15 @@
'NAME':'notreal',
}
}



LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'class':'coldbrew.tests.MockLoggingHandler',
},
},
'loggers': {
Expand All @@ -36,4 +38,12 @@
}
}

TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
)

TEMPLATE_DIRS = (
STATIC_ROOT
)

from coldbrew.settings import *
56 changes: 47 additions & 9 deletions coldbrew/tests/tests.py
@@ -1,17 +1,21 @@
from django.test import TestCase

from django.test.utils import override_settings

from django.conf import settings
from django.template import loader
from django.template.base import Template
from django.template.context import RequestContext
from django.conf import settings

from django.test import TestCase
from django.test.utils import override_settings
from coldbrew.exceptions import ColdBrewCompileError
from io import StringIO
import os
import re
import time
import shutil

import sys
import time

import logging

logger = logging.getLogger("coffeescript")


class CoffeeScriptTestCase(TestCase):

Expand Down Expand Up @@ -103,4 +107,38 @@ def test_compiled_file_already_exists_file_is_not_written_again(self):
self.assertEqual(third_access, second_access)

# ...and finally delete the file now that the test is over.
os.remove("%s/%s" % (settings.STATIC_ROOT, compiled_filename_yet_again))
os.remove("%s/%s" % (settings.STATIC_ROOT, compiled_filename_yet_again))

def test_error_quiet(self):
# Start by clearing the error message list.
logger.handlers[0].messages['error'] = []

template = Template("""
{% load coldbrew %}
{% coffeescript "scripts/test-error.coffee" %}
""")
template.render(RequestContext({})).strip()

# Now we got an error from the rendering.
errors = logger.handlers[0].messages['error']
self.assertTrue("Unexpected 'INDENT'" in errors[0])

@override_settings(COLDBREW_FAIL_LOUD=True)
def test_error_loud(self):
# Start by clearing the error message list.
logger.handlers[0].messages['error'] = []

template = loader.get_template('bad_template.html')
self.assertRaises(ColdBrewCompileError, template.render, RequestContext({}))

# Now we got an error from the rendering.
errors = logger.handlers[0].messages['error']
self.assertTrue("Unexpected 'INDENT'" in errors[0])

@override_settings(COLDBREW_FAIL_LOUD=True)
def test_error_loud_inline(self):
# Start by clearing the error message list.
logger.handlers[0].messages['error'] = []

template = loader.get_template('bad_template_inline.html')
self.assertRaises(ColdBrewCompileError, template.render, RequestContext({}))

0 comments on commit 02eead8

Please sign in to comment.