Debian Codegraph @

envisage/tests/support.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # (C) Copyright 2007-2025 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10
11 """
12 Support utilities for tests in the Envisage test suite.
13
14 Note: this is intended to provide helpers for testing Envisage itself rather
15 than for external Envisage-based code. The helpers here should be considered
16 private to Envisage.
17 """
18
19 import contextlib
20 import pathlib
21 import subprocess
22 import sys
23 import tempfile
24 import unittest
25
26 from pkg_resources import resource_filename, working_set
27
28 from pyface.api import GUI
29 from traits.api import Int, List
30
31 from envisage.api import Application, ExtensionPoint, Plugin
32
33 # Skip decorator for tests that require a working GUI instance.
34 try:
35 GUI()
36 except NotImplementedError:
37 gui_available = False
38 else:
39 gui_available = True
40
41 requires_gui = unittest.skipUnless(
42 gui_available, "Test requires a non-null GUI backend"
43 )
44
45
46 # Test for PySide6 being installed
47 try:
48 import PySide6
49 except ImportError:
50 pyside6_available = False
51 pyside6_version = None
52 else:
53 pyside6_available = True
54 pyside6_version = PySide6.__version_info__
55 del PySide6
56
57
58 # Various useful context managers.
59
60
61 @contextlib.contextmanager
62 def temporary_directory():
63 """
64 Create and remove a temporary directory.
65
66 Yields a pathlib.Path instance.
67 """
68 with tempfile.TemporaryDirectory() as tempdir:
69 yield pathlib.Path(tempdir)
70
71
72 @contextlib.contextmanager
73 def restore_sys_path():
74 """
75 Save and restore `sys.path` state.
76
77 On entering the associated context, this context manager saves the state of
78 `sys.path`. Within the context, code may then make changes to that global
79 state (for example by adding distributions to the working set). On exiting
80 the context, `sys.path` is restored to its original state.
81 """
82 original_sys_path = sys.path[:]
83 try:
84 yield
85 finally:
86 sys.path[:] = original_sys_path
87
88
89 @contextlib.contextmanager
90 def restore_sys_modules():
91 """
92 Save and restore `sys.modules` state.
93
94 On entering the associated context, this context manager saves the state of
95 `sys.modules`. On exiting the context, any additional keys that were added
96 to `sys.modules` are removed.
97 """
98 original_modules = set(sys.modules)
99 try:
100 yield
101 finally:
102 for name in sys.modules.keys() - original_modules:
103 del sys.modules[name]
104
105
106 @contextlib.contextmanager
107 def restore_pkg_resources_working_set():
108 """
109 Save and restore `pkg_resources.working_set` state.
110
111 On entering the associated context, this context manager saves the state of
112 `pkg_resources.working_set`. Within the context, code may then make changes
113 to that global state (for example by adding distributions to the working
114 set). On exiting the context, `pkg_resources.working_set` is restored to
115 its original state.
116 """
117 original_entries = working_set.entries[:]
118 original_entry_keys = set(working_set.entry_keys)
119 original_by_key = set(working_set.by_key)
120 # Older setuptools versions don't have this attribute; it appears to
121 # be new in setuptools ~ 62.
122 if hasattr(working_set, "normalized_to_canonical_keys"):
123 original_normalized = set(working_set.normalized_to_canonical_keys)
124 else:
125 original_normalized = None
126 try:
127 yield
128 finally:
129 if original_normalized is not None:
130 for key in (
131 working_set.normalized_to_canonical_keys.keys()
132 - original_normalized
133 ):
134 del working_set.normalized_to_canonical_keys[key]
135 for key in working_set.by_key.keys() - original_by_key:
136 del working_set.by_key[key]
137 for key in working_set.entry_keys.keys() - original_entry_keys:
138 del working_set.entry_keys[key]
139 working_set.entries[:] = original_entries
140
141
142 # Egg and package-related functionality.
143
144
145 def build_egg(package_dir, dist_dir):
146 """Helper function to build an egg.
147
148 Parameters
149 ----------
150 package_dir : pathlib.Path
151 Directory containing the Python package to be built. Should
152 contain a "setup.py" file that can be used with
153 "python setup.py bdist_egg" to build the package.
154 dist_dir : pathlib.Path
155 Directory to place the built egg in. The directory should
156 already exist.
157 """
158 subprocess.run(
159 [
160 sys.executable,
161 "setup.py",
162 "bdist_egg",
163 "--dist-dir",
164 dist_dir,
165 ],
166 cwd=package_dir,
167 check=True,
168 stdout=subprocess.PIPE,
169 stderr=subprocess.PIPE,
170 )
171
172
173 # Packages containing plugins that are used for testing
174
175 _PACKAGES_DIR = pathlib.Path(resource_filename("envisage.tests", "eggs"))
176 PLUGIN_PACKAGES = [
177 _PACKAGES_DIR / "acme-bar",
178 _PACKAGES_DIR / "acme-baz",
179 _PACKAGES_DIR / "acme-foo",
180 ]
181
182 # acme-bad contains a plugin that depends on a non-existent module.
183 _BAD_PACKAGES_DIR = pathlib.Path(
184 resource_filename("envisage.tests", "bad_eggs")
185 )
186 BAD_PLUGIN_PACKAGES = [_BAD_PACKAGES_DIR / "acme-bad"]
187
188
189 # Application class used in various tests.
190
191
192 class SimpleApplication(Application):
193 """The type of application used in the tests."""
194
195 id = "test"
196
197
198 # Plugins used in multiple tests.
199
200
201 class PluginA(Plugin):
202 """A plugin that offers an extension point."""
203
204 id = "A"
205 x = ExtensionPoint(List, id="a.x")
206
207
208 class PluginB(Plugin):
209 """A plugin that contributes to an extension point."""
210
211 id = "B"
212 x = List(Int, [1, 2, 3], contributes_to="a.x")
213
214
215 class PluginC(Plugin):
216 """Another plugin that contributes to an extension point!"""
217
218 id = "C"
219 x = List(Int, [98, 99, 100], contributes_to="a.x")