Exemplo n.º 1
0
class PostCompressSignalTestCase(TestCase):
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        settings.COMPRESS_DEBUG_TOGGLE = 'nocompress'
        self.css = """\
<link rel="stylesheet" href="/static/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/static/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)

    def tearDown(self):
        post_compress.disconnect()

    def test_js_signal_sent(self):
        def listener(sender, **kwargs):
            pass
        callback = Mock(wraps=listener)
        post_compress.connect(callback)
        self.js_node.output()
        args, kwargs = callback.call_args
        self.assertEquals(JsCompressor, kwargs['sender'])
        self.assertEquals('js', kwargs['type'])
        self.assertEquals('file', kwargs['mode'])
        context = kwargs['context']
        assert 'url' in context['compressed']

    def test_css_signal_sent(self):
        def listener(sender, **kwargs):
            pass
        callback = Mock(wraps=listener)
        post_compress.connect(callback)
        self.css_node.output()
        args, kwargs = callback.call_args
        self.assertEquals(CssCompressor, kwargs['sender'])
        self.assertEquals('css', kwargs['type'])
        self.assertEquals('file', kwargs['mode'])
        context = kwargs['context']
        assert 'url' in context['compressed']

    def test_css_signal_multiple_media_attributes(self):
        css = """\
<link rel="stylesheet" href="/static/css/one.css" media="handheld" type="text/css" />
<style type="text/css" media="print">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" />"""
        css_node = CssCompressor(css)

        def listener(sender, **kwargs):
            pass
        callback = Mock(wraps=listener)
        post_compress.connect(callback)
        css_node.output()
        self.assertEquals(3, callback.call_count)
Exemplo n.º 2
0
class PostCompressSignalTestCase(TestCase):
    def setUp(self):
        self.css = """\
<link rel="stylesheet" href="/static/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/static/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)

    def tearDown(self):
        post_compress.disconnect()

    def test_js_signal_sent(self):
        def listener(sender, **kwargs):
            pass

        callback = Mock(wraps=listener)
        post_compress.connect(callback)
        self.js_node.output()
        args, kwargs = callback.call_args
        self.assertEqual(JsCompressor, kwargs['sender'])
        self.assertEqual('js', kwargs['type'])
        self.assertEqual('file', kwargs['mode'])
        context = kwargs['context']
        assert 'url' in context['compressed']

    def test_css_signal_sent(self):
        def listener(sender, **kwargs):
            pass

        callback = Mock(wraps=listener)
        post_compress.connect(callback)
        self.css_node.output()
        args, kwargs = callback.call_args
        self.assertEqual(CssCompressor, kwargs['sender'])
        self.assertEqual('css', kwargs['type'])
        self.assertEqual('file', kwargs['mode'])
        context = kwargs['context']
        assert 'url' in context['compressed']

    def test_css_signal_multiple_media_attributes(self):
        css = """\
<link rel="stylesheet" href="/static/css/one.css" media="handheld" type="text/css" />
<style type="text/css" media="print">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" />"""
        css_node = CssCompressor(css)

        def listener(sender, **kwargs):
            pass

        callback = Mock(wraps=listener)
        post_compress.connect(callback)
        css_node.output()
        self.assertEqual(3, callback.call_count)
Exemplo n.º 3
0
class RequireJSPrecompiler(FilterBase):

    def __init__(self, content, attrs=None, filter_type=None, charset=None, filename=None):
        self.content = content
        self.attrs = attrs
        self.filter_type = filter_type
        self.filename = filename
        self.charset = charset

        # The RequireJS compiler for building optimized JS
        self.requireJSCompiler = RequireJSCompiler()

        # Use Django-Compressor's builtin Compressor tools to get the file
        # paths and contents of needed files
        self.compressor = JsCompressor()

    def input(self, **kwargs):
        if getattr(django_settings, 'COMPRESS_ENABLED', False):
            # Only use the build file to create RequireJS-optimizer content when
            # compress is enabled
            build_filepath = self.get_filepath(self.attrs.get('data-build'))

            global_config = getattr(settings, 'COMPRESSOR_REQUIREJS_GLOBAL_CONFIG', None)
            config_path = self.compressor.get_filename(global_config)

            paths = self.get_paths_from_required_libs()

            return self.requireJSCompiler.requirejs(
                build_filepath, config_path=config_path, paths=paths,
                charset=self.charset)
        else:
            # Just return the content of the main file, with no RequireJS
            # optimization (i.e., just use async-loading for all modules)
            main_file_full_path = self.compressor.get_filename(kwargs['basename'])
            return self.compressor.get_filecontent(main_file_full_path, self.charset)

    def get_paths_from_required_libs(self):
        paths = []
        if hasattr(settings, 'COMPRESSOR_REQUIREJS_REQUIRED_LIBS'):
            for arg in settings.COMPRESSOR_REQUIREJS_REQUIRED_LIBS.keys():
                path = self.get_filepath(settings.COMPRESSOR_REQUIREJS_REQUIRED_LIBS[arg])
                if path.endswith('.js'):
                    path = path[:-3]
                paths.append('paths.%s=%s' % (arg, path))
        return paths

    def get_filepath(self, static_path):
        """
        Get the absolute file-path of the the file given its
        STATIC_URL-inclusive path.

        Returns the file path on the file system.
        """
        basename = self.compressor.get_basename(static_path)
        return self.compressor.get_filename(basename)
Exemplo n.º 4
0
 def test_js_output(self):
     def extract_attr(tag):
         if tag.has_attr('async'):
             return 'async'
         if tag.has_attr('defer'):
             return 'defer'
     js_node = JsCompressor(self.js)
     output = [None, 'async', 'defer', None, 'async', None]
     scripts = make_soup(js_node.output()).find_all('script')
     attrs = [extract_attr(s) for s in scripts]
     self.assertEqual(output, attrs)
