Debian Codegraph @

tests/test_cmdline.py

raw
1 """
2 Command line test
3 ~~~~~~~~~~~~~~~~~
4
5 :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
6 :license: BSD, see LICENSE for details.
7 """
8
9 import io
10 import os
11 import re
12 import sys
13 import tempfile
14 from io import BytesIO
15 from os import path
16
17 import pytest
18 from pytest import raises
19
20 from pygments import cmdline, highlight
21
22 TESTDIR = path.dirname(path.abspath(__file__))
23 TESTFILE = path.join(TESTDIR, 'test_cmdline.py')
24
25 TESTCODE = '''\
26 def func(args):
27 pass
28 '''
29
30
31 def _decode_output(text):
32 try:
33 return text.decode('utf-8')
34 except UnicodeEncodeError: # implicit encode on Python 2 with data loss
35 return text
36
37
38 def run_cmdline(*args, **kwds):
39 saved_stdin = sys.stdin
40 saved_stdout = sys.stdout
41 saved_stderr = sys.stderr
42 stdin_buffer = BytesIO()
43 stdout_buffer = BytesIO()
44 stderr_buffer = BytesIO()
45 new_stdin = sys.stdin = io.TextIOWrapper(stdin_buffer, 'utf-8')
46 new_stdout = sys.stdout = io.TextIOWrapper(stdout_buffer, 'utf-8')
47 new_stderr = sys.stderr = io.TextIOWrapper(stderr_buffer, 'utf-8')
48 new_stdin.write(kwds.get('stdin', ''))
49 new_stdin.seek(0, 0)
50 try:
51 ret = cmdline.main(['pygmentize'] + list(args))
52 finally:
53 sys.stdin = saved_stdin
54 sys.stdout = saved_stdout
55 sys.stderr = saved_stderr
56 new_stdout.flush()
57 new_stderr.flush()
58 out, err = stdout_buffer.getvalue(), \
59 stderr_buffer.getvalue()
60 return (ret, _decode_output(out), _decode_output(err))
61
62
63 def check_success(*cmdline, **kwds):
64 code, out, err = run_cmdline(*cmdline, **kwds)
65 assert code == 0
66 assert err == ''
67 return out
68
69
70 def check_failure(*cmdline, **kwds):
71 expected_code = kwds.pop('code', 1)
72 try:
73 code, out, err = run_cmdline(*cmdline, **kwds)
74 except SystemExit as err:
75 assert err.args[0] == expected_code
76 else:
77 assert code == expected_code
78 assert out == ''
79 return err
80
81
82 def test_normal():
83 # test that cmdline gives the same output as library api
84 from pygments.lexers import PythonLexer
85 from pygments.formatters import HtmlFormatter
86 filename = TESTFILE
87 with open(filename, 'rb') as fp:
88 code = fp.read()
89
90 output = highlight(code, PythonLexer(), HtmlFormatter())
91
92 o = check_success('-lpython', '-fhtml', filename)
93 assert o == output
94
95
96 def test_stdin():
97 o = check_success('-lpython', '-fhtml', stdin=TESTCODE)
98 o = re.sub('<[^>]*>', '', o)
99 # rstrip is necessary since HTML inserts a \n after the last </div>
100 assert o.rstrip() == TESTCODE.rstrip()
101
102 # guess if no lexer given
103 o = check_success('-fhtml', stdin=TESTCODE)
104 o = re.sub('<[^>]*>', '', o)
105 # rstrip is necessary since HTML inserts a \n after the last </div>
106 assert o.rstrip() == TESTCODE.rstrip()
107
108
109 def test_outfile():
110 # test that output file works with and without encoding
111 fd, name = tempfile.mkstemp()
112 os.close(fd)
113 for opts in [['-fhtml', '-o', name, TESTFILE],
114 ['-flatex', '-o', name, TESTFILE],
115 ['-fhtml', '-o', name, '-O', 'encoding=utf-8', TESTFILE]]:
116 try:
117 check_success(*opts)
118 finally:
119 os.unlink(name)
120
121
122 def test_load_from_file():
123 lexer_file = os.path.join(TESTDIR, 'support', 'python_lexer.py')
124 formatter_file = os.path.join(TESTDIR, 'support', 'html_formatter.py')
125
126 # By default, use CustomLexer
127 o = check_success('-l', lexer_file, '-f', 'html', '-x', stdin=TESTCODE)
128 o = re.sub('<[^>]*>', '', o)
129 # rstrip is necessary since HTML inserts a \n after the last </div>
130 assert o.rstrip() == TESTCODE.rstrip()
131
132 # If user specifies a name, use it
133 o = check_success('-f', 'html', '-x', '-l',
134 lexer_file + ':LexerWrapper', stdin=TESTCODE)
135 o = re.sub('<[^>]*>', '', o)
136 # rstrip is necessary since HTML inserts a \n after the last </div>
137 assert o.rstrip() == TESTCODE.rstrip()
138
139 # Should also work for formatters
140 o = check_success('-lpython', '-f',
141 formatter_file + ':HtmlFormatterWrapper',
142 '-x', stdin=TESTCODE)
143 o = re.sub('<[^>]*>', '', o)
144 # rstrip is necessary since HTML inserts a \n after the last </div>
145 assert o.rstrip() == TESTCODE.rstrip()
146
147
148 def test_stream_opt():
149 o = check_success('-lpython', '-s', '-fterminal', stdin=TESTCODE)
150 o = re.sub(r'\x1b\[.*?m', '', o)
151 assert o.replace('\r\n', '\n') == TESTCODE
152
153
154 def test_h_opt():
155 o = check_success('-h')
156 assert 'usage:' in o
157
158
159 def test_L_opt():
160 o = check_success('-L')
161 assert 'Lexers' in o and 'Formatters' in o and 'Filters' in o and 'Styles' in o
162 o = check_success('-L', 'lexer')
163 assert 'Lexers' in o and 'Formatters' not in o
164 check_success('-L', 'lexers')
165
166
167 def test_O_opt():
168 filename = TESTFILE
169 o = check_success('-Ofull=1,linenos=true,foo=bar', '-fhtml', filename)
170 assert '<html' in o
171 assert 'class="linenos"' in o
172
173 # "foobar" is invalid for a bool option
174 e = check_failure('-Ostripnl=foobar', TESTFILE)
175 assert 'Error: Invalid value' in e
176 e = check_failure('-Ostripnl=foobar', '-lpy')
177 assert 'Error: Invalid value' in e
178
179
180 def test_P_opt():
181 filename = TESTFILE
182 o = check_success('-Pfull', '-Ptitle=foo, bar=baz=,', '-fhtml', filename)
183 assert '<title>foo, bar=baz=,</title>' in o
184
185
186 def test_F_opt():
187 filename = TESTFILE
188 o = check_success('-Fhighlight:tokentype=Name.Blubb,'
189 'names=TESTFILE filename', '-fhtml', filename)
190 assert '<span class="n n-Blubb' in o
191
192
193 def test_H_opt():
194 o = check_success('-H', 'formatter', 'html')
195 assert 'HTML' in o
196 o = check_success('-H', 'lexer', 'python')
197 assert 'Python' in o
198 o = check_success('-H', 'filter', 'raiseonerror')
199 assert 'raiseonerror' in o
200 e = check_failure('-H', 'lexer', 'foobar')
201 assert 'not found' in e
202
203
204 def test_S_opt():
205 o = check_success('-S', 'default', '-f', 'html', '-O', 'linenos=1')
206 lines = o.splitlines()
207 for line in lines[5:]:
208 # every line is for a token class, except for the first 5 lines,
209 # which define styles for `pre` and line numbers
210 parts = line.split()
211 assert parts[0].startswith('.')
212 assert parts[1] == '{'
213 if parts[0] != '.hll':
214 assert parts[-4] == '}'
215 assert parts[-3] == '/*'
216 assert parts[-1] == '*/'
217 check_failure('-S', 'default', '-f', 'foobar')
218
219
220 def test_N_opt():
221 o = check_success('-N', 'test.py')
222 assert 'python' == o.strip()
223 o = check_success('-N', 'test.unknown')
224 assert 'text' == o.strip()
225
226
227 def test_C_opt():
228 o = check_success('-C', stdin='#!python3\n')
229 assert 'python' == o.strip()
230 o = check_success('-C', stdin='x')
231 assert 'text' == o.strip()
232
233
234 @pytest.mark.parametrize('opts', [
235 ('-X',),
236 ('-L', '-lpy'),
237 ('-L', '-fhtml'),
238 ('-L', '-Ox'),
239 ('-S', 'default', '-l', 'py', '-f', 'html'),
240 ('-S', 'default'),
241 ('-a', 'arg'),
242 ('-H',),
243 (TESTFILE, TESTFILE),
244 ('-H', 'formatter'),
245 ('-H', 'foo', 'bar'),
246 ('-s',),
247 ('-s', TESTFILE),
248 ])
249 def test_invalid_opts(opts):
250 check_failure(*opts, code=2)
251
252
253 def test_errors():
254 # input file not found
255 e = check_failure('-lpython', 'nonexistent.py')
256 assert 'Error: cannot read infile' in e
257 assert 'nonexistent.py' in e
258
259 # lexer not found
260 e = check_failure('-lfooo', TESTFILE)
261 assert 'Error: no lexer for alias' in e
262
263 # cannot load .py file without load_from_file flag
264 e = check_failure('-l', 'nonexistent.py', TESTFILE)
265 assert 'Error: no lexer for alias' in e
266
267 # lexer file is missing/unreadable
268 e = check_failure('-l', 'nonexistent.py', '-x', TESTFILE)
269 assert 'Error: cannot read' in e
270
271 # lexer file is malformed
272 e = check_failure('-l', path.join(TESTDIR, 'support', 'empty.py'),
273 '-x', TESTFILE)
274 assert 'Error: no valid CustomLexer class found' in e
275
276 # formatter not found
277 e = check_failure('-lpython', '-ffoo', TESTFILE)
278 assert 'Error: no formatter found for name' in e
279
280 # formatter for outfile not found
281 e = check_failure('-ofoo.foo', TESTFILE)
282 assert 'Error: no formatter found for file name' in e
283
284 # cannot load .py file without load_from_file flag
285 e = check_failure('-f', 'nonexistent.py', TESTFILE)
286 assert 'Error: no formatter found for name' in e
287
288 # formatter file is missing/unreadable
289 e = check_failure('-f', 'nonexistent.py', '-x', TESTFILE)
290 assert 'Error: cannot read' in e
291
292 # formatter file is malformed
293 e = check_failure('-f', path.join(TESTDIR, 'support', 'empty.py'),
294 '-x', TESTFILE)
295 assert 'Error: no valid CustomFormatter class found' in e
296
297 # output file not writable
298 e = check_failure('-o', os.path.join('nonexistent', 'dir', 'out.html'),
299 '-lpython', TESTFILE)
300 assert 'Error: cannot open outfile' in e
301 assert 'out.html' in e
302
303 # unknown filter
304 e = check_failure('-F', 'foo', TESTFILE)
305 assert 'Error: filter \'foo\' not found' in e
306
307
308 def test_exception():
309 cmdline.highlight = None # override callable to provoke TypeError
310 try:
311 # unexpected exception while highlighting
312 e = check_failure('-lpython', TESTFILE)
313 assert '*** Error while highlighting:' in e
314 assert 'TypeError' in e
315
316 # same with -v: should reraise the exception
317 assert raises(Exception, check_failure, '-lpython', '-v', TESTFILE)
318 finally:
319 cmdline.highlight = highlight
320
321
322 def test_parse_opts():
323 assert cmdline._parse_options([' ', 'keyonly,key = value ']) == \
324 {'keyonly': True, 'key': 'value'}