Esempio n. 1
0
 def helper(field_stream):
     s = Stream(field_stream)
     value = s.select('@value').textOf()
     name = s.select('@name').textOf()
     for kind,data,pos in tag.span(value, id=("field-%s"%field)).generate():
         yield kind,data,pos
     for kind,data,pos in tag.input(value=value, name=name, type="hidden").generate():
         yield kind,data,pos
Esempio n. 2
0
 def select_helper(stream):
     s = Stream(stream)
     name = s.select('@name').textOf()
     opt = s.select('//option[@selected]')
     if not opt: s.select('//option[position()=1]')
     text = opt.select("text()").textOf()
     value = s.select('@value').textOf()
     if not value: value = text
     for kind,data,pos in tag.input(value=value, name=name, type="hidden").generate():
         yield kind,data,pos
Esempio n. 3
0
 def helper(field_stream):
     s = Stream(field_stream)
     value = s.select('@value').textOf()
     name = s.select('@name').textOf()
     for kind, data, pos in tag.span(value,
                                     id=("field-%s" % field)).generate():
         yield kind, data, pos
     for kind, data, pos in tag.input(value=value, name=name,
                                      type="hidden").generate():
         yield kind, data, pos
Esempio n. 4
0
 def select_helper(stream):
     s = Stream(stream)
     name = s.select('@name').textOf()
     opt = s.select('//option[@selected]')
     if not opt: s.select('//option[position()=1]')
     text = opt.select("text()").textOf()
     value = s.select('@value').textOf()
     if not value: value = text
     for kind, data, pos in tag.input(value=value, name=name,
                                      type="hidden").generate():
         yield kind, data, pos
Esempio n. 5
0
    def extract_javascript_script(fileobj, keywords, comment_tags, options):
        """Extract messages from Javascript embedding in <script> tags.

        Select <script type="javascript/text"> tags and delegate to
        `extract_javascript`.
        """
        from genshi.core import Stream
        from genshi.input import XMLParser

        out = StringIO()
        stream = Stream(XMLParser(fileobj))
        stream.select('//script[@type="text/javascript"]').render(out=out)
        out.seek(0)
        return extract_javascript(out, keywords, comment_tags, options)
Esempio n. 6
0
 def helper(field_stream):
     s =  Stream(field_stream)
     f = s.select('//strong/text()').textOf()
     if field != f: #if we are the field just skip it
         #identity stream filter
         for kind, data, pos in s:
             yield kind, data, pos
Esempio n. 7
0
 def helper(field_stream):
     s = Stream(field_stream)
     f = s.select('//strong/text()').textOf()
     if field != f:  #if we are the field just skip it
         #identity stream filter
         for kind, data, pos in s:
             yield kind, data, pos
Esempio n. 8
0
 def helper(field_stream):
     try:
         s = Stream(field_stream)
         self.log.debug('ChangeLog Pre')
         # without None as the second value we get str instead of unicode
         # and that causes things to break sometimes
         f = s.select('//strong/text()').textOf(strip_markup=True).lower()
         # self.log.debug(u'ChangeLog Pre 2 : %s: %r', type(f), f)
         self.log.debug('ChangeLog Filter: field:%s, label:%s, we are looking at:%r, skip?%s',
                        field, check, f, check == f )
         if check != f: #if we are the field just skip it
         #identity stream filter
             for kind, data, pos in s:
                 yield kind, data, pos
     except Exception, e:
         self.log.exception('ChangeLog: Stream Filter Exception');
         raise e
Esempio n. 9
0
 def helper(field_stream):
     try:
         s = Stream(field_stream)
         self.log.debug('ChangeLog Pre')
         # without None as the second value we get str instead of unicode
         # and that causes things to break sometimes
         f = s.select('//strong/text()').textOf(strip_markup=True).lower()
         # self.log.debug(u'ChangeLog Pre 2 : %s: %r', type(f), f)
         self.log.debug(
             'ChangeLog Filter: field:%s, label:%s, we are looking at:%r, skip?%s',
             field, check, f, check == f)
         if check != f:  #if we are the field just skip it
             #identity stream filter
             for kind, data, pos in s:
                 yield kind, data, pos
     except Exception, e:
         self.log.exception('ChangeLog: Stream Filter Exception')
         raise e