Exemplo n.º 5
0
    def setUp(self):
        self.css = """\
<link rel="stylesheet" href="/static/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/static/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)
Exemplo n.º 6
0
    def test_js_output(self):
        def extract_attr(tag):
            if tag.has_attr("async"):
                return "async"
            if tag.has_attr("defer"):
                return "defer"

        js_node = JsCompressor(self.js)
        output = [None, "async", "defer", None, "async", None]
        scripts = make_soup(js_node.output()).find_all("script")
        attrs = [extract_attr(s) for s in scripts]
        self.assertEqual(output, attrs)
Exemplo n.º 7
0
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        settings.COMPRESS_DEBUG_TOGGLE = 'nocompress'
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)
Exemplo n.º 8
0
 def test_custom_output_dir(self):
     try:
         old_output_dir = settings.COMPRESS_OUTPUT_DIR
         settings.COMPRESS_OUTPUT_DIR = 'custom'
         output = u'<script type="text/javascript" src="/media/custom/js/066cd253eada.js"></script>'
         self.assertEqual(output, JsCompressor(self.js).output())
         settings.COMPRESS_OUTPUT_DIR = ''
         output = u'<script type="text/javascript" src="/media/js/066cd253eada.js"></script>'
         self.assertEqual(output, JsCompressor(self.js).output())
         settings.COMPRESS_OUTPUT_DIR = '/custom/nested/'
         output = u'<script type="text/javascript" src="/media/custom/nested/js/066cd253eada.js"></script>'
         self.assertEqual(output, JsCompressor(self.js).output())
     finally:
         settings.COMPRESS_OUTPUT_DIR = old_output_dir
Exemplo n.º 9
0
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        self.css = """
        <link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        <link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
        """
        self.css_node = CssCompressor(self.css)

        self.js = """
        <script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        """
        self.js_node = JsCompressor(self.js)
 def test_js_output(self):
     def extract_attr(tag):
         if tag.has_attr('async'):
             return 'async'
         if tag.has_attr('defer'):
             return 'defer'
     js_node = JsCompressor(self.js)
     output = [None, 'async', 'defer', None, 'async', None]
     scripts = soup_find_all(js_node.output(), 'script')
     if use_bs4:
         attrs = [extract_attr(i) for i in scripts]
     else:
         attrs = [s.get('async') or s.get('defer') for s in scripts]
     self.assertEqual(output, attrs)
Exemplo n.º 11
0
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/one.less" type="text/less" />
<link rel="stylesheet" href="/media/css/two.less" type="text/less" />"""
        self.css_node = CssCompressor(self.css)
        self.css_node.opts = {'group_first': 'true'}

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>
<script src="/media/js/one.coffee" type="text/coffeescript"></script>
<script src="/media/js/two.coffee" type="text/coffeescript"></script>"""
        self.js_node = JsCompressor(self.js)
Exemplo n.º 12
0
    def __init__(self, content, attrs=None, filter_type=None, charset=None, filename=None):
        self.content = content
        self.attrs = attrs
        self.filter_type = filter_type
        self.filename = filename
        self.charset = charset

        # The RequireJS compiler for building optimized JS
        self.requireJSCompiler = RequireJSCompiler()

        # Use Django-Compressor's builtin Compressor tools to get the file
        # paths and contents of needed files
        self.compressor = JsCompressor()
Exemplo n.º 13
0
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        settings.COMPRESS_DEBUG_TOGGLE = 'nocompress'
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)
Exemplo n.º 14
0
    def setUp(self):
        settings.COMPRESS = True
        self.css = """
        <link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        <link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
        """
        self.cssNode = CssCompressor(self.css)

        self.js = """
        <script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        """
        self.jsNode = JsCompressor(self.js)
Exemplo n.º 15
0
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/one.less" type="text/less" />
<link rel="stylesheet" href="/media/css/two.less" type="text/less" />"""
        self.css_node = CssCompressor(self.css)
        self.css_node.opts = {"group_first": "true"}

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>
<script src="/media/js/one.coffee" type="text/coffeescript"></script>
<script src="/media/js/two.coffee" type="text/coffeescript"></script>"""
        self.js_node = JsCompressor(self.js)
Exemplo n.º 16
0
 def render_tag(self, context, name, nodelist):
     request = context['request']
     rendered_contents = nodelist.render(context)
     content = request.media_holder[name].render()
     if settings.COMPRESS:
         if name == 'css':
             compressor = CssCompressor(content)
         elif name == 'js':
             compressor = JsCompressor(content)
         output = self.cache_get(compressor.cachekey)
         if output is None:
             try:
                 output = compressor.output()
                 self.cache_set(compressor.cachekey, output)
             except:
                 from traceback import format_exc
                 raise Exception(format_exc())
     else:
         output = content  # no compression
     return '%s\n%s' % (output, rendered_contents)
Exemplo n.º 17
0
class CompressorTestCase(TestCase):

    def setUp(self):
        self.maxDiff = None
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        settings.COMPRESS_DEBUG_TOGGLE = 'nocompress'
        self.css = """
        <link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        <link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
        """
        self.css_node = CssCompressor(self.css)

        self.js = """
        <script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        """
        self.js_node = JsCompressor(self.js)

    def test_css_split(self):
        out = [
            (SOURCE_FILE, os.path.join(settings.COMPRESS_ROOT, u'css/one.css'), u'css/one.css', u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8" />'),
            (SOURCE_HUNK, u'p { border:5px solid green;}', None, u'<style type="text/css">p { border:5px solid green;}</style>'),
            (SOURCE_FILE, os.path.join(settings.COMPRESS_ROOT, u'css/two.css'), u'css/two.css', u'<link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8" />'),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], x[2], self.css_node.parser.elem_str(x[3])) for x in split]
        self.assertEqual(out, split)

    def test_css_hunks(self):
        out = ['body { background:#990; }', u'p { border:5px solid green;}', 'body { color:#fff; }']
        self.assertEqual(out, list(self.css_node.hunks))

    def test_css_output(self):
        out = u'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
        self.assertEqual(out, self.css_node.combined)

    def test_css_mtimes(self):
        is_date = re.compile(r'^\d{10}[\.\d]+$')
        for date in self.css_node.mtimes:
            self.assertTrue(is_date.match(str(float(date))),
                "mtimes is returning something that doesn't look like a date: %s" % date)

    def test_css_return_if_off(self):
        settings.COMPRESS_ENABLED = False
        self.assertEqual(self.css, self.css_node.output())

    def test_cachekey(self):
        is_cachekey = re.compile(r'\w{12}')
        self.assertTrue(is_cachekey.match(self.css_node.cachekey),
            "cachekey is returning something that doesn't look like r'\w{12}'")

    def test_css_hash(self):
        self.assertEqual('c618e6846d04', get_hexdigest(self.css, 12))

    def test_css_return_if_on(self):
        output = css_tag('/media/CACHE/css/e41ba2cc6982.css')
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_split(self):
        out = [(SOURCE_FILE, os.path.join(settings.COMPRESS_ROOT, u'js/one.js'), u'js/one.js', '<script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>'),
         (SOURCE_HUNK, u'obj.value = "value";', None, '<script type="text/javascript" charset="utf-8">obj.value = "value";</script>')
         ]
        split = self.js_node.split_contents()
        split = [(x[0], x[1], x[2], self.js_node.parser.elem_str(x[3])) for x in split]
        self.assertEqual(out, split)

    def test_js_hunks(self):
        out = ['obj = {};', u'obj.value = "value";']
        self.assertEqual(out, list(self.js_node.hunks))

    def test_js_concat(self):
        out = u'obj = {};\nobj.value = "value";'
        self.assertEqual(out, self.js_node.concat)

    def test_js_output(self):
        out = u'obj={};obj.value="value";'
        self.assertEqual(out, self.js_node.combined)

    def test_js_return_if_off(self):
        try:
            enabled = settings.COMPRESS_ENABLED
            precompilers = settings.COMPRESS_PRECOMPILERS
            settings.COMPRESS_ENABLED = False
            settings.COMPRESS_PRECOMPILERS = {}
            self.assertEqual(self.js, self.js_node.output())
        finally:
            settings.COMPRESS_ENABLED = enabled
            settings.COMPRESS_PRECOMPILERS = precompilers

    def test_js_return_if_on(self):
        output = u'<script type="text/javascript" src="/media/CACHE/js/066cd253eada.js" charset="utf-8"></script>'
        self.assertEqual(output, self.js_node.output())

    def test_custom_output_dir(self):
        try:
            old_output_dir = settings.COMPRESS_OUTPUT_DIR
            settings.COMPRESS_OUTPUT_DIR = 'custom'
            output = u'<script type="text/javascript" src="/media/custom/js/066cd253eada.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = ''
            output = u'<script type="text/javascript" src="/media/js/066cd253eada.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = '/custom/nested/'
            output = u'<script type="text/javascript" src="/media/custom/nested/js/066cd253eada.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
        finally:
            settings.COMPRESS_OUTPUT_DIR = old_output_dir
Exemplo n.º 18
0
class CompressorTestCase(SimpleTestCase):

    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = ()
        settings.COMPRESS_DEBUG_TOGGLE = 'nocompress'
        self.css = """\
