|
| 1 | +import types |
| 2 | +import sys |
| 3 | +import builtins |
| 4 | +import os |
| 5 | +import pytest |
| 6 | +import pathlib |
| 7 | +import shutil |
| 8 | + |
| 9 | +from IPython.testing import tools |
| 10 | + |
| 11 | + |
| 12 | +def get_ipython(): |
| 13 | + from IPython.terminal.interactiveshell import TerminalInteractiveShell |
| 14 | + if TerminalInteractiveShell._instance: |
| 15 | + return TerminalInteractiveShell.instance() |
| 16 | + |
| 17 | + config = tools.default_config() |
| 18 | + config.TerminalInteractiveShell.simple_prompt = True |
| 19 | + |
| 20 | + # Create and initialize our test-friendly IPython instance. |
| 21 | + shell = TerminalInteractiveShell.instance(config=config) |
| 22 | + return shell |
| 23 | + |
| 24 | + |
| 25 | +@pytest.fixture(scope='session', autouse=True) |
| 26 | +def work_path(): |
| 27 | + path = pathlib.Path("./tmp-ipython-pytest-profiledir") |
| 28 | + os.environ["IPYTHONDIR"] = str(path.absolute()) |
| 29 | + if path.exists(): |
| 30 | + raise ValueError('IPython dir temporary path already exists ! Did previous test run exit successfully ?') |
| 31 | + path.mkdir() |
| 32 | + yield |
| 33 | + shutil.rmtree(str(path.resolve())) |
| 34 | + |
| 35 | + |
| 36 | +def nopage(strng, start=0, screen_lines=0, pager_cmd=None): |
| 37 | + if isinstance(strng, dict): |
| 38 | + strng = strng.get("text/plain", "") |
| 39 | + print(strng) |
| 40 | + |
| 41 | + |
| 42 | +def xsys(self, cmd): |
| 43 | + """Replace the default system call with a capturing one for doctest. |
| 44 | + """ |
| 45 | + # We use getoutput, but we need to strip it because pexpect captures |
| 46 | + # the trailing newline differently from commands.getoutput |
| 47 | + print(self.getoutput(cmd, split=False, depth=1).rstrip(), end="", file=sys.stdout) |
| 48 | + sys.stdout.flush() |
| 49 | + |
| 50 | + |
| 51 | +# for things to work correctly we would need this as a session fixture; |
| 52 | +# unfortunately this will fail on some test that get executed as _collection_ |
| 53 | +# time (before the fixture run), in particular parametrized test that contain |
| 54 | +# yields. so for now execute at import time. |
| 55 | +#@pytest.fixture(autouse=True, scope='session') |
| 56 | +def inject(): |
| 57 | + |
| 58 | + builtins.get_ipython = get_ipython |
| 59 | + builtins._ip = get_ipython() |
| 60 | + builtins.ip = get_ipython() |
| 61 | + builtins.ip.system = types.MethodType(xsys, ip) |
| 62 | + builtins.ip.builtin_trap.activate() |
| 63 | + from IPython.core import page |
| 64 | + |
| 65 | + page.pager_page = nopage |
| 66 | + # yield |
| 67 | + |
| 68 | + |
| 69 | +inject() |
0 commit comments