django.utils.functional.lazystr - python examples

Here are the examples of the python api django.utils.functional.lazystr taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

29 Examples 7

3 View Complete Implementation : test_wordwrap.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_wrap_lazy_string(self):
        self.astertEqual(
            wordwrap(lazystr(
                'this is a long paragraph of text that really needs to be wrapped I\'m afraid'
            ), 14),
            'this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI\'m afraid',
        )

3 View Complete Implementation : test_loaders.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_template_name_lazy_string(self):
        """
        #26603 -- A template name specified as a lazy string should be forced
        to text before computing its cache key.
        """
        self.astertEqual(self.engine.template_loaders[0].cache_key(lazystr('template.html'), []), 'template.html')

3 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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)

3 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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)

3 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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)

3 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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>!'
            ),
            ('[email protected]', '<a href="mailto:[email protected]">[email protected]</a>'),
        )
        for value, output in tests:
            with self.subTest(value=value):
                self.astertEqual(urlize(value), output)

3 View Complete Implementation : test_safestring.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_add_lazy_safe_text_and_safe_text(self):
        s = html.escape(lazystr('a'))
        s += mark_safe('&b')
        self.astertRenderEqual('{{ s }}', 'a&b', s=s)

        s = html.escapejs(lazystr('a'))
        s += mark_safe('&b')
        self.astertRenderEqual('{{ s }}', 'a&b', s=s)

        s = text.slugify(lazystr('a'))
        s += mark_safe('&b')
        self.astertRenderEqual('{{ s }}', 'a&b', s=s)