<link rel="stylesheet" href="/static/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/static/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)

    def test_css_split(self):
        out = [
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, 'css', 'one.css'),
                'css/one.css', '<link rel="stylesheet" href="/static/css/one.css" type="text/css" />',
            ),
            (
                SOURCE_HUNK,
                'p { border:5px solid green;}',
                None,
                '<style type="text/css">p { border:5px solid green;}</style>',
            ),
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, 'css', 'two.css'),
                'css/two.css',
                '<link rel="stylesheet" href="/static/css/two.css" type="text/css" />',
            ),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], x[2], self.css_node.parser.elem_str(x[3])) for x in split]
        self.assertEqual(out, split)

    def test_css_hunks(self):
        out = ['body { background:#990; }', 'p { border:5px solid green;}', 'body { color:#fff; }']
        self.assertEqual(out, list(self.css_node.hunks()))

    def test_css_output(self):
        out = 'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
        hunks = '\n'.join([h for h in self.css_node.hunks()])
        self.assertEqual(out, hunks)

    def test_css_mtimes(self):
        is_date = re.compile(r'^\d{10}[\.\d]+$')
        for date in self.css_node.mtimes:
            self.assertTrue(is_date.match(str(float(date))),
                "mtimes is returning something that doesn't look like a date: %s" % date)

    def test_css_return_if_off(self):
        settings.COMPRESS_ENABLED = False
        self.assertEqual(self.css, self.css_node.output())

    def test_cachekey(self):
        is_cachekey = re.compile(r'\w{12}')
        self.assertTrue(is_cachekey.match(self.css_node.cachekey),
            "cachekey is returning something that doesn't look like r'\w{12}'")

    def test_css_return_if_on(self):
        output = css_tag('/static/CACHE/css/e41ba2cc6982.css')
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_split(self):
        out = [
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, 'js', 'one.js'),
                'js/one.js',
                '<script src="/static/js/one.js" type="text/javascript"></script>',
            ),
            (
                SOURCE_HUNK,
                'obj.value = "value";',
                None,
                '<script type="text/javascript">obj.value = "value";</script>',
            ),
        ]
        split = self.js_node.split_contents()
        split = [(x[0], x[1], x[2], self.js_node.parser.elem_str(x[3])) for x in split]
        self.assertEqual(out, split)

    def test_js_hunks(self):
        out = ['obj = {};', 'obj.value = "value";']
        self.assertEqual(out, list(self.js_node.hunks()))

    def test_js_output(self):
        out = '<script type="text/javascript" src="/static/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_js_override_url(self):
        self.js_node.context.update({'url': 'This is not a url, just a text'})
        out = '<script type="text/javascript" src="/static/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_css_override_url(self):
        self.css_node.context.update({'url': 'This is not a url, just a text'})
        output = css_tag('/static/CACHE/css/e41ba2cc6982.css')
        self.assertEqual(output, self.css_node.output().strip())

    @override_settings(COMPRESS_PRECOMPILERS=(), COMPRESS_ENABLED=False)
    def test_js_return_if_off(self):
        self.assertEqual(self.js, self.js_node.output())

    def test_js_return_if_on(self):
        output = '<script type="text/javascript" src="/static/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(output, self.js_node.output())

    @override_settings(COMPRESS_OUTPUT_DIR='custom')
    def test_custom_output_dir1(self):
        output = '<script type="text/javascript" src="/static/custom/js/066cd253eada.js"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())

    @override_settings(COMPRESS_OUTPUT_DIR='')
    def test_custom_output_dir2(self):
        output = '<script type="text/javascript" src="/static/js/066cd253eada.js"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())

    @override_settings(COMPRESS_OUTPUT_DIR='/custom/nested/')
    def test_custom_output_dir3(self):
        output = '<script type="text/javascript" src="/static/custom/nested/js/066cd253eada.js"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())

    @override_settings(COMPRESS_PRECOMPILERS=(
        ('text/foobar', 'compressor.tests.test_base.TestPrecompiler'),
    ), COMPRESS_ENABLED=True)
    def test_precompiler_class_used(self):
        css = '<style type="text/foobar">p { border:10px solid red;}</style>'
        css_node = CssCompressor(css)
        output = make_soup(css_node.output('inline'))
        self.assertEqual(output.text, 'OUTPUT')

    @override_settings(COMPRESS_PRECOMPILERS=(
        ('text/foobar', 'compressor.tests.test_base.NonexistentFilter'),
    ), COMPRESS_ENABLED=True)
    def test_nonexistent_precompiler_class_error(self):
        css = '<style type="text/foobar">p { border:10px solid red;}</style>'
        css_node = CssCompressor(css)
        self.assertRaises(FilterDoesNotExist, css_node.output, 'inline')
