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