1# -*- coding: utf-8 -*- 2""" 3 Pygments LaTeX formatter tests 4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 6 :copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS. 7 :license: BSD, see LICENSE for details. 8""" 9 10import os 11import tempfile 12from os import path 13from textwrap import dedent 14 15import pytest 16 17from pygments.formatters import LatexFormatter 18from pygments.formatters.latex import LatexEmbeddedLexer 19from pygments.lexers import PythonLexer, PythonConsoleLexer 20from pygments.token import Token 21 22TESTDIR = path.dirname(path.abspath(__file__)) 23TESTFILE = path.join(TESTDIR, 'test_latex_formatter.py') 24 25 26def test_valid_output(): 27 with open(TESTFILE) as fp: 28 tokensource = list(PythonLexer().get_tokens(fp.read())) 29 fmt = LatexFormatter(full=True, encoding='latin1') 30 31 handle, pathname = tempfile.mkstemp('.tex') 32 # place all output files in /tmp too 33 old_wd = os.getcwd() 34 os.chdir(os.path.dirname(pathname)) 35 tfile = os.fdopen(handle, 'wb') 36 fmt.format(tokensource, tfile) 37 tfile.close() 38 try: 39 import subprocess 40 po = subprocess.Popen(['latex', '-interaction=nonstopmode', 41 pathname], stdout=subprocess.PIPE) 42 ret = po.wait() 43 output = po.stdout.read() 44 po.stdout.close() 45 except OSError as e: 46 # latex not available 47 pytest.skip(str(e)) 48 else: 49 if ret: 50 print(output) 51 assert not ret, 'latex run reported errors' 52 53 os.unlink(pathname) 54 os.chdir(old_wd) 55 56 57def test_embedded_lexer(): 58 # Latex surrounded by '|' should be Escaped 59 lexer = LatexEmbeddedLexer('|', '|', PythonConsoleLexer()) 60 61 # similar to gh-1516 62 src = dedent("""\ 63 >>> x = 1 64 >>> y = mul(x, |$z^2$|) # these |pipes| are untouched 65 >>> y 66 |$1 + z^2$|""") 67 68 assert list(lexer.get_tokens(src)) == [(Token.Name, ''), 69 (Token.Generic.Prompt, '>>> '), 70 (Token.Name, 'x'), 71 (Token.Text, ' '), 72 (Token.Operator, '='), 73 (Token.Text, ' '), 74 (Token.Literal.Number.Integer, '1'), 75 (Token.Text, '\n'), 76 (Token.Generic.Prompt, '>>> '), 77 (Token.Text, ''), 78 (Token.Name, 'y'), 79 (Token.Text, ' '), 80 (Token.Operator, '='), 81 (Token.Text, ' '), 82 (Token.Name, 'mul'), 83 (Token.Punctuation, '('), 84 (Token.Name, 'x'), 85 (Token.Punctuation, ','), 86 (Token.Text, ' '), 87 (Token.Escape, '$z^2$'), 88 (Token.Text, ''), 89 (Token.Punctuation, ')'), 90 (Token.Text, ' '), 91 (Token.Comment.Single, '# these |pipes| are untouched'), # note: not Token.Escape 92 (Token.Text, '\n'), 93 (Token.Generic.Prompt, '>>> '), 94 (Token.Text, ''), 95 (Token.Name, 'y'), 96 (Token.Text, '\n'), 97 (Token.Escape, '$1 + z^2$'), 98 (Token.Text, ''), 99 (Token.Generic.Output, '\n'), 100 ]