Exemplo n.º 19
0
class CompressorTestCase(TestCase):

    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        settings.COMPRESS_DEBUG_TOGGLE = 'nocompress'
        self.css = """
        <link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        <link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
        """
        self.css_node = CssCompressor(self.css)

        self.js = """
        <script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        """
        self.js_node = JsCompressor(self.js)

    def test_css_split(self):
        out = [
            ('file', os.path.join(settings.COMPRESS_ROOT, u'css/one.css'), u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8" />'),
            ('hunk', u'p { border:5px solid green;}', u'<style type="text/css">p { border:5px solid green;}</style>'),
            ('file', os.path.join(settings.COMPRESS_ROOT, u'css/two.css'), u'<link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8" />'),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], self.css_node.parser.elem_str(x[2])) for x in split]
        self.assertEqual(out, split)

    def test_css_hunks(self):
        out = ['body { background:#990; }', u'p { border:5px solid green;}', 'body { color:#fff; }']
        self.assertEqual(out, list(self.css_node.hunks))

    def test_css_output(self):
        out = u'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
        self.assertEqual(out, self.css_node.combined)

    def test_css_mtimes(self):
        is_date = re.compile(r'^\d{10}[\.\d]+$')
        for date in self.css_node.mtimes:
            self.assert_(is_date.match(str(float(date))), "mtimes is returning something that doesn't look like a date: %s" % date)

    def test_css_return_if_off(self):
        settings.COMPRESS_ENABLED = False
        self.assertEqual(self.css, self.css_node.output())

    def test_cachekey(self):
        host_name = socket.gethostname()
        is_cachekey = re.compile(r'django_compressor\.%s\.\w{12}' % host_name)
        self.assert_(is_cachekey.match(self.css_node.cachekey), "cachekey is returning something that doesn't look like r'django_compressor\.%s\.\w{12}'" % host_name)

    def test_css_hash(self):
        self.assertEqual('666f3aa8eacd', self.css_node.hash(self.css))

    def test_css_return_if_on(self):
        output = u'<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css">'
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_split(self):
        out = [('file', os.path.join(settings.COMPRESS_ROOT, u'js/one.js'), '<script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>'),
         ('hunk', u'obj.value = "value";', '<script type="text/javascript" charset="utf-8">obj.value = "value";</script>')
         ]
        split = self.js_node.split_contents()
        split = [(x[0], x[1], self.js_node.parser.elem_str(x[2])) for x in split]
        self.assertEqual(out, split)

    def test_js_hunks(self):
        out = ['obj = {};', u'obj.value = "value";']
        self.assertEqual(out, list(self.js_node.hunks))

    def test_js_concat(self):
        out = u'obj = {};\nobj.value = "value";'
        self.assertEqual(out, self.js_node.concat)

    def test_js_output(self):
        out = u'obj={};obj.value="value";'
        self.assertEqual(out, self.js_node.combined)

    def test_js_return_if_off(self):
        try:
            enabled = settings.COMPRESS_ENABLED
            precompilers = settings.COMPRESS_PRECOMPILERS
            settings.COMPRESS_ENABLED = False
            settings.COMPRESS_PRECOMPILERS = {}
            self.assertEqual(self.js, self.js_node.output())
        finally:
            settings.COMPRESS_ENABLED = enabled
            settings.COMPRESS_PRECOMPILERS = precompilers

    def test_js_return_if_on(self):
        output = u'<script type="text/javascript" src="/media/CACHE/js/3f33b9146e12.js" charset="utf-8"></script>'
        self.assertEqual(output, self.js_node.output())

    def test_custom_output_dir(self):
        try:
            old_output_dir = settings.COMPRESS_OUTPUT_DIR
            settings.COMPRESS_OUTPUT_DIR = 'custom'
            output = u'<script type="text/javascript" src="/media/custom/js/3f33b9146e12.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = ''
            output = u'<script type="text/javascript" src="/media/js/3f33b9146e12.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = '/custom/nested/'
            output = u'<script type="text/javascript" src="/media/custom/nested/js/3f33b9146e12.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
        finally:
            settings.COMPRESS_OUTPUT_DIR = old_output_dir
