s = escape(s)
else:
s = soft_unicode(s)
- return s.replace(old, new, count)
+ return s.replace(soft_unicode(old), soft_unicode(new), count)
def do_upper(s):
"""
__slots__ = ()
+ def __new__(cls, base=u''):
+ if hasattr(base, '__html__'):
+ base = base.__html__()
+ return unicode.__new__(cls, base)
+
def __html__(self):
return self
unit test for the filters
~~~~~~~~~~~~~~~~~~~~~~~~~
- Missing tests:
-
- - wordcount
- - rst
- - markdown
- - textile
-
- :copyright: 2007 by Armin Ronacher.
+ :copyright: 2008 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
-from jinja2 import Markup
+from jinja2 import Markup, Environment
+
CAPITALIZE = '''{{ "foo bar"|capitalize }}'''
CENTER = '''{{ "foo"|center(9) }}'''
out = tmpl.render()
assert out == '1|2|3'
+ env2 = Environment(autoescape=True)
+ tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')
+ assert tmpl.render() == '<foo><span>foo</span>'
+
def test_last(env):
tmpl = env.from_string(LAST)
assert tmpl.render() == 'fooBAR'
-def test_replace(env):
- tmpl = env.from_string('{{ "foo"|replace("o", 42)}}')
- assert tmpl.render() == 'f4242'
+def test_replace():
+ env = Environment()
+ tmpl = env.from_string('{{ string|replace("o", 42) }}')
+ assert tmpl.render(string='<foo>') == '<f4242>'
+
+ env = Environment(autoescape=True)
+ tmpl = env.from_string('{{ string|replace("o", 42) }}')
+ assert tmpl.render(string='<foo>') == '<f4242>'
+ tmpl = env.from_string('{{ string|replace("<", 42) }}')
+ assert tmpl.render(string='<foo>') == '42foo>'
+ tmpl = env.from_string('{{ string|replace("o", ">x<") }}')
+ assert tmpl.render(string=Markup('foo')) == 'f>x<>x<'
def test_forceescape(env):
"""
from jinja2.sandbox import SandboxedEnvironment, \
ImmutableSandboxedEnvironment, unsafe
+from jinja2 import Markup, escape
class PrivateStuff(object):
...
SecurityError: access to attribute 'clear' of 'dict' object is unsafe.
'''
+
+def test_markup_operations():
+ # adding two strings should escape the unsafe one
+ unsafe = '<script type="application/x-some-script">alert("foo");</script>'
+ safe = Markup('<em>username</em>')
+ assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)
+
+ # string interpolations are safe to use too
+ assert Markup('<em>%s</em>') % '<bad user>' == \
+ '<em><bad user></em>'
+ assert Markup('<em>%(username)s</em>') % {
+ 'username': '<bad user>'
+ } == '<em><bad user></em>'
+
+ # an escaped object is markup too
+ assert type(Markup('foo') + 'bar') is Markup
+
+ # and it implements __html__ by returning itself
+ x = Markup("foo")
+ assert x.__html__() is x
+
+ # it also knows how to treat __html__ objects
+ class Foo(object):
+ def __html__(self):
+ return '<em>awesome</em>'
+ def __unicode__(self):
+ return 'awesome'
+ assert Markup(Foo()) == '<em>awesome</em>'
+ assert Markup('<strong>%s</strong>') % Foo() == \
+ '<strong><em>awesome</em></strong>'