Debian Codegraph @

tests/conftest.py

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