Example #1
0
    def test_format_lazy(self):
        self.assertEqual('djmodels/test',
                         format_lazy('{}/{}', 'djmodels', lazystr('test')))
        self.assertEqual('djmodels/test',
                         format_lazy('{0}/{1}', *('djmodels', 'test')))
        self.assertEqual(
            'djmodels/test',
            format_lazy('{a}/{b}', **{
                'a': 'djmodels',
                'b': 'test'
            }))
        self.assertEqual('djmodels/test',
                         format_lazy('{a[0]}/{a[1]}', a=('djmodels', 'test')))

        t = {}
        s = format_lazy('{0[a]}-{p[a]}', t, p=t)
        t['a'] = lazystr('djmodels')
        self.assertEqual('djmodels-djmodels', s)
        t['a'] = 'update'
        self.assertEqual('update-update', s)

        # The format string can be lazy. (string comes from contrib.admin)
        s = format_lazy(
            gettext_lazy("Added {name} \"{object}\"."),
            name='article',
            object='My first try',
        )
        with override('fr'):
            self.assertEqual('Ajout de article «\xa0My first try\xa0».', s)
Example #2
0
 def test_json_script(self):
     tests = (
         # "<", ">" and "&" are quoted inside JSON strings
         (('&<>',
           '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>'
           )),
         # "<", ">" and "&" are quoted inside JSON objects
         ({
             'a': '<script>test&ing</script>'
         }, '<script id="test_id" type="application/json">'
          '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>'
          ),
         # Lazy strings are quoted
         (lazystr('&<>'),
          '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>'
          ),
         ({
             'a': lazystr('<script>test&ing</script>')
         }, '<script id="test_id" type="application/json">'
          '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>'
          ),
     )
     for arg, expected in tests:
         with self.subTest(arg=arg):
             self.assertEqual(json_script(arg, 'test_id'), expected)
Example #3
0
    def test_add_lazy_safe_text_and_safe_text(self):
        s = html.escape(lazystr('a'))
        s += mark_safe('&b')
        self.assertRenderEqual('{{ s }}', 'a&b', s=s)

        s = html.escapejs(lazystr('a'))
        s += mark_safe('&b')
        self.assertRenderEqual('{{ s }}', 'a&b', s=s)
Example #4
0
 def test_smart_split(self):
     testdata = [
         ('This is "a person" test.', ['This', 'is', '"a person"',
                                       'test.']),
         ('This is "a person\'s" test.',
          ['This', 'is', '"a person\'s"', 'test.']),
         ('This is "a person\\"s" test.',
          ['This', 'is', '"a person\\"s"', 'test.']),
         ('"a \'one', ['"a', "'one"]),
         ('all friends\' tests', ['all', 'friends\'', 'tests']),
         ('url search_page words="something else"',
          ['url', 'search_page', 'words="something else"']),
         ("url search_page words='something else'",
          ['url', 'search_page', "words='something else'"]),
         ('url search_page words "something else"',
          ['url', 'search_page', 'words', '"something else"']),
         ('url search_page words-"something else"',
          ['url', 'search_page', 'words-"something else"']),
         ('url search_page words=hello',
          ['url', 'search_page', 'words=hello']),
         ('url search_page words="something else',
          ['url', 'search_page', 'words="something', 'else']),
         ("cut:','|cut:' '", ["cut:','|cut:' '"]),
         (
             lazystr("a b c d"),  # Test for #20231
             ['a', 'b', 'c', 'd']),
     ]
     for test, expected in testdata:
         self.assertEqual(list(text.smart_split(test)), expected)
Example #5
0
 def test_strip_tags(self):
     items = (
         ('<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>',
          'See: &#39;&eacute; is an apostrophe followed by e acute'),
         ('<adf>a', 'a'),
         ('</adf>a', 'a'),
         ('<asdf><asdf>e', 'e'),
         ('hi, <f x', 'hi, <f x'),
         ('234<235, right?', '234<235, right?'),
         ('a4<a5 right?', 'a4<a5 right?'),
         ('b7>b2!', 'b7>b2!'),
         ('</fe', '</fe'),
         ('<x>b<y>', 'b'),
         ('a<p onclick="alert(\'<test>\')">b</p>c', 'abc'),
         ('a<p a >b</p>c', 'abc'),
         ('d<a:b c:d>e</p>f', 'def'),
         ('<strong>foo</strong><a href="http://example.com">bar</a>',
          'foobar'),
         # caused infinite loop on Pythons not patched with
         # http://bugs.python.org/issue20288
         ('&gotcha&#;<>', '&gotcha&#;<>'),
         ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'),
         ('<script>alert()</script>&h', 'alert()h'),
     )
     for value, output in items:
         with self.subTest(value=value, output=output):
             self.check_output(strip_tags, value, output)
             self.check_output(strip_tags, lazystr(value), output)