Exemplo n.º 20
0
class CompressorTestCase(TestCase):

    def setUp(self):
        settings.COMPRESS = True
        self.css = """
        <link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        <link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
        """
        self.cssNode = CssCompressor(self.css)

        self.js = """
        <script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        """
        self.jsNode = JsCompressor(self.js)

    def test_css_split(self):
        out = [
            ('file', os.path.join(settings.MEDIA_ROOT, u'css/one.css'), u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8" />'),
            ('hunk', u'p { border:5px solid green;}', u'<style type="text/css">p { border:5px solid green;}</style>'),
            ('file', os.path.join(settings.MEDIA_ROOT, u'css/two.css'), u'<link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8" />'),
        ]
        split = self.cssNode.split_contents()
        split = [(x[0], x[1], self.cssNode.parser.elem_str(x[2])) for x in split]
        self.assertEqual(out, split)

    def test_css_hunks(self):
        out = ['body { background:#990; }', u'p { border:5px solid green;}', 'body { color:#fff; }']
        self.assertEqual(out, self.cssNode.hunks)

    def test_css_output(self):
        out = u'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
        self.assertEqual(out, self.cssNode.combined)

    def test_css_mtimes(self):
        is_date = re.compile(r'^\d{10}\.\d$')
        for date in self.cssNode.mtimes:
            self.assert_(is_date.match(str(float(date))), "mtimes is returning something that doesn't look like a date")

    def test_css_return_if_off(self):
        settings.COMPRESS = False
        self.assertEqual(self.css, self.cssNode.output())

    def test_cachekey(self):
        is_cachekey = re.compile(r'django_compressor\.\w{12}')
        self.assert_(is_cachekey.match(self.cssNode.cachekey), "cachekey is returning something that doesn't look like r'django_compressor\.\w{12}'")

    def test_css_hash(self):
        self.assertEqual('f7c661b7a124', self.cssNode.hash)

    def test_css_return_if_on(self):
        output = u'<link rel="stylesheet" href="/media/cache/css/f7c661b7a124.css" type="text/css">'
        self.assertEqual(output, self.cssNode.output().strip())

    def test_js_split(self):
        out = [('file', os.path.join(settings.MEDIA_ROOT, u'js/one.js'), '<script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>'),
         ('hunk', u'obj.value = "value";', '<script type="text/javascript" charset="utf-8">obj.value = "value";</script>')
         ]
        split = self.jsNode.split_contents()
        split = [(x[0], x[1], self.jsNode.parser.elem_str(x[2])) for x in split]
        self.assertEqual(out, split)

    def test_js_hunks(self):
        out = ['obj = {};', u'obj.value = "value";']
        self.assertEqual(out, self.jsNode.hunks)

    def test_js_concat(self):
        out = u'obj = {};\nobj.value = "value";'
        self.assertEqual(out, self.jsNode.concat())

    def test_js_output(self):
        out = u'obj={};obj.value="value";'
        self.assertEqual(out, self.jsNode.combined)

    def test_js_return_if_off(self):
        settings.COMPRESS = False
        self.assertEqual(self.js, self.jsNode.output())

    def test_js_return_if_on(self):
        output = u'<script type="text/javascript" src="/media/cache/js/3f33b9146e12.js" charset="utf-8"></script>'
        self.assertEqual(output, self.jsNode.output())

    def test_custom_output_dir(self):
        old_output_dir = settings.OUTPUT_DIR
        settings.OUTPUT_DIR = 'custom'
        output = u'<script type="text/javascript" src="/media/custom/js/3f33b9146e12.js" charset="utf-8"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())
        settings.OUTPUT_DIR = ''
        output = u'<script type="text/javascript" src="/media/js/3f33b9146e12.js" charset="utf-8"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())
        settings.OUTPUT_DIR = '/custom/nested/'
        output = u'<script type="text/javascript" src="/media/custom/nested/js/3f33b9146e12.js" charset="utf-8"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())
        settings.OUTPUT_DIR = old_output_dir
Exemplo n.º 21
0
class CompressorTestCase(TestCase):
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        self.css = """
        <link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        <link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
        """
        self.css_node = CssCompressor(self.css)

        self.js = """
        <script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        """
        self.js_node = JsCompressor(self.js)

    def test_css_split(self):
        out = [
            ('file', os.path.join(settings.COMPRESS_ROOT, u'css/one.css'),
             u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8" />'
             ),
            ('hunk', u'p { border:5px solid green;}',
             u'<style type="text/css">p { border:5px solid green;}</style>'),
            ('file', os.path.join(settings.COMPRESS_ROOT, u'css/two.css'),
             u'<link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8" />'
             ),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], self.css_node.parser.elem_str(x[2]))
                 for x in split]
        self.assertEqual(out, split)

    def test_css_hunks(self):
        out = [
            'body { background:#990; }', u'p { border:5px solid green;}',
            'body { color:#fff; }'
        ]
        self.assertEqual(out, list(self.css_node.hunks))

    def test_css_output(self):
        out = u'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
        self.assertEqual(out, self.css_node.combined)

    def test_css_mtimes(self):
        is_date = re.compile(r'^\d{10}[\.\d]+$')
        for date in self.css_node.mtimes:
            self.assert_(
                is_date.match(str(float(date))),
                "mtimes is returning something that doesn't look like a date: %s"
                % date)

    def test_css_return_if_off(self):
        settings.COMPRESS_ENABLED = False
        self.assertEqual(self.css, self.css_node.output())

    def test_cachekey(self):
        host_name = socket.gethostname()
        is_cachekey = re.compile(r'django_compressor\.%s\.\w{12}' % host_name)
        self.assert_(
            is_cachekey.match(self.css_node.cachekey),
            "cachekey is returning something that doesn't look like r'django_compressor\.%s\.\w{12}'"
            % host_name)

    def test_css_hash(self):
        self.assertEqual('f7c661b7a124', self.css_node.hash)

    def test_css_return_if_on(self):
        output = u'<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css">'
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_split(self):
        out = [
            ('file', os.path.join(settings.COMPRESS_ROOT, u'js/one.js'),
             '<script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>'
             ),
            ('hunk', u'obj.value = "value";',
             '<script type="text/javascript" charset="utf-8">obj.value = "value";</script>'
             )
        ]
        split = self.js_node.split_contents()
        split = [(x[0], x[1], self.js_node.parser.elem_str(x[2]))
                 for x in split]
        self.assertEqual(out, split)

    def test_js_hunks(self):
        out = ['obj = {};', u'obj.value = "value";']
        self.assertEqual(out, list(self.js_node.hunks))

    def test_js_concat(self):
        out = u'obj = {};\nobj.value = "value";'
        self.assertEqual(out, self.js_node.concat())

    def test_js_output(self):
        out = u'obj={};obj.value="value";'
        self.assertEqual(out, self.js_node.combined)

    def test_js_return_if_off(self):
        try:
            enabled = settings.COMPRESS_ENABLED
            settings.COMPRESS_ENABLED = False
            self.assertEqual(self.js, self.js_node.output())
        finally:
            settings.COMPRESS_ENABLED = enabled

    def test_js_return_if_on(self):
        output = u'<script type="text/javascript" src="/media/CACHE/js/3f33b9146e12.js" charset="utf-8"></script>'
        self.assertEqual(output, self.js_node.output())

    def test_custom_output_dir(self):
        try:
            old_output_dir = settings.COMPRESS_OUTPUT_DIR
            settings.COMPRESS_OUTPUT_DIR = 'custom'
            output = u'<script type="text/javascript" src="/media/custom/js/3f33b9146e12.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = ''
            output = u'<script type="text/javascript" src="/media/js/3f33b9146e12.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = '/custom/nested/'
            output = u'<script type="text/javascript" src="/media/custom/nested/js/3f33b9146e12.js" charset="utf-8"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
        finally:
            settings.COMPRESS_OUTPUT_DIR = old_output_dir
