Example #1
0
 def test_tint_django_jinja_global_function(self):
     context = Context({ "image": self.image })
     result = env.from_string("{{ image_at_transformation(image, 'test1') }}").render(context)
     self.assertEqual(result, reverse('image-thumbnail', args=(self.image.id, 'test1')))
     self.image.get_absolute_url('test1', True)
     result = env.from_string("{{ image_at_transformation(image, 'test1') }}").render(context)
     self.assertEqual(result, '/media/image/thumbnail/by-md5/3/f/3fe2d799fd59ef5a9c6b057eb546bed5/test-image.png')
Example #2
0
    def test_template_sites_url_functions(self):
        url = env.from_string("{{ sites_url('foo') }}").render({})
        self.assertEqual(url, "http://example2.com/foo")

        url = env.from_string("{{ sites_url('foo', site_id='foo') }}").render(
            {})
        self.assertEqual(url, "https://example1.com/foo")
Example #3
0
    def test_template_static_url_functions(self):
        url = env.from_string("{{ sites_static('lib.js') }}").render({})
        self.assertEqual(url, "http://example2.com/static/lib.js")

        url = env.from_string(
            "{{ sites_static('libs.js', site_id='foo') }}").render({})
        self.assertEqual(url, "https://example1.com/static/libs.js")
Example #4
0
 def test_sr_django_jinja_global_function(self):
     result = env.from_string("{{ sr('test1') }}").render()
     self.assertEqual(result, 'Test1')
     result = env.from_string("{{ sr('test2.test3') }}").render()
     self.assertEqual(result, 'Test3')
     result = env.from_string("{{ sr('test4.test4', 'testing', 'testing2') }}").render()
     self.assertEqual(result, 'Test4 testing testing2')
Example #5
0
 def test_sr_django_jinja_global_function(self):
     result = env.from_string("{{ sr('test1') }}").render()
     self.assertEqual(result, 'Test1')
     result = env.from_string("{{ sr('test2.test3') }}").render()
     self.assertEqual(result, 'Test3')
     result = env.from_string(
         "{{ sr('test4.test4', 'testing', 'testing2') }}").render()
     self.assertEqual(result, 'Test4 testing testing2')
Example #6
0
 def test_tint_django_jinja_global_function(self):
     context = Context({"image": self.image})
     result = env.from_string("{{ image_at_transformation(image, 'test1') }}").render(context)
     self.assertEqual(result, reverse('image-thumbnail', args=(self.image.id, 'test1')))
     self.image.get_absolute_url('test1', True)
     result = env.from_string("{{ image_at_transformation(image, 'test1') }}").render(context)
     self.assertIsNotNone(re.search(
         '/media/image/thumbnail/by-md5/[a-f0-9]/[a-f0-9]/[a-f0-9]{32}/test-image.png',
         result
     ))
Example #7
0
 def test_tint_django_jinja_global_function(self):
     context = Context({"image": self.image})
     result = env.from_string(
         "{{ image_at_transformation(image, 'test1') }}").render(context)
     self.assertEqual(
         result, reverse('image-thumbnail', args=(self.image.id, 'test1')))
     self.image.get_absolute_url('test1', True)
     result = env.from_string(
         "{{ image_at_transformation(image, 'test1') }}").render(context)
     self.assertIsNotNone(
         re.search(
             '/media/image/thumbnail/by-md5/[a-f0-9]/[a-f0-9]/[a-f0-9]{32}/test-image.png',
             result))
Example #8
0
    def test_autoscape_with_form_field(self):
        form = TestForm()
        template = env.from_string("{{ form.name }}")
        result = template.render({"form": form})

        self.assertIn('maxlength="2"', result)
        self.assertIn("/>", result)
Example #9
0
    def test_autoscape_with_form(self):
        form = TestForm()
        template = env.from_string("{{ form.as_p() }}")
        result = template.render({"form": form})

        self.assertIn('maxlength="2"', result)
        self.assertIn("/>", result)
Example #10
0
    def test_pipeline_js_safe(self):
        template = env.from_string("{{ compressed_js('test') }}")
        result = template.render({})

        self.assertTrue(result.startswith("<script"))
        self.assertIn("text/javascript", result)
        self.assertIn("/static/script.2.js", result)