Example #6
0
 def test_normalize_newlines(self):
     self.assertEqual(text.normalize_newlines("abc\ndef\rghi\r\n"),
                      "abc\ndef\nghi\n")
     self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n")
     self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi")
     self.assertEqual(text.normalize_newlines(""), "")
     self.assertEqual(text.normalize_newlines(lazystr("abc\ndef\rghi\r\n")),
                      "abc\ndef\nghi\n")
Example #7
0
    def test_strip_spaces_between_tags(self):
        # Strings that should come out untouched.
        items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>')
        for value in items:
            with self.subTest(value=value):
                self.check_output(strip_spaces_between_tags, value)
                self.check_output(strip_spaces_between_tags, lazystr(value))

        # Strings that have spaces to strip.
        items = (
            ('<d> </d>', '<d></d>'),
            ('<p>hello </p>\n<p> world</p>', '<p>hello </p><p> world</p>'),
            ('\n<p>\t</p>\n<p> </p>\n', '\n<p></p><p></p>\n'),
        )
        for value, output in items:
            with self.subTest(value=value, output=output):
                self.check_output(strip_spaces_between_tags, value, output)
                self.check_output(strip_spaces_between_tags, lazystr(value),
                                  output)
Example #8
0
 def test_unescape_string_literal(self):
     items = [
         ('"abc"', 'abc'),
         ("'abc'", 'abc'),
         ('"a \"bc\""', 'a "bc"'),
         ("'\'ab\' c'", "'ab' c"),
     ]
     for value, output in items:
         self.assertEqual(text.unescape_string_literal(value), output)
         self.assertEqual(text.unescape_string_literal(lazystr(value)),
                          output)
Example #9
0
 def test_truncate_words(self):
     truncator = text.Truncator(
         'The quick brown fox jumped over the lazy dog.')
     self.assertEqual('The quick brown fox jumped over the lazy dog.',
                      truncator.words(10))
     self.assertEqual('The quick brown fox...', truncator.words(4))
     self.assertEqual('The quick brown fox[snip]',
                      truncator.words(4, '[snip]'))
     # lazy strings are handled correctly
     truncator = text.Truncator(
         lazystr('The quick brown fox jumped over the lazy dog.'))
     self.assertEqual('The quick brown fox...', truncator.words(4))
Example #10
0
 def test_urlize(self):
     tests = (
         ('Search for google.com/?q=! and see.',
          'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and see.'
          ),
         (lazystr('Search for google.com/?q=!'),
          'Search for <a href="http://google.com/?q=">google.com/?q=</a>!'),
         ('*****@*****.**',
          '<a href="mailto:[email protected]">[email protected]</a>'),
     )
     for value, output in tests:
         with self.subTest(value=value):
             self.assertEqual(urlize(value), output)
Example #11
0
 def test_unescape_entities(self):
     items = [
         ('', ''),
         ('foo', 'foo'),
         ('&amp;', '&'),
         ('&#x26;', '&'),
         ('&#38;', '&'),
         ('foo &amp; bar', 'foo & bar'),
         ('foo & bar', 'foo & bar'),
     ]
     for value, output in items:
         self.assertEqual(text.unescape_entities(value), output)
         self.assertEqual(text.unescape_entities(lazystr(value)), output)
Example #12
0
 def test_linebreaks(self):
     items = (
         ("para1\n\npara2\r\rpara3",
          "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"),
         ("para1\nsub1\rsub2\n\npara2",
          "<p>para1<br>sub1<br>sub2</p>\n\n<p>para2</p>"),
         ("para1\r\n\r\npara2\rsub1\r\rpara4",
          "<p>para1</p>\n\n<p>para2<br>sub1</p>\n\n<p>para4</p>"),
         ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"),
     )
     for value, output in items:
         with self.subTest(value=value, output=output):
             self.check_output(linebreaks, value, output)
             self.check_output(linebreaks, lazystr(value), output)
Example #13
0
    def test_wrap(self):
        digits = '1234 67 9'
        self.assertEqual(text.wrap(digits, 100), '1234 67 9')
        self.assertEqual(text.wrap(digits, 9), '1234 67 9')
        self.assertEqual(text.wrap(digits, 8), '1234 67\n9')

        self.assertEqual(text.wrap('short\na long line', 7),
                         'short\na long\nline')
        self.assertEqual(text.wrap('do-not-break-long-words please? ok', 8),
                         'do-not-break-long-words\nplease?\nok')

        long_word = 'l%sng' % ('o' * 20)
        self.assertEqual(text.wrap(long_word, 20), long_word)
        self.assertEqual(text.wrap('a %s word' % long_word, 10),
                         'a\n%s\nword' % long_word)
        self.assertEqual(text.wrap(lazystr(digits), 100), '1234 67 9')