Exemplo n.º 22
0
class CompressorTestCase(SimpleTestCase):

    def setUp(self):
        self.css = """\
<link rel="stylesheet" href="/static/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/static/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)

    def assertEqualCollapsed(self, a, b):
        """
        assertEqual with internal newlines collapsed to single, and
        trailing whitespace removed.
        """
        collapse = lambda x: re.sub(r'\n+', '\n', x).rstrip()
        self.assertEqual(collapse(a), collapse(b))

    def assertEqualSplits(self, a, b):
        """
        assertEqual for splits, particularly ignoring the presence of
        a trailing newline on the content.
        """
        mangle = lambda split: [(x[0], x[1], x[2], x[3].rstrip()) for x in split]
        self.assertEqual(mangle(a), mangle(b))

    def test_css_split(self):
        out = [
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, 'css', 'one.css'),
                'css/one.css', '<link rel="stylesheet" href="/static/css/one.css" type="text/css" />',
            ),
            (
                SOURCE_HUNK,
                'p { border:5px solid green;}',
                None,
                '<style type="text/css">p { border:5px solid green;}</style>',
            ),
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, 'css', 'two.css'),
                'css/two.css',
                '<link rel="stylesheet" href="/static/css/two.css" type="text/css" />',
            ),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], x[2], self.css_node.parser.elem_str(x[3])) for x in split]
        self.assertEqualSplits(split, out)

    def test_css_hunks(self):
        out = ['body { background:#990; }', 'p { border:5px solid green;}', 'body { color:#fff; }']
        self.assertEqual(out, list(self.css_node.hunks()))

    def test_css_output(self):
        out = 'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
        hunks = '\n'.join([h for h in self.css_node.hunks()])
        self.assertEqual(out, hunks)

    def test_css_output_with_bom_input(self):
        out = 'body { background:#990; }\n.compress-test {color: red;}'
        css = ("""<link rel="stylesheet" href="/static/css/one.css" type="text/css" />
        <link rel="stylesheet" href="/static/css/utf-8_with-BOM.css" type="text/css" />""")
        css_node_with_bom = CssCompressor(css)
        hunks = '\n'.join([h for h in css_node_with_bom.hunks()])
        self.assertEqual(out, hunks)

    def test_css_mtimes(self):
        is_date = re.compile(r'^\d{10}[\.\d]+$')
        for date in self.css_node.mtimes:
            self.assertTrue(is_date.match(str(float(date))),
                "mtimes is returning something that doesn't look like a date: %s" % date)

    @override_settings(COMPRESS_ENABLED=False)
    def test_css_return_if_off(self):
        self.assertEqualCollapsed(self.css, self.css_node.output())

    def test_cachekey(self):
        is_cachekey = re.compile(r'\w{12}')
        self.assertTrue(is_cachekey.match(self.css_node.cachekey),
            r"cachekey is returning something that doesn't look like r'\w{12}'")

    def test_css_return_if_on(self):
        output = css_tag('/static/CACHE/css/58a8c0714e59.css')
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_split(self):
        out = [
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, 'js', 'one.js'),
                'js/one.js',
                '<script src="/static/js/one.js" type="text/javascript"></script>',
            ),
            (
                SOURCE_HUNK,
                'obj.value = "value";',
                None,
                '<script type="text/javascript">obj.value = "value";</script>',
            ),
        ]
        split = self.js_node.split_contents()
        split = [(x[0], x[1], x[2], self.js_node.parser.elem_str(x[3])) for x in split]
        self.assertEqualSplits(split, out)

    def test_js_hunks(self):
        out = ['obj = {};', 'obj.value = "value";']
        self.assertEqual(out, list(self.js_node.hunks()))

    def test_js_output(self):
        out = '<script type="text/javascript" src="/static/CACHE/js/74e158ccb432.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_js_override_url(self):
        self.js_node.context.update({'url': 'This is not a url, just a text'})
        out = '<script type="text/javascript" src="/static/CACHE/js/74e158ccb432.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_css_override_url(self):
        self.css_node.context.update({'url': 'This is not a url, just a text'})
        output = css_tag('/static/CACHE/css/58a8c0714e59.css')
        self.assertEqual(output, self.css_node.output().strip())

    @override_settings(COMPRESS_PRECOMPILERS=(), COMPRESS_ENABLED=False)
    def test_js_return_if_off(self):
        self.assertEqualCollapsed(self.js, self.js_node.output())

    def test_js_return_if_on(self):
        output = '<script type="text/javascript" src="/static/CACHE/js/74e158ccb432.js"></script>'
        self.assertEqual(output, self.js_node.output())

    @override_settings(COMPRESS_OUTPUT_DIR='custom')
    def test_custom_output_dir1(self):
        output = '<script type="text/javascript" src="/static/custom/js/74e158ccb432.js"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())

    @override_settings(COMPRESS_OUTPUT_DIR='')
    def test_custom_output_dir2(self):
        output = '<script type="text/javascript" src="/static/js/74e158ccb432.js"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())

    @override_settings(COMPRESS_OUTPUT_DIR='/custom/nested/')
    def test_custom_output_dir3(self):
        output = '<script type="text/javascript" src="/static/custom/nested/js/74e158ccb432.js"></script>'
        self.assertEqual(output, JsCompressor(self.js).output())

    @override_settings(COMPRESS_PRECOMPILERS=(
        ('text/foobar', 'compressor.tests.test_base.TestPrecompiler'),
    ), COMPRESS_ENABLED=True)
    def test_precompiler_class_used(self):
        css = '<style type="text/foobar">p { border:10px solid red;}</style>'
        css_node = CssCompressor(css)
        output = make_soup(css_node.output('inline'))
        self.assertEqual(output.text, 'OUTPUT')

    @override_settings(COMPRESS_PRECOMPILERS=(
        ('text/foobar', 'compressor.tests.test_base.NonexistentFilter'),
    ), COMPRESS_ENABLED=True)
    def test_nonexistent_precompiler_class_error(self):
        css = '<style type="text/foobar">p { border:10px solid red;}</style>'
        css_node = CssCompressor(css)
        self.assertRaises(FilterDoesNotExist, css_node.output, 'inline')

    @override_settings(COMPRESS_PRECOMPILERS=(
        ('text/foobar', './foo -I ./bar/baz'),
    ), COMPRESS_ENABLED=True)
    def test_command_with_dot_precompiler(self):
        css = '<style type="text/foobar">p { border:10px solid red;}</style>'
        css_node = CssCompressor(css)
        self.assertRaises(FilterError, css_node.output, 'inline')

    @override_settings(COMPRESS_PRECOMPILERS=(
        ('text/django', 'compressor.filters.template.TemplateFilter'),
    ), COMPRESS_ENABLED=True)
    def test_template_precompiler(self):
        css = '<style type="text/django">p { border:10px solid {% if 1 %}green{% else %}red{% endif %};}</style>'
        css_node = CssCompressor(css)
        output = make_soup(css_node.output('inline'))
        self.assertEqual(output.text, 'p { border:10px solid green;}')
Exemplo n.º 23
0
class CompressorGroupFirstTestCase(TestCase):
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/one.less" type="text/less" />
<link rel="stylesheet" href="/media/css/two.less" type="text/less" />"""
        self.css_node = CssCompressor(self.css)
        self.css_node.opts = {'group_first': 'true'}

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>
<script src="/media/js/one.coffee" type="text/coffeescript"></script>
<script src="/media/js/two.coffee" type="text/coffeescript"></script>"""
        self.js_node = JsCompressor(self.js)

    def test_css_group(self):
        out = [
            [
                SOURCE_HUNK,
                u'body { background:#990; }p { border:5px solid green;}',
                u'css/one.css',
                u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" /><style type="text/css">p { border:5px solid green;}</style>'
            ],
            [
                SOURCE_HUNK, u'body { background:#990; }body { color:#fff; }',
                u'css/one.less',
                u'<link rel="stylesheet" href="/media/css/one.less" type="text/less" /><link rel="stylesheet" href="/media/css/two.less" type="text/less" />'
            ],
        ]
        split = self.css_node.group_contents()
        split = [[
            x[0], x[1], x[2],
            make_elems_str(self.css_node.parser, x[3])
        ] for x in split]
        self.assertEqual(out, split)

    def test_css_single(self):
        css_node = CssCompressor(
            """<link rel="stylesheet" href="/media/css/one.css" type="text/css" />"""
        )
        css_node.opts = {'group_first': 'true'}
        out = [
            [
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, u'css',
                             u'one.css'), u'css/one.css',
                u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" />'
            ],
        ]
        split = css_node.group_contents()
        split = [[
            x[0], x[1], x[2],
            make_elems_str(self.css_node.parser, x[3])
        ] for x in split]
        self.assertEqual(out, split)

    def test_js_group(self):
        out = [
            [
                SOURCE_HUNK, u'obj = {};obj.value = "value";', u'js/one.js',
                '<script src="/media/js/one.js" type="text/javascript"></script><script type="text/javascript">obj.value = "value";</script>'
            ],
            [
                SOURCE_HUNK, u'# this is a comment.\n# this is a comment.',
                u'js/one.coffee',
                '<script src="/media/js/one.coffee" type="text/coffeescript"></script><script src="/media/js/two.coffee" type="text/coffeescript"></script>'
            ],
        ]
        split = self.js_node.group_contents()
        split = [[x[0], x[1], x[2],
                  make_elems_str(self.js_node.parser, x[3])] for x in split]
        self.assertEqual(out, split)
Exemplo n.º 24
0
class CompressorTestCase(TestCase):
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        settings.COMPRESS_DEBUG_TOGGLE = 'nocompress'
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)

    def test_css_split(self):
        out = [
            (SOURCE_FILE,
             os.path.join(settings.COMPRESS_ROOT, u'css',
                          u'one.css'), u'css/one.css',
             u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" />'
             ),
            (SOURCE_HUNK, u'p { border:5px solid green;}', None,
             u'<style type="text/css">p { border:5px solid green;}</style>'),
            (SOURCE_FILE,
             os.path.join(settings.COMPRESS_ROOT, u'css',
                          u'two.css'), u'css/two.css',
             u'<link rel="stylesheet" href="/media/css/two.css" type="text/css" />'
             ),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], x[2], self.css_node.parser.elem_str(x[3][0]))
                 for x in split]
        self.assertEqual(out, split)

    def test_css_hunks(self):
        out = [
            'body { background:#990; }', u'p { border:5px solid green;}',
            'body { color:#fff; }'
        ]
        self.assertEqual(out, list(self.css_node.hunks()))

    def test_css_output(self):
        out = u'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
        hunks = '\n'.join([h for h in self.css_node.hunks()])
        self.assertEqual(out, hunks)

    def test_css_mtimes(self):
        is_date = re.compile(r'^\d{10}[\.\d]+$')
        for date in self.css_node.mtimes:
            self.assertTrue(
                is_date.match(str(float(date))),
                "mtimes is returning something that doesn't look like a date: %s"
                % date)

    def test_css_return_if_off(self):
        settings.COMPRESS_ENABLED = False
        self.assertEqual(self.css, self.css_node.output())

    def test_cachekey(self):
        is_cachekey = re.compile(r'\w{12}')
        self.assertTrue(
            is_cachekey.match(self.css_node.cachekey),
            "cachekey is returning something that doesn't look like r'\w{12}'")

    def test_css_return_if_on(self):
        output = css_tag('/media/CACHE/css/e41ba2cc6982.css')
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_split(self):
        out = [
            (SOURCE_FILE, os.path.join(settings.COMPRESS_ROOT, u'js',
                                       u'one.js'), u'js/one.js',
             '<script src="/media/js/one.js" type="text/javascript"></script>'
             ),
            (SOURCE_HUNK, u'obj.value = "value";', None,
             '<script type="text/javascript">obj.value = "value";</script>'),
        ]
        split = self.js_node.split_contents()
        split = [(x[0], x[1], x[2], self.js_node.parser.elem_str(x[3][0]))
                 for x in split]
        self.assertEqual(out, split)

    def test_js_hunks(self):
        out = ['obj = {};', u'obj.value = "value";']
        self.assertEqual(out, list(self.js_node.hunks()))

    def test_js_output(self):
        out = u'<script type="text/javascript" src="/media/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_js_override_url(self):
        self.js_node.context.update({'url': u'This is not a url, just a text'})
        out = u'<script type="text/javascript" src="/media/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_css_override_url(self):
        self.css_node.context.update(
            {'url': u'This is not a url, just a text'})
        output = css_tag('/media/CACHE/css/e41ba2cc6982.css')
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_return_if_off(self):
        try:
            enabled = settings.COMPRESS_ENABLED
            precompilers = settings.COMPRESS_PRECOMPILERS
            settings.COMPRESS_ENABLED = False
            settings.COMPRESS_PRECOMPILERS = {}
            self.assertEqual(self.js, self.js_node.output())
        finally:
            settings.COMPRESS_ENABLED = enabled
            settings.COMPRESS_PRECOMPILERS = precompilers

    def test_js_return_if_on(self):
        output = u'<script type="text/javascript" src="/media/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(output, self.js_node.output())

    def test_custom_output_dir(self):
        try:
            old_output_dir = settings.COMPRESS_OUTPUT_DIR
            settings.COMPRESS_OUTPUT_DIR = 'custom'
            output = u'<script type="text/javascript" src="/media/custom/js/066cd253eada.js"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = ''
            output = u'<script type="text/javascript" src="/media/js/066cd253eada.js"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = '/custom/nested/'
            output = u'<script type="text/javascript" src="/media/custom/nested/js/066cd253eada.js"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
        finally:
            settings.COMPRESS_OUTPUT_DIR = old_output_dir
Exemplo n.º 25
0
    def test_js_content(self):
        js_node = JsCompressor(self.js)

        content = js_node.filter_input()
        self.assertEqual(content[0], ';obj = {};')
        self.assertEqual(content[1], ';pollos = {}')
Exemplo n.º 26
0
 def test_custom_output_dir3(self):
     output = '<script type="text/javascript" src="/static/custom/nested/js/74e158ccb432.js"></script>'
     self.assertEqual(output, JsCompressor(self.js).output())
Exemplo n.º 27
0
class CompressorGroupFirstTestCase(TestCase):
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/one.less" type="text/less" />
<link rel="stylesheet" href="/media/css/two.less" type="text/less" />"""
        self.css_node = CssCompressor(self.css)
        self.css_node.opts = {"group_first": "true"}

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>
<script src="/media/js/one.coffee" type="text/coffeescript"></script>
<script src="/media/js/two.coffee" type="text/coffeescript"></script>"""
        self.js_node = JsCompressor(self.js)

    def test_css_group(self):
        out = [
            [
                SOURCE_HUNK,
                u"body { background:#990; }p { border:5px solid green;}",
                u"css/one.css",
                u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" /><style type="text/css">p { border:5px solid green;}</style>',
            ],
            [
                SOURCE_HUNK,
                u"body { background:#990; }body { color:#fff; }",
                u"css/one.less",
                u'<link rel="stylesheet" href="/media/css/one.less" type="text/less" /><link rel="stylesheet" href="/media/css/two.less" type="text/less" />',
            ],
        ]
        split = self.css_node.group_contents()
        split = [[x[0], x[1], x[2], make_elems_str(self.css_node.parser, x[3])] for x in split]
        self.assertEqual(out, split)

    def test_css_single(self):
        css_node = CssCompressor("""<link rel="stylesheet" href="/media/css/one.css" type="text/css" />""")
        css_node.opts = {"group_first": "true"}
        out = [
            [
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, u"css", u"one.css"),
                u"css/one.css",
                u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" />',
            ]
        ]
        split = css_node.group_contents()
        split = [[x[0], x[1], x[2], make_elems_str(self.css_node.parser, x[3])] for x in split]
        self.assertEqual(out, split)

    def test_js_group(self):
        out = [
            [
                SOURCE_HUNK,
                u'obj = {};obj.value = "value";',
                u"js/one.js",
                '<script src="/media/js/one.js" type="text/javascript"></script><script type="text/javascript">obj.value = "value";</script>',
            ],
            [
                SOURCE_HUNK,
                u"# this is a comment.\n# this is a comment.",
                u"js/one.coffee",
                '<script src="/media/js/one.coffee" type="text/coffeescript"></script><script src="/media/js/two.coffee" type="text/coffeescript"></script>',
            ],
        ]
        split = self.js_node.group_contents()
        split = [[x[0], x[1], x[2], make_elems_str(self.js_node.parser, x[3])] for x in split]
        self.assertEqual(out, split)
Exemplo n.º 28
0
 def test_custom_output_dir3(self):
     output = '<script src="/static/custom/nested/js/8a0fed36c317.js"></script>'
     self.assertEqual(output, JsCompressor('js', self.js).output())
Exemplo n.º 29
0
class CompressorTestCase(TestCase):
    def setUp(self):
        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_PRECOMPILERS = {}
        settings.COMPRESS_DEBUG_TOGGLE = "nocompress"
        self.css = """\