Example #11
0
    def test_template_filters(self):
        filters_data = [
            ("{{ 'test-1'|reverseurl }}", {}, "/test1/"),
            ("{{ 'test-1'|reverseurl(data=2) }}", {}, "/test1/2/"),
            ("{{ num|floatformat }}", {"num": 34.23234}, "34.2"),
            ("{{ num|floatformat(3) }}", {"num": 34.23234}, "34.232"),
            ("{{ 'hola'|capfirst }}", {}, "Hola"),
            ("{{ 'hola mundo'|truncatechars(5) }}", {}, "ho..."),
            ("{{ 'hola mundo'|truncatewords(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|truncatewords_html(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|wordwrap(1) }}", {}, "hola\nmundo"),
            ("{{ 'hola mundo'|title }}", {}, "Hola Mundo"),
            ("{{ 'hola mundo'|slugify }}", {}, "hola-mundo"),
            ("{{ 'hello'|ljust(10) }}", {}, "hello     "),
            ("{{ 'hello'|rjust(10) }}", {}, "     hello"),
            ("{{ 'hello\nworld'|linebreaksbr }}", {}, "hello<br />world"),
            ("{{ '<div>hello</div>'|removetags('div') }}", {}, "hello"),
            ("{{ '<div>hello</div>'|striptags }}", {}, "hello"),
            ("{{ list|join(',') }}", {"list": ["a", "b"]}, "a,b"),
            ("{{ 3|add(2) }}", {}, "5"),
            ("{{ now|date('n Y') }}", {"now": datetime.datetime(2012, 12, 20)}, "12 2012"),
        ]

        print()
        for template_str, kwargs, result in filters_data:
            print("- Testing: ", template_str, "with:", kwargs)

            template = env.from_string(template_str)
            _result = template.render(kwargs)
            self.assertEqual(_result, result)
Example #12
0
 def test_pipeline_js_safe(self):
     template = env.from_string("{{ compressed_js('test') }}")
     result = template.render({})
     self.assertEqual(
         result,
         '<script type="application/javascript" src="/static/script.2.js" charset="utf-8"></script>'
     )
Example #13
0
 def test_pipeline_css_safe(self):
     template = env.from_string("{{ compressed_css('test') }}")
     result = template.render({})
     self.assertEqual(
         result,
         '<link href="/static/style.2.css" rel="stylesheet" type="text/css" />'
     )
Example #14
0
 def test_pipeline_css_safe_02(self):
     template = env.from_string("{{ compressed_css('test2') }}")
     result = template.render({})
     self.assertNotIn("media", result)
     self.assertIn("stylesheet", result)
     self.assertIn("<link", result)
     self.assertIn("/static/style.2.css", result)
Example #15
0
    def test_template_filters(self):
        filters_data = [
            ("{{ 'test-static.css'|static }}", {}, '/static/test-static.css'),
            ("{{ 'test-1'|reverseurl }}", {}, '/test1/'),
            ("{{ 'test-1'|reverseurl(data=2) }}", {}, '/test1/2/'),
            ("{{ num|floatformat }}", {'num': 34.23234}, '34.2'),
            ("{{ num|floatformat(3) }}", {'num': 34.23234}, '34.232'),
            ("{{ 'hola'|capfirst }}", {}, "Hola"),
            ("{{ 'hola mundo'|truncatechars(5) }}", {}, "ho..."),
            ("{{ 'hola mundo'|truncatewords(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|truncatewords_html(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|wordwrap(1) }}", {}, "hola\nmundo"),
            ("{{ 'hola mundo'|title }}", {}, "Hola Mundo"),
            ("{{ 'hola mundo'|slugify }}", {}, "hola-mundo"),
            ("{{ 'hello'|ljust(10) }}", {}, "hello     "),
            ("{{ 'hello'|rjust(10) }}", {}, "     hello"),
            ("{{ 'hello\nworld'|linebreaksbr }}", {}, "hello<br />world"),
            ("{{ '<div>hello</div>'|removetags('div') }}", {}, "hello"),
            ("{{ '<div>hello</div>'|striptags }}", {}, "hello"),
            ("{{ list|join(',') }}", {'list':['a','b']}, 'a,b'),
            ("{{ 3|add(2) }}", {}, "5"),
            ("{{ now|date('n Y') }}", {"now": datetime.datetime(2012, 12, 20)}, "12 2012"),
        ]

        print()
        for template_str, kwargs, result in filters_data:
            print("- Testing: ", template_str, "with:", kwargs)
            template = env.from_string(template_str)
            _result = template.render(kwargs)
            self.assertEqual(_result, result)
Example #16
0
    def load_jinja2_template_source(self, template, template_name):
        if django_jinja:
            template = env.from_string(template.get_content())
            return template, template_name
        else:
            from .j2.exceptions import DjangoJinjaNotInstalled

            raise DjangoJinjaNotInstalled
Example #17
0
    def test_autoscape_with_form_errors(self):
        form = TestForm({"name": "foo"})
        self.assertFalse(form.is_valid())

        template = env.from_string("{{ form.name.errors }}")
        result = template.render({"form": form})

        self.assertEqual(result,
                         ("""<ul class="errorlist"><li>Ensure this value """
                          """has at most 2 characters (it has 3).</li></ul>"""))

        template = env.from_string("{{ form.errors }}")
        result = template.render({"form": form})

        self.assertEqual(result,
                         ("""<ul class="errorlist"><li>name<ul class="errorlist">"""
                          """<li>Ensure this value has at most 2 characters (it """
                          """has 3).</li></ul></li></ul>"""))