Esempio n. 10
0
class PygmentsRendererTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(enable=[Chrome, PygmentsRenderer])
        self.pygments = Mimeview(self.env).renderers[0]
        self.req = Mock(base_path='', chrome={}, args={},
                        abs_href=Href('/'), href=Href('/'),
                        session={}, perm=None, authname=None, tz=None)
        self.context = web_context(self.req)
        pygments_html = open(os.path.join(os.path.split(__file__)[0],
                                       'pygments.html'))
        self.pygments_html = Stream(list(HTMLParser(pygments_html, encoding='utf-8')))

    def _expected(self, expected_id):
        return self.pygments_html.select(
            '//div[@id="%s"]/*|//div[@id="%s"]/text())' %
            (expected_id, expected_id))

    def _test(self, expected_id, result):
        expected = str(self._expected(expected_id))
        result = str(result)
        #print "\nE: " + repr(expected)
        #print "\nR: " + repr(result)
        expected, result = expected.splitlines(), result.splitlines()
        for exp, res in zip(expected, result):
            self.assertEqual(exp, res)
        self.assertEqual(len(expected), len(result))

    def test_python_hello(self):
        """
        Simple Python highlighting with Pygments (direct)
        """
        result = self.pygments.render(self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        self._test('python_hello', result)

    def test_python_hello_mimeview(self):
        """
        Simple Python highlighting with Pygments (through Mimeview.render)
        """
        result = Mimeview(self.env).render(self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        self._test('python_hello_mimeview', result)

    def test_newline_content(self):
        """
        The behavior of Pygments changed post-Pygments 0.11.1, and now
        contains all four newlines.  In Pygments 0.11.1 and prior, it only
        has three since stripnl defaults to True.

        See http://trac.edgewall.org/ticket/7705.
        """
        from pkg_resources import parse_version, get_distribution

        result = self.pygments.render(self.context, 'text/x-python', '\n\n\n\n')
        self.assertTrue(result)
        t = "".join([r[1] for r in result if r[0] is TEXT])

        if parse_version(pygments.__version__) > parse_version('0.11.1') \
           or pygments.__version__ == '0.11.1' and 'dev' in \
           get_distribution('Pygments').version:
            self.assertEqual("\n\n\n\n", t)
        else:
            self.assertEqual("\n\n\n", t)

    def test_empty_content(self):
        """
        A '\n' token is generated for an empty file, so we have to bypass
        pygments when rendering empty files.
        """
        result = self.pygments.render(self.context, 'text/x-python', '')
        self.assertIsNone(result)

    def test_extra_mimetypes(self):
        """
        The text/x-ini mimetype is normally not known by Trac, but
        Pygments supports it.
        """
        mimeview = Mimeview(self.env)
        self.assertEqual('text/x-ini; charset=utf-8',
                         mimeview.get_mimetype('file.ini'))
        self.assertEqual('text/x-ini; charset=utf-8',
                         mimeview.get_mimetype('file.cfg'))
        self.assertEqual('text/x-ini; charset=utf-8',
                         mimeview.get_mimetype('file.text/x-ini'))
Esempio n. 11
0
class PatchRendererTestCase(unittest.TestCase):
    def setUp(self):
        env = EnvironmentStub(enable=[Chrome, PatchRenderer])
        req = Mock(base_path='',
                   chrome={},
                   args={},
                   session={},
                   abs_href=Href('/'),
                   href=Href('/'),
                   locale='',
                   perm=MockPerm(),
                   authname=None,
                   tz=None)
        self.context = Context.from_request(req)
        self.patch = Mimeview(env).renderers[0]
        patch_html = open(
            os.path.join(os.path.split(__file__)[0], 'patch.html'))
        self.patch_html = Stream(list(HTMLParser(patch_html)))

    def _expected(self, expected_id):
        return self.patch_html.select('//div[@id="%s"]/div' % expected_id)

    def _test(self, expected_id, result):
        expected = str(self._expected(expected_id))
        result = str(XML(result))
        expected, result = expected.splitlines(), result.splitlines()
        for exp, res in zip(expected, result):
            self.assertEquals(exp, res)
        self.assertEquals(len(expected), len(result))

    def test_simple(self):
        """
        Simple patch rendering
        """
        result = self.patch.render(
            self.context, None, """
--- README.orig 2006-10-27 14:42:04.062500000 +0200
+++ README      2006-10-27 14:42:28.125000000 +0200
@@ -1,5 +1,5 @@
 ----
-base
-base
-base
+be
+the base
+base modified
 .
""")
        self.assertTrue(result)
        self._test('simple', result)

    def test_no_newline_in_base(self):
        """
        Simple regression test for #4027 ("No newline at end of file")
        """
        result = self.patch.render(
            self.context, None, """
--- nonewline   2006-10-27 08:36:48.453125000 +0200
+++ newline     2006-10-27 08:36:57.187500000 +0200
@@ -1 +1 @@
-ONELINE
\ No newline at end of file
+ONELINE        
""")
        self.assertTrue(result)
        self._test('no_newline_in_base', result)

    def test_no_newline_in_changed(self):
        """
        Another simple regression test for #4027 ("No newline at end of file")
        """
        result = self.patch.render(
            self.context, None, """
--- newline     2006-10-27 08:36:57.187500000 +0200
+++ nonewline   2006-10-27 08:36:48.453125000 +0200
@@ -1 +1 @@
-ONELINE
+ONELINE
\ No newline at end of file
""")
        self.assertTrue(result)
        self._test('no_newline_in_changed', result)

    def test_diff_to_hdf_expandtabs(self):
        """Regression test related to #4557"""
        changes = self.patch._diff_to_hdf([
            '--- hello.c 1', '+++ hello.c 2', '@@ -1 +1 @@', '-aa\tb', '+aaxb'
        ], 8)
        self.assertEquals('aa<del>&nbsp; &nbsp; &nbsp; </del>b',
                          str(changes[0]['diffs'][0][0]['base']['lines'][0]))
        self.assertEquals(
            'aa<ins>x</ins>b',
            str(changes[0]['diffs'][0][0]['changed']['lines'][0]))

    def test_diff_to_hdf_leading_ws(self):
        """Regression test related to #5795"""
        changes = self.patch._diff_to_hdf(
            ['--- hello.c 1', '+++ hello.c 2', '@@ -1 +1 @@', '-*a', '+ *a'],
            8)
        self.assertEquals('<del></del>*a',
                          str(changes[0]['diffs'][0][0]['base']['lines'][0]))
        self.assertEquals(
            '<ins>&nbsp;</ins>*a',
            str(changes[0]['diffs'][0][0]['changed']['lines'][0]))
Esempio n. 12
0
class PatchRendererTestCase(unittest.TestCase):

    def setUp(self):
        env = EnvironmentStub(enable=[Chrome, PatchRenderer])
        req = Mock(base_path='', chrome={'static_hash': None}, args={},
                   session={}, abs_href=Href('/'), href=Href('/'), locale='',
                   perm=MockPerm(), authname=None, tz=None)
        self.context = web_context(req)
        self.patch = Mimeview(env).renderers[0]
        patch_html = open(os.path.join(os.path.split(__file__)[0],
                                       'patch.html'))
        self.patch_html = Stream(list(HTMLParser(patch_html, encoding='utf-8')))

    def _expected(self, expected_id):
        return self.patch_html.select('//div[@id="%s"]/div' % expected_id)

    def _test(self, expected_id, result):
        expected = self._expected(expected_id).render(encoding='utf-8')
        result = XML(result.render(encoding='utf-8')).render(encoding='utf-8')
        expected, result = expected.splitlines(), result.splitlines()
        for exp, res in zip(expected, result):
            self.assertEquals(exp, res)
        self.assertEquals(len(expected), len(result))

    def test_simple(self):
        """
        Simple patch rendering
        """
        result = self.patch.render(self.context, None, """
--- README.orig 2006-10-27 14:42:04.062500000 +0200
+++ README      2006-10-27 14:42:28.125000000 +0200
@@ -1,5 +1,5 @@
 ----
-base
-base
-base
+be
+the base
+base modified
 .
""")
        self.assertTrue(result)
        self._test('simple', result)

    def test_no_newline_in_base(self):
        """
        Simple regression test for #4027 ("No newline at end of file")
        """
        result = self.patch.render(self.context, None, """
--- nonewline   2006-10-27 08:36:48.453125000 +0200
+++ newline     2006-10-27 08:36:57.187500000 +0200
@@ -1 +1 @@
-ONELINE
\ No newline at end of file
+ONELINE        
""")
        self.assertTrue(result)
        self._test('no_newline_in_base', result)

    def test_no_newline_in_changed(self):
        """
        Another simple regression test for #4027 ("No newline at end of file")
        """
        result = self.patch.render(self.context, None, """
--- newline     2006-10-27 08:36:57.187500000 +0200
+++ nonewline   2006-10-27 08:36:48.453125000 +0200
@@ -1 +1 @@
-ONELINE
+ONELINE
\ No newline at end of file
""")
        self.assertTrue(result)
        self._test('no_newline_in_changed', result)
    def test_diff_to_hdf_expandtabs(self):
        """Regression test related to #4557"""
        changes = self.patch._diff_to_hdf(
            ['--- hello.c 1',
             '+++ hello.c 2',
             '@@ -1 +1 @@',
             '-aa\tb',
             '+aaxb'], 8)
        self.assertEquals('aa<del>&nbsp; &nbsp; &nbsp; </del>b',
                          str(changes[0]['diffs'][0][0]['base']['lines'][0]))
        self.assertEquals('aa<ins>x</ins>b',
                          str(changes[0]['diffs'][0][0]['changed']['lines'][0]))

    def test_diff_to_hdf_leading_ws(self):
        """Regression test related to #5795"""
        changes = self.patch._diff_to_hdf(
            ['--- hello.c 1',
             '+++ hello.c 2',
             '@@ -1 +1 @@',
             '-*a',
             '+ *a'], 8)
        self.assertEquals('<del></del>*a',
                          str(changes[0]['diffs'][0][0]['base']['lines'][0]))
        self.assertEquals('<ins>&nbsp;</ins>*a',
                          str(changes[0]['diffs'][0][0]['changed']['lines'][0]))
Esempio n. 13
0
class PygmentsRendererTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub(
            enable=[Chrome, LineNumberAnnotator, PygmentsRenderer])
        self.pygments = Mimeview(self.env).renderers[0]
        self.req = Mock(base_path='',
                        chrome={},
                        args={},
                        abs_href=Href('/'),
                        href=Href('/'),
                        session={},
                        perm=None,
                        authname=None,
                        tz=None)
        self.context = web_context(self.req)
        pygments_html = open(
            os.path.join(os.path.split(__file__)[0], 'pygments.html'))
        self.pygments_html = Stream(
            list(HTMLParser(pygments_html, encoding='utf-8')))

    def _expected(self, expected_id):
        return self.pygments_html.select(
            '//div[@id="%s"]/*|//div[@id="%s"]/text())' %
            (expected_id, expected_id))

    def _test(self, expected_id, result):
        expected = unicode(self._expected(expected_id))
        result = unicode(result)
        #print("\nE: " + repr(expected))
        #print("\nR: " + repr(result))
        expected, result = expected.splitlines(), result.splitlines()
        for exp, res in zip(expected, result):
            self.assertEqual(exp, res)
        self.assertEqual(len(expected), len(result))

    def test_python_hello(self):
        """
        Simple Python highlighting with Pygments (direct)
        """
        result = self.pygments.render(
            self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        self._test('python_hello', result)

    def test_python_hello_mimeview(self):
        """
        Simple Python highlighting with Pygments (through Mimeview.render)
        """
        result = Mimeview(self.env).render(
            self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        self._test('python_hello_mimeview', result)

    def test_python_with_lineno(self):
        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        self._test('python_with_lineno_1', result)

        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=3
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        self._test('python_with_lineno_2', result)

    def test_python_with_lineno_and_markups(self):
        """Python highlighting with Pygments and lineno annotator
        """
        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=3 id=b marks=4-5
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        self._test('python_with_lineno_and_markups', result)

    def test_python_with_invalid_arguments(self):
        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=-10
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        self._test('python_with_invalid_arguments_1', result)

        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=a id=d marks=a-b
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        self._test('python_with_invalid_arguments_2', result)

    def test_pygments_lexer_options(self):
        self.env.config.set('pygments-lexer', 'php.startinline', True)
        self.env.config.set('pygments-lexer', 'php.funcnamehighlighting',
                            False)
        result = format_to_html(
            self.env, self.context, """
{{{#!php
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
}}}
""")
        self.assertTrue(result)
        self._test('pygments_lexer_options', result)

    def test_pygments_lexer_arguments(self):
        result = format_to_html(
            self.env, self.context, """
{{{#!php startinline=True funcnamehighlighting=False
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
}}}
""")
        self.assertTrue(result)
        self._test('pygments_lexer_arguments', result)

    def test_pygments_lexer_arguments_override_options(self):
        self.env.config.set('pygments-lexer', 'php.startinline', True)
        self.env.config.set('pygments-lexer', 'php.funcnamehighlighting',
                            False)
        result = format_to_html(
            self.env, self.context, """
{{{#!php funcnamehighlighting=True
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
}}}
""")
        self.assertTrue(result)
        self._test('pygments_lexer_arguments_override_options', result)

    def test_newline_content(self):
        """
        The behavior of Pygments changed post-Pygments 0.11.1, and now
        contains all four newlines.  In Pygments 0.11.1 and prior, it only
        has three since stripnl defaults to True.

        See http://trac.edgewall.org/ticket/7705.
        """
        from pkg_resources import parse_version, get_distribution

        result = self.pygments.render(self.context, 'text/x-python',
                                      '\n\n\n\n')
        self.assertTrue(result)
        t = "".join([r[1] for r in result if r[0] is TEXT])

        if parse_version(pygments.__version__) > parse_version('0.11.1') \
           or pygments.__version__ == '0.11.1' and 'dev' in \
           get_distribution('Pygments').version:
            self.assertEqual("\n\n\n\n", t)
        else:
            self.assertEqual("\n\n\n", t)

    def test_empty_content(self):
        """
        A '\n' token is generated for an empty file, so we have to bypass
        pygments when rendering empty files.
        """
        result = self.pygments.render(self.context, 'text/x-python', '')
        self.assertIsNone(result)

    def test_extra_mimetypes(self):
        """
        The text/x-ini mimetype is normally not known by Trac, but
        Pygments supports it.
        """
        mimeview = Mimeview(self.env)
        self.assertEqual('text/x-ini; charset=utf-8',
                         mimeview.get_mimetype('file.ini'))
        self.assertEqual('text/x-ini; charset=utf-8',
                         mimeview.get_mimetype('file.cfg'))
        self.assertEqual('text/x-ini; charset=utf-8',
                         mimeview.get_mimetype('file.text/x-ini'))
Esempio n. 14
0
class PygmentsRendererTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(enable=[Chrome, PygmentsRenderer])
        self.pygments = Mimeview(self.env).renderers[0]
        self.req = Mock(base_path='', chrome={}, args={},
                        abs_href=Href('/'), href=Href('/'),
                        session={}, perm=None, authname=None, tz=None)
        self.context = web_context(self.req)
        pygments_html = open(os.path.join(os.path.split(__file__)[0],
                                       'pygments.html'))
        self.pygments_html = Stream(list(HTMLParser(pygments_html, encoding='utf-8')))

    def _expected(self, expected_id):
        return self.pygments_html.select(
            '//div[@id="%s"]/*|//div[@id="%s"]/text())' % 
            (expected_id, expected_id))

    def _test(self, expected_id, result):
        expected = str(self._expected(expected_id))
        result = str(result)
        #print "\nE: " + repr(expected)
        #print "\nR: " + repr(result)
        expected, result = expected.splitlines(), result.splitlines()
        for exp, res in zip(expected, result):
            self.assertEquals(exp, res)
        self.assertEquals(len(expected), len(result))

    def test_python_hello(self):
        """
        Simple Python highlighting with Pygments (direct)
        """
        result = self.pygments.render(self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        self._test('python_hello', result)

    def test_python_hello_mimeview(self):
        """
        Simple Python highlighting with Pygments (through Mimeview.render)
        """
        result = Mimeview(self.env).render(self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        self._test('python_hello_mimeview', result)

    def test_newline_content(self):
        """
        The behavior of Pygments changed post-Pygments 0.11.1, and now
        contains all four newlines.  In Pygments 0.11.1 and prior, it only
        has three since stripnl defaults to True.

        See http://trac.edgewall.org/ticket/7705.
        """
        from pkg_resources import parse_version, get_distribution

        result = self.pygments.render(self.context, 'text/x-python', '\n\n\n\n')
        self.assertTrue(result)
        t = "".join([r[1] for r in result if r[0] is TEXT])

        if parse_version(pygments.__version__) > parse_version('0.11.1') \
           or pygments.__version__ == '0.11.1' and 'dev' in \
           get_distribution('Pygments').version:
            self.assertEqual("\n\n\n\n", t)
        else:
            self.assertEqual("\n\n\n", t)

    def test_empty_content(self):
        """
        A '\n' token is generated for an empty file, so we have to bypass
        pygments when rendering empty files.
        """
        result = self.pygments.render(self.context, 'text/x-python', '')
        self.assertEqual(None, result)
Esempio n. 15
0
class PygmentsRendererTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub(
            enable=[Chrome, LineNumberAnnotator, PygmentsRenderer])
        self.pygments = Mimeview(self.env).renderers[0]
        self.req = MockRequest(self.env)
        self.context = web_context(self.req)
        pygments_html = open(
            os.path.join(os.path.split(__file__)[0], 'pygments.html'))
        self.pygments_html = Stream(
            list(HTMLParser(pygments_html, encoding='utf-8')))

    def _expected(self, expected_id):
        return self.pygments_html.select(
            '//div[@id="%s"]/*|//div[@id="%s"]/text())' %
            (expected_id, expected_id))

    def _test(self, expected_id, result):
        expected = unicode(self._expected(expected_id))
        result = unicode(result)
        #print("\nE: " + repr(expected))
        #print("\nR: " + repr(result))
        expected, result = expected.splitlines(), result.splitlines()
        for exp, res in zip(expected, result):
            self.assertEqual(exp, res)
        self.assertEqual(len(expected), len(result))

    def test_python_hello(self):
        """
        Simple Python highlighting with Pygments (direct)
        """
        result = self.pygments.render(
            self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        if pygments_version < parse_version('2.1'):
            self._test('python_hello', result)
        else:
            self._test('python_hello_pygments_2.1plus', result)

    def test_python_hello_mimeview(self):
        """
        Simple Python highlighting with Pygments (through Mimeview.render)
        """
        result = Mimeview(self.env).render(
            self.context, 'text/x-python', """
def hello():
        return "Hello World!"
""")
        self.assertTrue(result)
        if pygments_version < parse_version('2.1'):
            self._test('python_hello_mimeview', result)
        else:
            self._test('python_hello_mimeview_pygments_2.1plus', result)

    def test_python_with_lineno(self):
        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        if pygments_version < parse_version('2.1'):
            self._test('python_with_lineno_1', result)
        else:
            self._test('python_with_lineno_1_pygments_2.1plus', result)

        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=3
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        if pygments_version < parse_version('2.1'):
            self._test('python_with_lineno_2', result)
        else:
            self._test('python_with_lineno_2_pygments_2.1plus', result)

    def test_python_with_lineno_and_markups(self):
        """Python highlighting with Pygments and lineno annotator
        """
        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=3 id=b marks=4-5
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        if pygments_version < parse_version('2.1'):
            self._test('python_with_lineno_and_markups', result)
        else:
            self._test('python_with_lineno_and_markups_pygments_2.1plus',
                       result)

    def test_python_with_invalid_arguments(self):
        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=-10
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        if pygments_version < parse_version('2.1'):
            self._test('python_with_invalid_arguments_1', result)
        else:
            self._test('python_with_invalid_arguments_1_pygments_2.1plus',
                       result)

        result = format_to_html(
            self.env, self.context, """\
{{{#!text/x-python lineno=a id=d marks=a-b
print 'this is a python sample'
a = b+3
z = "this is a string"
print 'this is the end of the python sample'
}}}
""")
        self.assertTrue(result)
        if pygments_version < parse_version('2.1'):
            self._test('python_with_invalid_arguments_2', result)
        else:
            self._test('python_with_invalid_arguments_2_pygments_2.1plus',
                       result)

    def test_pygments_lexer_options(self):
        self.env.config.set('pygments-lexer', 'php.startinline', True)
        self.env.config.set('pygments-lexer', 'php.funcnamehighlighting',
                            False)
        result = format_to_html(
            self.env, self.context, """
{{{#!php
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
}}}
""")
        self.assertTrue(result)
        self._test('pygments_lexer_options', result)

    def test_pygments_lexer_arguments(self):
        result = format_to_html(
            self.env, self.context, """
{{{#!php startinline=True funcnamehighlighting=False
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
}}}
""")
        self.assertTrue(result)
        self._test('pygments_lexer_arguments', result)

    def test_pygments_lexer_arguments_override_options(self):
        self.env.config.set('pygments-lexer', 'php.startinline', True)
        self.env.config.set('pygments-lexer', 'php.funcnamehighlighting',
                            False)
        result = format_to_html(
            self.env, self.context, """
{{{#!php funcnamehighlighting=True
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
}}}
""")
        self.assertTrue(result)
        self._test('pygments_lexer_arguments_override_options', result)

    def test_newline_content(self):
        """Regression test for newline-stripping behavior in Pygments.

        http://trac.edgewall.org/ticket/7705
        """
        result = self.pygments.render(self.context, 'text/x-python',
                                      '\n\n\n\n')
        self.assertTrue(result)
        t = "".join(r[1] for r in result if r[0] is TEXT)

        self.assertEqual("\n\n\n\n", t)

    def test_empty_content(self):
        """
        A '\n' token is generated for an empty file, so we have to bypass
        pygments when rendering empty files.
        """
        result = self.pygments.render(self.context, 'text/x-python', '')
        self.assertIsNone(result)

    def test_extra_mimetypes(self):
        """
        The text/x-ini mimetype is normally not known by Trac, but
        Pygments supports it.
        """
        mimeview = Mimeview(self.env)
        self.assertIn(mimeview.get_mimetype('file.ini'),
                      ('text/x-ini; charset=utf-8',
                       'text/inf; charset=utf-8'))  # Pygment 2.1+
        self.assertIn(mimeview.get_mimetype('file.cfg'),
                      ('text/x-ini; charset=utf-8',
                       'text/inf; charset=utf-8'))  # Pygment 2.1+
        self.assertEqual('text/x-ini; charset=utf-8',
                         mimeview.get_mimetype('file.text/x-ini'))