<link rel="stylesheet" href="/media/css/one.css" type="text/css" />
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/two.css" type="text/css" />"""
        self.css_node = CssCompressor(self.css)

        self.js = """\
<script src="/media/js/one.js" type="text/javascript"></script>
<script type="text/javascript">obj.value = "value";</script>"""
        self.js_node = JsCompressor(self.js)

    def test_css_split(self):
        out = [
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, u"css", u"one.css"),
                u"css/one.css",
                u'<link rel="stylesheet" href="/media/css/one.css" type="text/css" />',
            ),
            (
                SOURCE_HUNK,
                u"p { border:5px solid green;}",
                None,
                u'<style type="text/css">p { border:5px solid green;}</style>',
            ),
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, u"css", u"two.css"),
                u"css/two.css",
                u'<link rel="stylesheet" href="/media/css/two.css" type="text/css" />',
            ),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], x[2], self.css_node.parser.elem_str(x[3][0])) for x in split]
        self.assertEqual(out, split)

    def test_css_hunks(self):
        out = ["body { background:#990; }", u"p { border:5px solid green;}", "body { color:#fff; }"]
        self.assertEqual(out, list(self.css_node.hunks()))

    def test_css_output(self):
        out = u"body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }"
        hunks = "\n".join([h for h in self.css_node.hunks()])
        self.assertEqual(out, hunks)

    def test_css_mtimes(self):
        is_date = re.compile(r"^\d{10}[\.\d]+$")
        for date in self.css_node.mtimes:
            self.assertTrue(
                is_date.match(str(float(date))),
                "mtimes is returning something that doesn't look like a date: %s" % date,
            )

    def test_css_return_if_off(self):
        settings.COMPRESS_ENABLED = False
        self.assertEqual(self.css, self.css_node.output())

    def test_cachekey(self):
        is_cachekey = re.compile(r"\w{12}")
        self.assertTrue(
            is_cachekey.match(self.css_node.cachekey),
            "cachekey is returning something that doesn't look like r'\w{12}'",
        )

    def test_css_return_if_on(self):
        output = css_tag("/media/CACHE/css/e41ba2cc6982.css")
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_split(self):
        out = [
            (
                SOURCE_FILE,
                os.path.join(settings.COMPRESS_ROOT, u"js", u"one.js"),
                u"js/one.js",
                '<script src="/media/js/one.js" type="text/javascript"></script>',
            ),
            (
                SOURCE_HUNK,
                u'obj.value = "value";',
                None,
                '<script type="text/javascript">obj.value = "value";</script>',
            ),
        ]
        split = self.js_node.split_contents()
        split = [(x[0], x[1], x[2], self.js_node.parser.elem_str(x[3][0])) for x in split]
        self.assertEqual(out, split)

    def test_js_hunks(self):
        out = ["obj = {};", u'obj.value = "value";']
        self.assertEqual(out, list(self.js_node.hunks()))

    def test_js_output(self):
        out = u'<script type="text/javascript" src="/media/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_js_override_url(self):
        self.js_node.context.update({"url": u"This is not a url, just a text"})
        out = u'<script type="text/javascript" src="/media/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(out, self.js_node.output())

    def test_css_override_url(self):
        self.css_node.context.update({"url": u"This is not a url, just a text"})
        output = css_tag("/media/CACHE/css/e41ba2cc6982.css")
        self.assertEqual(output, self.css_node.output().strip())

    def test_js_return_if_off(self):
        try:
            enabled = settings.COMPRESS_ENABLED
            precompilers = settings.COMPRESS_PRECOMPILERS
            settings.COMPRESS_ENABLED = False
            settings.COMPRESS_PRECOMPILERS = {}
            self.assertEqual(self.js, self.js_node.output())
        finally:
            settings.COMPRESS_ENABLED = enabled
            settings.COMPRESS_PRECOMPILERS = precompilers

    def test_js_return_if_on(self):
        output = u'<script type="text/javascript" src="/media/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(output, self.js_node.output())

    def test_custom_output_dir(self):
        try:
            old_output_dir = settings.COMPRESS_OUTPUT_DIR
            settings.COMPRESS_OUTPUT_DIR = "custom"
            output = u'<script type="text/javascript" src="/media/custom/js/066cd253eada.js"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = ""
            output = u'<script type="text/javascript" src="/media/js/066cd253eada.js"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
            settings.COMPRESS_OUTPUT_DIR = "/custom/nested/"
            output = u'<script type="text/javascript" src="/media/custom/nested/js/066cd253eada.js"></script>'
            self.assertEqual(output, JsCompressor(self.js).output())
        finally:
            settings.COMPRESS_OUTPUT_DIR = old_output_dir
Exemplo n.º 30
0
 def test_custom_output_dir2(self):
     output = '<script type="text/javascript" src="/static/js/066cd253eada.js"></script>'
     self.assertEqual(output, JsCompressor(self.js).output())