Debian Codegraph @

IPython/testing/tools.py

raw
1 """Generic testing tools.
2
3 Authors
4 -------
5 - Fernando Perez <[email protected]>
6 """
7
8
9 # Copyright (c) IPython Development Team.
10 # Distributed under the terms of the Modified BSD License.
11
12 import os
13 from pathlib import Path
14 import re
15 import sys
16 import tempfile
17 import unittest
18
19 from contextlib import contextmanager
20 from io import StringIO
21 from subprocess import Popen, PIPE
22 from unittest.mock import patch
23
24 from traitlets.config.loader import Config
25 from IPython.utils.process import get_output_error_code
26 from IPython.utils.text import list_strings
27 from IPython.utils.io import temp_pyfile, Tee
28 from IPython.utils import py3compat
29
30 from . import decorators as dec
31 from . import skipdoctest
32
33
34 # The docstring for full_path doctests differently on win32 (different path
35 # separator) so just skip the doctest there. The example remains informative.
36 doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
37
38 @doctest_deco
39 def full_path(startPath: str, files: list[str]) -> list[str]:
40 """Make full paths for all the listed files, based on startPath.
41
42 Only the base part of startPath is kept, since this routine is typically
43 used with a script's ``__file__`` variable as startPath. The base of startPath
44 is then prepended to all the listed files, forming the output list.
45
46 Parameters
47 ----------
48 startPath : string
49 Initial path to use as the base for the results. This path is split
50 using os.path.split() and only its first component is kept.
51
52 files : list
53 One or more files.
54
55 Examples
56 --------
57
58 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
59 ['/foo/a.txt', '/foo/b.txt']
60
61 >>> full_path('/foo',['a.txt','b.txt'])
62 ['/a.txt', '/b.txt']
63
64 """
65 assert isinstance(files, list)
66 base = os.path.split(startPath)[0]
67 return [ os.path.join(base,f) for f in files ]
68
69
70 def parse_test_output(txt):
71 """Parse the output of a test run and return errors, failures.
72
73 Parameters
74 ----------
75 txt : str
76 Text output of a test run, assumed to contain a line of one of the
77 following forms::
78
79 'FAILED (errors=1)'
80 'FAILED (failures=1)'
81 'FAILED (errors=1, failures=1)'
82
83 Returns
84 -------
85 nerr, nfail
86 number of errors and failures.
87 """
88
89 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
90 if err_m:
91 nerr = int(err_m.group(1))
92 nfail = 0
93 return nerr, nfail
94
95 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
96 if fail_m:
97 nerr = 0
98 nfail = int(fail_m.group(1))
99 return nerr, nfail
100
101 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
102 re.MULTILINE)
103 if both_m:
104 nerr = int(both_m.group(1))
105 nfail = int(both_m.group(2))
106 return nerr, nfail
107
108 # If the input didn't match any of these forms, assume no error/failures
109 return 0, 0
110
111
112 # So nose doesn't think this is a test
113 parse_test_output.__test__ = False
114
115
116 def default_argv():
117 """Return a valid default argv for creating testing instances of ipython"""
118
119 return [
120 "--quick", # so no config file is loaded
121 # Other defaults to minimize side effects on stdout
122 "--colors=nocolor",
123 "--no-term-title",
124 "--no-banner",
125 "--autocall=0",
126 ]
127
128
129 def default_config():
130 """Return a config object with good defaults for testing."""
131 config = Config()
132 config.TerminalInteractiveShell.colors = "nocolor"
133 config.TerminalTerminalInteractiveShell.term_title = (False,)
134 config.TerminalInteractiveShell.autocall = 0
135 f = tempfile.NamedTemporaryFile(suffix="test_hist.sqlite", delete=False)
136 config.HistoryManager.hist_file = Path(f.name)
137 f.close()
138 config.HistoryManager.db_cache_size = 10000
139 return config
140
141
142 def get_ipython_cmd(as_string=False):
143 """
144 Return appropriate IPython command line name. By default, this will return
145 a list that can be used with subprocess.Popen, for example, but passing
146 `as_string=True` allows for returning the IPython command as a string.
147
148 Parameters
149 ----------
150 as_string: bool
151 Flag to allow to return the command as a string.
152 """
153 ipython_cmd = [sys.executable, "-m", "IPython"]
154
155 if as_string:
156 ipython_cmd = " ".join(ipython_cmd)
157
158 return ipython_cmd
159
160 def ipexec(fname, options=None, commands=()):
161 """Utility to call 'ipython filename'.
162
163 Starts IPython with a minimal and safe configuration to make startup as fast
164 as possible.
165
166 Note that this starts IPython in a subprocess!
167
168 Parameters
169 ----------
170 fname : str, Path
171 Name of file to be executed (should have .py or .ipy extension).
172
173 options : optional, list
174 Extra command-line flags to be passed to IPython.
175
176 commands : optional, list
177 Commands to send in on stdin
178
179 Returns
180 -------
181 ``(stdout, stderr)`` of ipython subprocess.
182 """
183 __tracebackhide__ = True
184
185 if options is None:
186 options = []
187
188 cmdargs = default_argv() + options
189
190 test_dir = os.path.dirname(__file__)
191
192 ipython_cmd = get_ipython_cmd()
193 # Absolute path for filename
194 full_fname = os.path.join(test_dir, fname)
195 full_cmd = ipython_cmd + cmdargs + ['--', full_fname]
196 env = os.environ.copy()
197 # FIXME: ignore all warnings in ipexec while we have shims
198 # should we keep suppressing warnings here, even after removing shims?
199 env['PYTHONWARNINGS'] = 'ignore'
200 # env.pop('PYTHONWARNINGS', None) # Avoid extraneous warnings appearing on stderr
201 # Prevent coloring under PyCharm ("\x1b[0m" at the end of the stdout)
202 env.pop("PYCHARM_HOSTED", None)
203 for k, v in env.items():
204 # Debug a bizarre failure we've seen on Windows:
205 # TypeError: environment can only contain strings
206 if not isinstance(v, str):
207 print(k, v)
208 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
209 out, err = p.communicate(input=py3compat.encode('\n'.join(commands)) or None)
210 out, err = py3compat.decode(out), py3compat.decode(err)
211 # `import readline` causes 'ESC[?1034h' to be output sometimes,
212 # so strip that out before doing comparisons
213 if out:
214 out = re.sub(r'\x1b\[[^h]+h', '', out)
215 return out, err
216
217
218 def ipexec_validate(fname, expected_out, expected_err='',
219 options=None, commands=()):
220 """Utility to call 'ipython filename' and validate output/error.
221
222 This function raises an AssertionError if the validation fails.
223
224 Note that this starts IPython in a subprocess!
225
226 Parameters
227 ----------
228 fname : str, Path
229 Name of the file to be executed (should have .py or .ipy extension).
230
231 expected_out : str
232 Expected stdout of the process.
233
234 expected_err : optional, str
235 Expected stderr of the process.
236
237 options : optional, list
238 Extra command-line flags to be passed to IPython.
239
240 Returns
241 -------
242 None
243 """
244 __tracebackhide__ = True
245
246 out, err = ipexec(fname, options, commands)
247 # print('OUT', out) # dbg
248 # print('ERR', err) # dbg
249 # If there are any errors, we must check those before stdout, as they may be
250 # more informative than simply having an empty stdout.
251 if err:
252 if expected_err:
253 assert "\n".join(err.strip().splitlines()) == "\n".join(
254 expected_err.strip().splitlines()
255 )
256 else:
257 raise ValueError('Running file %r produced error: %r' %
258 (fname, err))
259 # If no errors or output on stderr was expected, match stdout
260 assert "\n".join(out.strip().splitlines()) == "\n".join(
261 expected_out.strip().splitlines()
262 )
263
264
265 class TempFileMixin(unittest.TestCase):
266 """Utility class to create temporary Python/IPython files.
267
268 Meant as a mixin class for test cases."""
269
270 def mktmp(self, src, ext='.py'):
271 """Make a valid python temp file."""
272 fname = temp_pyfile(src, ext)
273 if not hasattr(self, 'tmps'):
274 self.tmps=[]
275 self.tmps.append(fname)
276 self.fname = fname
277
278 def tearDown(self):
279 # If the tmpfile wasn't made because of skipped tests, like in
280 # win32, there's nothing to cleanup.
281 if hasattr(self, 'tmps'):
282 for fname in self.tmps:
283 # If the tmpfile wasn't made because of skipped tests, like in
284 # win32, there's nothing to cleanup.
285 try:
286 os.unlink(fname)
287 except:
288 # On Windows, even though we close the file, we still can't
289 # delete it. I have no clue why
290 pass
291
292 def __enter__(self):
293 return self
294
295 def __exit__(self, exc_type, exc_value, traceback):
296 self.tearDown()
297
298
299 MyStringIO = StringIO
300
301 _re_type = type(re.compile(r''))
302
303 notprinted_msg = """Did not find {0!r} in printed output (on {1}):
304 -------
305 {2!s}
306 -------
307 """
308
309 class AssertPrints:
310 """Context manager for testing that code prints certain text.
311
312 Examples
313 --------
314 >>> with AssertPrints("abc", suppress=False):
315 ... print("abcd")
316 ... print("def")
317 ...
318 abcd
319 def
320 """
321 def __init__(self, s, channel='stdout', suppress=True):
322 self.s = s
323 if isinstance(self.s, (str, _re_type)):
324 self.s = [self.s]
325 self.channel = channel
326 self.suppress = suppress
327
328 def __enter__(self):
329 self.orig_stream = getattr(sys, self.channel)
330 self.buffer = MyStringIO()
331 self.tee = Tee(self.buffer, channel=self.channel)
332 setattr(sys, self.channel, self.buffer if self.suppress else self.tee)
333
334 def __exit__(self, etype, value, traceback):
335 __tracebackhide__ = True
336
337 try:
338 if value is not None:
339 # If an error was raised, don't check anything else
340 return False
341 self.tee.flush()
342 setattr(sys, self.channel, self.orig_stream)
343 printed = self.buffer.getvalue()
344 for s in self.s:
345 if isinstance(s, _re_type):
346 assert s.search(printed), notprinted_msg.format(s.pattern, self.channel, printed)
347 else:
348 assert s in printed, notprinted_msg.format(s, self.channel, printed)
349 return False
350 finally:
351 self.tee.close()
352
353 printed_msg = """Found {0!r} in printed output (on {1}):
354 -------
355 {2!s}
356 -------
357 """
358
359 class AssertNotPrints(AssertPrints):
360 """Context manager for checking that certain output *isn't* produced.
361
362 Counterpart of AssertPrints"""
363 def __exit__(self, etype, value, traceback):
364 __tracebackhide__ = True
365
366 try:
367 if value is not None:
368 # If an error was raised, don't check anything else
369 self.tee.close()
370 return False
371 self.tee.flush()
372 setattr(sys, self.channel, self.orig_stream)
373 printed = self.buffer.getvalue()
374 for s in self.s:
375 if isinstance(s, _re_type):
376 assert not s.search(printed),printed_msg.format(
377 s.pattern, self.channel, printed)
378 else:
379 assert s not in printed, printed_msg.format(
380 s, self.channel, printed)
381 return False
382 finally:
383 self.tee.close()
384
385 @contextmanager
386 def make_tempfile(name):
387 """Create an empty, named, temporary file for the duration of the context."""
388 open(name, "w", encoding="utf-8").close()
389 try:
390 yield
391 finally:
392 os.unlink(name)
393
394 def fake_input(inputs):
395 """Temporarily replace the input() function to return the given values
396
397 Use as a context manager:
398
399 with fake_input(['result1', 'result2']):
400 ...
401
402 Values are returned in order. If input() is called again after the last value
403 was used, EOFError is raised.
404 """
405 it = iter(inputs)
406 def mock_input(prompt=''):
407 try:
408 return next(it)
409 except StopIteration as e:
410 raise EOFError('No more inputs given') from e
411
412 return patch('builtins.input', mock_input)
413
414 def help_output_test(subcommand=''):
415 """test that `ipython [subcommand] -h` works"""
416 cmd = get_ipython_cmd() + [subcommand, '-h']
417 out, err, rc = get_output_error_code(cmd)
418 assert rc == 0, err
419 assert "Traceback" not in err
420 assert "Options" in out
421 assert "--help-all" in out
422 return out, err
423
424
425 def help_all_output_test(subcommand=''):
426 """test that `ipython [subcommand] --help-all` works"""
427 cmd = get_ipython_cmd() + [subcommand, '--help-all']
428 out, err, rc = get_output_error_code(cmd)
429 assert rc == 0, err
430 assert "Traceback" not in err
431 assert "Options" in out
432 assert "Class" in out
433 return out, err
434