Example #18
0
    def test_autoescape_02(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo }}")
        result = template.render({'foo': '<h1>Hellp</h1>'})
        self.assertEqual(result, "&lt;h1&gt;Hellp&lt;/h1&gt;")

        env.autoescape = old_autoescape_value
Example #19
0
    def test_autoscape_with_form_errors(self):
        form = TestForm({"name": "foo"})
        self.assertFalse(form.is_valid())

        template = env.from_string("{{ form.name.errors }}")
        result = template.render({"form": form})

        self.assertEqual(result,
                         ("""<ul class="errorlist"><li>Ensure this value """
                          """has at most 2 characters (it has 3).</li></ul>"""))

        template = env.from_string("{{ form.errors }}")
        result = template.render({"form": form})

        self.assertEqual(result,
                         ("""<ul class="errorlist"><li>name<ul class="errorlist">"""
                          """<li>Ensure this value has at most 2 characters (it """
                          """has 3).</li></ul></li></ul>"""))
Example #20
0
    def test_autoescape_01(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo|safe }}")
        result = template.render({"foo": "<h1>Hellp</h1>"})
        self.assertEqual(result, "<h1>Hellp</h1>")

        env.autoescape = old_autoescape_value
Example #21
0
    def test_autoescape_02(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo }}")
        result = template.render({"foo": "<h1>Hellp</h1>"})
        self.assertEqual(result, "&lt;h1&gt;Hellp&lt;/h1&gt;")

        env.autoescape = old_autoescape_value
Example #22
0
    def test_autoescape_01(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo|safe }}")
        result = template.render({'foo': '<h1>Hellp</h1>'})
        self.assertEqual(result, "<h1>Hellp</h1>")

        env.autoescape = old_autoescape_value
Example #23
0
    def test_cache_01(self):
        template_content = "{% cache 200 'fooo' %}foo bar{% endcache %}"

        request = self.factory.get("/customer/details")
        context = dict_from_context(RequestContext(request))

        template = env.from_string(template_content)
        result = template.render(context)

        self.assertEqual(result, "foo bar")
Example #24
0
    def test_csrf_01(self):
        template_content = "{% csrf_token %}"

        request = self.factory.get('/customer/details')
        if sys.version_info[0] < 3:
            request.META["CSRF_COOKIE"] = b'1234123123'
        else:
            request.META["CSRF_COOKIE"] = '1234123123'

        if django.VERSION[:2] >= (1, 8):
            template = env.from_string(template_content)
            result = template.render({}, request)

        else:
            context = dict_from_context(RequestContext(request))
            template = env.from_string(template_content)
            result = template.render(context)

        self.assertEqual(result, "<input type='hidden' name='csrfmiddlewaretoken' value='1234123123' />")
Example #25
0
    def test_cache_01(self):
        template_content = "{% cache 200 'fooo' %}foo bar{% endcache %}"

        request = self.factory.get('/customer/details')
        context = dict_from_context(RequestContext(request))

        template = env.from_string(template_content)
        result = template.render(context)

        self.assertEqual(result, "foo bar")
Example #26
0
    def test_autoscape_with_form(self):
        form = TestForm()
        template = env.from_string("{{ form.as_p() }}")
        result = template.render({"form": form})

        self.assertEqual(
            result,
            (
                """<p><label for="id_name">Name:</label> """
                """<input id="id_name" maxlength="2" """
                """name="name" type="text" /></p>"""
            ),
        )
Example #27
0
    def as_template(self):
        if self.template_engine in [Template.DJANGO]:
            return self.template_engine_class(self.get_content())
        elif self.template_engine in [Template.JINJA2]:
            if django_jinja:
                # Make sure the loader is initialized. django-jinja doesn't automatically
                # handle the initialization in Django 1.7
                if not env.loader:
                    env.initialize_template_loader()

                return env.from_string(self.get_content())
            else:
                from .j2.exceptions import DjangoJinjaNotInstalled
                raise DjangoJinjaNotInstalled
Example #28
0
    def test_csrf_01(self):
        template_content = "{% csrf_token %}"

        request = self.factory.get("/customer/details")
        if sys.version_info.major < 3:
            request.META["CSRF_COOKIE"] = b"1234123123"
        else:
            request.META["CSRF_COOKIE"] = "1234123123"

        context = dict_from_context(RequestContext(request))

        template = env.from_string(template_content)
        result = template.render(context)
        self.assertEqual(result, "<input type='hidden' name='csrfmiddlewaretoken' value='1234123123' />")