Example #14
0
 def test_escapejs(self):
     items = (
         ('"double quotes" and \'single quotes\'',
          '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
         (r'\ : backslashes, too', '\\u005C : backslashes, too'),
         ('and lots of whitespace: \r\n\t\v\f\b',
          'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'
          ),
         (r'<script>and this</script>',
          '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
         ('paragraph separator:\u2029and line separator:\u2028',
          'paragraph separator:\\u2029and line separator:\\u2028'),
         ('`', '\\u0060'),
     )
     for value, output in items:
         with self.subTest(value=value, output=output):
             self.check_output(escapejs, value, output)
             self.check_output(escapejs, lazystr(value), output)
Example #15
0
    def test_truncate_chars(self):
        truncator = text.Truncator(
            'The quick brown fox jumped over the lazy dog.')
        self.assertEqual('The quick brown fox jumped over the lazy dog.',
                         truncator.chars(100)),
        self.assertEqual('The quick brown fox ...', truncator.chars(23)),
        self.assertEqual('The quick brown fo.....',
                         truncator.chars(23, '.....')),

        nfc = text.Truncator('o\xfco\xfco\xfco\xfc')
        nfd = text.Truncator('ou\u0308ou\u0308ou\u0308ou\u0308')
        self.assertEqual('oüoüoüoü', nfc.chars(8))
        self.assertEqual('oüoüoüoü', nfd.chars(8))
        self.assertEqual('oü...', nfc.chars(5))
        self.assertEqual('oü...', nfd.chars(5))

        # Ensure the final length is calculated correctly when there are
        # combining characters with no precomposed form, and that combining
        # characters are not split up.
        truncator = text.Truncator('-B\u030AB\u030A----8')
        self.assertEqual('-B\u030A...', truncator.chars(5))
        self.assertEqual('-B\u030AB\u030A-...', truncator.chars(7))
        self.assertEqual('-B\u030AB\u030A----8', truncator.chars(8))

        # Ensure the length of the end text is correctly calculated when it
        # contains combining characters with no precomposed form.
        truncator = text.Truncator('-----')
        self.assertEqual('---B\u030A', truncator.chars(4, 'B\u030A'))
        self.assertEqual('-----', truncator.chars(5, 'B\u030A'))

        # Make a best effort to shorten to the desired length, but requesting
        # a length shorter than the ellipsis shouldn't break
        self.assertEqual('...', text.Truncator('asdf').chars(1))
        # lazy strings are handled correctly
        self.assertEqual(
            text.Truncator(lazystr('The quick brown fox')).chars(12),
            'The quick...')
Example #16
0
 def test_escape(self):
     items = (
         ('&', '&amp;'),
         ('<', '&lt;'),
         ('>', '&gt;'),
         ('"', '&quot;'),
         ("'", '&#39;'),
     )
     # Substitution patterns for testing the above items.
     patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb")
     for value, output in items:
         with self.subTest(value=value, output=output):
             for pattern in patterns:
                 with self.subTest(value=value,
                                   output=output,
                                   pattern=pattern):
                     self.check_output(escape, pattern % value,
                                       pattern % output)
                     self.check_output(escape, lazystr(pattern % value),
                                       pattern % output)
             # Check repeated values.
             self.check_output(escape, value * 2, output * 2)
     # Verify it doesn't double replace &.
     self.check_output(escape, '<&', '&lt;&amp;')
Example #17
0
    def test_mark_safe_lazy(self):
        s = lazystr('a&b')

        self.assertIsInstance(mark_safe(s), SafeData)
        self.assertRenderEqual('{{ s }}', 'a&b', s=mark_safe(s))
Example #18
0
 def test_phone2numeric(self):
     numeric = text.phone2numeric('0800 flowers')
     self.assertEqual(numeric, '0800 3569377')
     lazy_numeric = lazystr(text.phone2numeric('0800 flowers'))
     self.assertEqual(lazy_numeric, '0800 3569377')
Example #19
0
 def test_get_valid_filename(self):
     filename = "^&'@{}[],$=!-#()%+~_123.txt"
     self.assertEqual(text.get_valid_filename(filename), "-_123.txt")
     self.assertEqual(text.get_valid_filename(lazystr(filename)),
                      "-_123.txt")
Example #20
0
 def test_conditional_escape(self):
     s = '<h1>interop</h1>'
     self.assertEqual(conditional_escape(s), '&lt;h1&gt;interop&lt;/h1&gt;')
     self.assertEqual(conditional_escape(mark_safe(s)), s)
     self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s)
Example #21
0
 def test_mark_safe_lazy_result_implements_dunder_html(self):
     self.assertEqual(mark_safe(lazystr('a&b')).__html__(), 'a&b')