3 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_truncate_words(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.astertEqual('The quick brown fox jumped over the lazy dog.', truncator.words(10))
        self.astertEqual('The quick brown fox...', truncator.words(4))
        self.astertEqual('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.astertEqual('The quick brown fox...', truncator.words(4))

3 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_wrap(self):
        digits = '1234 67 9'
        self.astertEqual(text.wrap(digits, 100), '1234 67 9')
        self.astertEqual(text.wrap(digits, 9), '1234 67 9')
        self.astertEqual(text.wrap(digits, 8), '1234 67\n9')

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

        long_word = 'l%sng' % ('o' * 20)
        self.astertEqual(text.wrap(long_word, 20), long_word)
        self.astertEqual(text.wrap('a %s word' % long_word, 10), 'a\n%s\nword' % long_word)
        self.astertEqual(text.wrap(lazystr(digits), 100), '1234 67 9')

3 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_normalize_newlines(self):
        self.astertEqual(text.normalize_newlines("abc\ndef\rghi\r\n"), "abc\ndef\nghi\n")
        self.astertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n")
        self.astertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi")
        self.astertEqual(text.normalize_newlines(""), "")
        self.astertEqual(text.normalize_newlines(lazystr("abc\ndef\rghi\r\n")), "abc\ndef\nghi\n")

3 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_unescape_ensaties(self):
        items = [
            ('', ''),
            ('foo', 'foo'),
            ('&', '&'),
            ('&', '&'),
            ('&', '&'),
            ('foo & bar', 'foo & bar'),
            ('foo & bar', 'foo & bar'),
        ]
        for value, output in items:
            self.astertEqual(text.unescape_ensaties(value), output)
            self.astertEqual(text.unescape_ensaties(lazystr(value)), output)

3 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertEqual(text.unescape_string_literal(value), output)
            self.astertEqual(text.unescape_string_literal(lazystr(value)), output)

3 View Complete Implementation : test_safestring.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_add_lazy_safe_text_and_safe_text(self):
        s = html.escape(lazystr('a'))
        s += mark_safe('&b')
        self.astertRenderEqual('{{ s }}', 'a&b', s=s)

        s = html.escapejs(lazystr('a'))
        s += mark_safe('&b')
        self.astertRenderEqual('{{ s }}', 'a&b', s=s)

3 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_truncate_words(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.astertEqual('The quick brown fox jumped over the lazy dog.', truncator.words(10))
        self.astertEqual('The quick brown fox…', truncator.words(4))
        self.astertEqual('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.astertEqual('The quick brown fox…', truncator.words(4))

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_lazy_content(self):
        r = HttpResponse(lazystr('helloworld'))
        self.astertEqual(r.content, b'helloworld')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_redirect_lazy(self):
        """Make sure HttpResponseRedirect works with lazy strings."""
        r = HttpResponseRedirect(lazystr('/redirected/'))
        self.astertEqual(r.url, '/redirected/')

0 View Complete Implementation : test_striptags.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_strip_lazy_string(self):
        self.astertEqual(
            striptags(lazystr('some <b>html</b> with <script>alert("Hello")</script> disallowed <img /> tags')),
            'some html with alert("Hello") disallowed  tags',
        )

0 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_escape(self):
        items = (
            ('&', '&'),
            ('<', '<'),
            ('>', '>'),
            ('"', '"'),
            ("'", '''),
        )
        # Subssatution 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, '<&', '<&')

0 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_strip_tags(self):
        items = (
            ('<p>See: 'é is an apostrophe followed by e acute</p>',
             'See: 'é 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
            # https://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)

0 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertEqual(json_script(arg, 'test_id'), expected)

0 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_conditional_escape(self):
        s = '<h1>interop</h1>'
        self.astertEqual(conditional_escape(s), '<h1>interop</h1>')
        self.astertEqual(conditional_escape(mark_safe(s)), s)
        self.astertEqual(conditional_escape(lazystr(mark_safe(s))), s)

0 View Complete Implementation : test_safestring.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_mark_safe_lazy(self):
        s = lazystr('a&b')

        self.astertIsInstance(mark_safe(s), SafeData)
        self.astertRenderEqual('{{ s }}', 'a&b', s=mark_safe(s))

0 View Complete Implementation : test_safestring.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_mark_safe_lazy_result_implements_dunder_html(self):
        self.astertEqual(mark_safe(lazystr('a&b')).__html__(), 'a&b')

0 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertEqual(list(text.smart_split(test)), expected)

0 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_truncate_chars(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.astertEqual('The quick brown fox jumped over the lazy dog.', truncator.chars(100)),
        self.astertEqual('The quick brown fox ...', truncator.chars(23)),
        self.astertEqual('The quick brown fo.....', truncator.chars(23, '.....')),

        nfc = text.Truncator('o\xfco\xfco\xfco\xfc')
        nfd = text.Truncator('ou\u0308ou\u0308ou\u0308ou\u0308')
        self.astertEqual('oüoüoüoü', nfc.chars(8))
        self.astertEqual('oüoüoüoü', nfd.chars(8))
        self.astertEqual('oü...', nfc.chars(5))
        self.astertEqual('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.astertEqual('-B\u030A...', truncator.chars(5))
        self.astertEqual('-B\u030AB\u030A-...', truncator.chars(7))
        self.astertEqual('-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.astertEqual('---B\u030A', truncator.chars(4, 'B\u030A'))
        self.astertEqual('-----', 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.astertEqual('...', text.Truncator('asdf').chars(1))
        # lazy strings are handled correctly
        self.astertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')

0 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_phone2numeric(self):
        numeric = text.phone2numeric('0800 flowers')
        self.astertEqual(numeric, '0800 3569377')
        lazy_numeric = lazystr(text.phone2numeric('0800 flowers'))
        self.astertEqual(lazy_numeric, '0800 3569377')

0 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_valid_filename(self):
        filename = "^&'@{}[],$=!-#()%+~_123.txt"
        self.astertEqual(text.get_valid_filename(filename), "-_123.txt")
        self.astertEqual(text.get_valid_filename(lazystr(filename)), "-_123.txt")

0 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_format_lazy(self):
        self.astertEqual('django/test', format_lazy('{}/{}', 'django', lazystr('test')))
        self.astertEqual('django/test', format_lazy('{0}/{1}', *('django', 'test')))
        self.astertEqual('django/test', format_lazy('{a}/{b}', **{'a': 'django', 'b': 'test'}))
        self.astertEqual('django/test', format_lazy('{a[0]}/{a[1]}', a=('django', 'test')))

        t = {}
        s = format_lazy('{0[a]}-{p[a]}', t, p=t)
        t['a'] = lazystr('django')
        self.astertEqual('django-django', s)
        t['a'] = 'update'
        self.astertEqual('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.astertEqual('Ajout de article «\xa0My first try\xa0».', s)

0 View Complete Implementation : test_text.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_truncate_chars(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.astertEqual('The quick brown fox jumped over the lazy dog.', truncator.chars(100)),
        self.astertEqual('The quick brown fox …', truncator.chars(21)),
        self.astertEqual('The quick brown fo.....', truncator.chars(23, '.....')),

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

        # 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.astertEqual('-B\u030A…', truncator.chars(3))
        self.astertEqual('-B\u030AB\u030A-…', truncator.chars(5))
        self.astertEqual('-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.astertEqual('---B\u030A', truncator.chars(4, 'B\u030A'))
        self.astertEqual('-----', 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.astertEqual('…', text.Truncator('asdf').chars(0))
        # lazy strings are handled correctly
        self.astertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…')