Example #29
0
    def test_custom_addons_02(self):
        template = env.from_string("{% if m is one %}Foo{% endif %}")
        result = template.render({"m": 1})

        self.assertEqual(result, "Foo")
Example #30
0
 def test_urlresolve_exceptions(self):
     template = env.from_string("{{ url('adads') }}")
     template.render({})
Example #31
0
    def test_custom_addons_01(self):
        template = env.from_string("{{ 'Hello'|replace('H','M') }}")
        result = template.render({})

        self.assertEqual(result, "Mello")
Example #32
0
 def test_autoescape_03(self):
     template = env.from_string("{{ foo|linebreaksbr }}")
     result = template.render({"foo": "<script>alert(1)</script>\nfoo"})
     self.assertEqual(result, "&lt;script&gt;alert(1)&lt;/script&gt;<br />foo")
Example #33
0
 def test_autoescape_jinja2_templates(self):
     result = env.from_string("{{ sr('test5.test5') }}").render()
     self.assertEqual(result, '<b>foo</b>')
Example #34
0
    def test_string_interpolation(self):
        template = env.from_string("{{ 'Hello %s!' % name }}")
        self.assertEqual(template.render({"name": "foo"}), "Hello foo!")

        template = env.from_string("{{ _('Hello %s!').format(name) }}")
        self.assertEqual(template.render({"name": "foo"}), "Hello foo!")
Example #35
0
    def test_custom_addons_03(self):
        template = env.from_string("{{ myecho('foo') }}")
        result = template.render({})

        self.assertEqual(result, "foo")
Example #36
0
 def test_pipeline_js_safe(self):
     template = env.from_string("{{ compressed_js('test') }}")
     result = template.render({})
     self.assertEqual(
         result, '<script type="application/javascript" src="/static/script.2.js" charset="utf-8"></script>'
     )
Example #37
0
 def test_pipeline_css_safe(self):
     template = env.from_string("{{ compressed_css('test') }}")
     result = template.render({})
     self.assertEqual(result, '<link href="/static/style.2.css" rel="stylesheet" type="text/css" />')
Example #38
0
    def test_template_static_url_functions(self):
        url = env.from_string("{{ sites_static('lib.js') }}").render({})
        self.assertEqual(url, "http://example2.com/static/lib.js")

        url = env.from_string("{{ sites_static('libs.js', site_id='foo') }}").render({})
        self.assertEqual(url, "https://example1.com/static/libs.js")
Example #39
0
    def test_autoscape_with_form_field(self):
        form = TestForm()
        template = env.from_string("{{ form.name }}")
        result = template.render({"form": form})

        self.assertEqual(result, """<input id="id_name" maxlength="2" name="name" type="text" />""")
Example #40
0
 def test_autoescape_jinja2_templates(self):
     result = env.from_string("{{ sr('test5.test5') }}").render()
     self.assertEqual(result, '<b>foo</b>')
Example #41
0
    def test_template_sites_url_functions(self):
        url = env.from_string("{{ sites_url('foo') }}").render({})
        self.assertEqual(url, "http://example2.com/foo")

        url = env.from_string("{{ sites_url('foo', site_id='foo') }}").render({})
        self.assertEqual(url, "https://example1.com/foo")
Example #42
0
    def test_string_interpolation(self):
        template = env.from_string("{{ 'Hello %s!' % name }}")
        self.assertEqual(template.render({"name": "foo"}), "Hello foo!")

        template = env.from_string("{{ _('Hello %s!').format(name) }}")
        self.assertEqual(template.render({"name": "foo"}), "Hello foo!")
Example #43
0
    def test_custom_addons_03(self):
        template = env.from_string("{{ myecho('foo') }}")
        result = template.render({})

        self.assertEqual(result, "foo")
Example #44
0
 def test_urlresolve_exceptions(self):
     template = env.from_string("{{ url('adads') }}")
     template.render({})
Example #45
0
 def test_render_with(self):
     template = env.from_string("{{ myrenderwith() }}")
     result = template.render({})
     self.assertEqual(result, "<strong>Foo</strong>")
Example #46
0
 def test_render_with(self):
     template = env.from_string("{{ myrenderwith() }}")
     result = template.render({})
     self.assertEqual(result, "<strong>Foo</strong>")
Example #47
0
    def test_custom_addons_02(self):
        template = env.from_string("{% if m is one %}Foo{% endif %}")
        result = template.render({'m': 1})

        self.assertEqual(result, "Foo")
Example #48
0
    def test_custom_addons_01(self):
        template = env.from_string("{{ 'Hello'|replace('H','M') }}")
        result = template.render({})

        self.assertEqual(result, "Mello")