Debian Codegraph @

tests/conftest.py

raw
1 import logging
2 import os
3 import sys
4 import termios
5
6 import pytest
7 from unittest.mock import patch
8
9 from _util import support
10
11 # Set up icecream globally for convenience.
12 from icecream import install
13
14 install()
15
16
17 # pytest seems to tweak logging such that Invoke's debug logs go to stderr,
18 # which is then hella spammy if one is using --capture=no (which one must in
19 # order to test low level terminal IO stuff, as we do!)
20 # So, we explicitly turn default logging back down.
21 # NOTE: no real better place to put this than here
22 # TODO: see if we can use modern pytest's logging functionality to remove the
23 # need for this, now that pytest-relaxed was modernized
24 logging.basicConfig(level=logging.INFO)
25
26
27 @pytest.fixture(autouse=True)
28 def fake_user_home():
29 # Ignore any real user homedir for purpose of testing.
30 # This allows, for example, a user who has real Invoke configs in their
31 # homedir to still run the test suite safely.
32 # TODO: this is still a bit of a kludge & doesn't solve systemwide configs
33 with patch("invoke.config.expanduser", side_effect=lambda x: x):
34 yield
35
36
37 @pytest.fixture
38 def reset_environ():
39 """
40 Resets `os.environ` to its prior state after the fixtured test finishes.
41 """
42 old_environ = os.environ.copy()
43 yield
44 os.environ.clear()
45 os.environ.update(old_environ)
46
47
48 @pytest.fixture
49 def chdir_support():
50 # Always do things relative to tests/_support
51 os.chdir(support)
52 yield
53 # Chdir back to project root to avoid problems
54 os.chdir(os.path.join(os.path.dirname(__file__), ".."))
55
56
57 @pytest.fixture
58 def clean_sys_modules():
59 """
60 Attempt to nix any imports incurred by the test, to prevent state bleed.
61
62 In some cases this prevents outright errors (eg a test accidentally relying
63 on another's import of a task tree in the support folder) and in others
64 it's required because we're literally testing runtime imports.
65 """
66 snapshot = sys.modules.copy()
67 yield
68 # Iterate over another copy to avoid ye olde mutate-during-iterate problem
69 # NOTE: cannot simply 'sys.modules = snapshot' as that is warned against
70 for name, module in sys.modules.copy().items():
71 # Delete anything newly added (imported)
72 if name not in snapshot:
73 del sys.modules[name]
74 # Overwrite anything that was modified (the easy version...)
75 sys.modules.update(snapshot)
76
77
78 @pytest.fixture
79 def integration(reset_environ, chdir_support, clean_sys_modules):
80 yield
81
82
83 @pytest.fixture
84 def mock_termios():
85 with patch("invoke.terminals.termios") as mocked:
86 # Ensure mocked termios has 'real' values for constants...otherwise
87 # doing bit arithmetic on Mocks kinda defeats the point.
88 mocked.ECHO = termios.ECHO
89 mocked.ICANON = termios.ICANON
90 mocked.VMIN = termios.VMIN
91 mocked.VTIME = termios.VTIME
92 yield mocked