globalipapp.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. """Global IPython app to support test running.
  2. We must start our own ipython object and heavily muck with it so that all the
  3. modifications IPython makes to system behavior don't send the doctest machinery
  4. into a fit. This code should be considered a gross hack, but it gets the job
  5. done.
  6. """
  7. # Copyright (c) IPython Development Team.
  8. # Distributed under the terms of the Modified BSD License.
  9. import builtins as builtin_mod
  10. import sys
  11. import types
  12. from pathlib import Path
  13. from . import tools
  14. from IPython.core import page
  15. from IPython.utils import io
  16. from IPython.terminal.interactiveshell import TerminalInteractiveShell
  17. def get_ipython():
  18. # This will get replaced by the real thing once we start IPython below
  19. return start_ipython()
  20. # A couple of methods to override those in the running IPython to interact
  21. # better with doctest (doctest captures on raw stdout, so we need to direct
  22. # various types of output there otherwise it will miss them).
  23. def xsys(self, cmd):
  24. """Replace the default system call with a capturing one for doctest.
  25. """
  26. # We use getoutput, but we need to strip it because pexpect captures
  27. # the trailing newline differently from commands.getoutput
  28. print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout)
  29. sys.stdout.flush()
  30. def _showtraceback(self, etype, evalue, stb):
  31. """Print the traceback purely on stdout for doctest to capture it.
  32. """
  33. print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
  34. def start_ipython():
  35. """Start a global IPython shell, which we need for IPython-specific syntax.
  36. """
  37. global get_ipython
  38. # This function should only ever run once!
  39. if hasattr(start_ipython, 'already_called'):
  40. return
  41. start_ipython.already_called = True
  42. # Store certain global objects that IPython modifies
  43. _displayhook = sys.displayhook
  44. _excepthook = sys.excepthook
  45. _main = sys.modules.get('__main__')
  46. # Create custom argv and namespaces for our IPython to be test-friendly
  47. config = tools.default_config()
  48. config.TerminalInteractiveShell.simple_prompt = True
  49. # Create and initialize our test-friendly IPython instance.
  50. shell = TerminalInteractiveShell.instance(config=config,
  51. )
  52. # A few more tweaks needed for playing nicely with doctests...
  53. # remove history file
  54. shell.tempfiles.append(Path(config.HistoryManager.hist_file))
  55. # These traps are normally only active for interactive use, set them
  56. # permanently since we'll be mocking interactive sessions.
  57. shell.builtin_trap.activate()
  58. # Modify the IPython system call with one that uses getoutput, so that we
  59. # can capture subcommands and print them to Python's stdout, otherwise the
  60. # doctest machinery would miss them.
  61. shell.system = types.MethodType(xsys, shell)
  62. shell._showtraceback = types.MethodType(_showtraceback, shell)
  63. # IPython is ready, now clean up some global state...
  64. # Deactivate the various python system hooks added by ipython for
  65. # interactive convenience so we don't confuse the doctest system
  66. sys.modules['__main__'] = _main
  67. sys.displayhook = _displayhook
  68. sys.excepthook = _excepthook
  69. # So that ipython magics and aliases can be doctested (they work by making
  70. # a call into a global _ip object). Also make the top-level get_ipython
  71. # now return this without recursively calling here again.
  72. _ip = shell
  73. get_ipython = _ip.get_ipython
  74. builtin_mod._ip = _ip
  75. builtin_mod.ip = _ip
  76. builtin_mod.get_ipython = get_ipython
  77. # Override paging, so we don't require user interaction during the tests.
  78. def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
  79. if isinstance(strng, dict):
  80. strng = strng.get('text/plain', '')
  81. print(strng)
  82. page.orig_page = page.pager_page
  83. page.pager_page = nopage
  84. return _ip