Debian Codegraph @

testing/test_pluginmanager.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import os
5 import shutil
6 import sys
7 import types
8
9 from _pytest.config import Config
10 from _pytest.config import ExitCode
11 from _pytest.config import PytestPluginManager
12 from _pytest.config.exceptions import UsageError
13 from _pytest.main import Session
14 from _pytest.monkeypatch import MonkeyPatch
15 from _pytest.pathlib import import_path
16 from _pytest.pytester import Pytester
17 import pytest
18
19
20 @pytest.fixture
21 def pytestpm() -> PytestPluginManager:
22 return PytestPluginManager()
23
24
25 class TestPytestPluginInteractions:
26 def test_addhooks_conftestplugin(
27 self, pytester: Pytester, _config_for_test: Config
28 ) -> None:
29 pytester.makepyfile(
30 newhooks="""
31 def pytest_myhook(xyz):
32 "new hook"
33 """
34 )
35 conf = pytester.makeconftest(
36 """
37 import newhooks
38 def pytest_addhooks(pluginmanager):
39 pluginmanager.add_hookspecs(newhooks)
40 def pytest_myhook(xyz):
41 return xyz + 1
42 """
43 )
44 config = _config_for_test
45 pm = config.pluginmanager
46 pm.hook.pytest_addhooks.call_historic(
47 kwargs=dict(pluginmanager=config.pluginmanager)
48 )
49 config.pluginmanager._importconftest(
50 conf,
51 importmode="prepend",
52 rootpath=pytester.path,
53 consider_namespace_packages=False,
54 )
55 # print(config.pluginmanager.get_plugins())
56 res = config.hook.pytest_myhook(xyz=10)
57 assert res == [11]
58
59 def test_addhooks_nohooks(self, pytester: Pytester) -> None:
60 pytester.makeconftest(
61 """
62 import sys
63 def pytest_addhooks(pluginmanager):
64 pluginmanager.add_hookspecs(sys)
65 """
66 )
67 res = pytester.runpytest()
68 assert res.ret != 0
69 res.stderr.fnmatch_lines(["*did not find*sys*"])
70
71 def test_do_option_postinitialize(self, pytester: Pytester) -> None:
72 config = pytester.parseconfigure()
73 assert not hasattr(config.option, "test123")
74 p = pytester.makepyfile(
75 """
76 def pytest_addoption(parser):
77 parser.addoption('--test123', action="store_true",
78 default=True)
79 """
80 )
81 config.pluginmanager._importconftest(
82 p,
83 importmode="prepend",
84 rootpath=pytester.path,
85 consider_namespace_packages=False,
86 )
87 assert config.option.test123
88
89 def test_configure(self, pytester: Pytester) -> None:
90 config = pytester.parseconfig()
91 values = []
92
93 class A:
94 def pytest_configure(self):
95 values.append(self)
96
97 config.pluginmanager.register(A())
98 assert len(values) == 0
99 config._do_configure()
100 assert len(values) == 1
101 config.pluginmanager.register(A()) # leads to a configured() plugin
102 assert len(values) == 2
103 assert values[0] != values[1]
104
105 config._ensure_unconfigure()
106 config.pluginmanager.register(A())
107 assert len(values) == 2
108
109 @pytest.mark.skipif(
110 not sys.platform.startswith("win"),
111 reason="requires a case-insensitive file system",
112 )
113 def test_conftestpath_case_sensitivity(self, pytester: Pytester) -> None:
114 """Unit test for issue #9765."""
115 config = pytester.parseconfig()
116 pytester.makepyfile(**{"tests/conftest.py": ""})
117
118 conftest = pytester.path.joinpath("tests/conftest.py")
119 conftest_upper_case = pytester.path.joinpath("TESTS/conftest.py")
120
121 mod = config.pluginmanager._importconftest(
122 conftest,
123 importmode="prepend",
124 rootpath=pytester.path,
125 consider_namespace_packages=False,
126 )
127 plugin = config.pluginmanager.get_plugin(str(conftest))
128 assert plugin is mod
129
130 mod_uppercase = config.pluginmanager._importconftest(
131 conftest_upper_case,
132 importmode="prepend",
133 rootpath=pytester.path,
134 consider_namespace_packages=False,
135 )
136 plugin_uppercase = config.pluginmanager.get_plugin(str(conftest_upper_case))
137 assert plugin_uppercase is mod_uppercase
138
139 # No str(conftestpath) normalization so conftest should be imported
140 # twice and modules should be different objects
141 assert mod is not mod_uppercase
142
143 def test_hook_tracing(self, _config_for_test: Config) -> None:
144 pytestpm = _config_for_test.pluginmanager # fully initialized with plugins
145 saveindent = []
146
147 class api1:
148 def pytest_plugin_registered(self):
149 saveindent.append(pytestpm.trace.root.indent)
150
151 class api2:
152 def pytest_plugin_registered(self):
153 saveindent.append(pytestpm.trace.root.indent)
154 raise ValueError()
155
156 values: list[str] = []
157 pytestpm.trace.root.setwriter(values.append)
158 undo = pytestpm.enable_tracing()
159 try:
160 indent = pytestpm.trace.root.indent
161 p = api1()
162 pytestpm.register(p)
163 assert pytestpm.trace.root.indent == indent
164 assert len(values) >= 2
165 assert "pytest_plugin_registered" in values[0]
166 assert "finish" in values[1]
167
168 values[:] = []
169 with pytest.raises(ValueError):
170 pytestpm.register(api2())
171 assert pytestpm.trace.root.indent == indent
172 assert saveindent[0] > indent
173 finally:
174 undo()
175
176 def test_hook_proxy(self, pytester: Pytester) -> None:
177 """Test the gethookproxy function(#2016)"""
178 config = pytester.parseconfig()
179 session = Session.from_config(config)
180 pytester.makepyfile(**{"tests/conftest.py": "", "tests/subdir/conftest.py": ""})
181
182 conftest1 = pytester.path.joinpath("tests/conftest.py")
183 conftest2 = pytester.path.joinpath("tests/subdir/conftest.py")
184
185 config.pluginmanager._importconftest(
186 conftest1,
187 importmode="prepend",
188 rootpath=pytester.path,
189 consider_namespace_packages=False,
190 )
191 ihook_a = session.gethookproxy(pytester.path / "tests")
192 assert ihook_a is not None
193 config.pluginmanager._importconftest(
194 conftest2,
195 importmode="prepend",
196 rootpath=pytester.path,
197 consider_namespace_packages=False,
198 )
199 ihook_b = session.gethookproxy(pytester.path / "tests")
200 assert ihook_a is not ihook_b
201
202 def test_hook_with_addoption(self, pytester: Pytester) -> None:
203 """Test that hooks can be used in a call to pytest_addoption"""
204 pytester.makepyfile(
205 newhooks="""
206 import pytest
207 @pytest.hookspec(firstresult=True)
208 def pytest_default_value():
209 pass
210 """
211 )
212 pytester.makepyfile(
213 myplugin="""
214 import newhooks
215 def pytest_addhooks(pluginmanager):
216 pluginmanager.add_hookspecs(newhooks)
217 def pytest_addoption(parser, pluginmanager):
218 default_value = pluginmanager.hook.pytest_default_value()
219 parser.addoption("--config", help="Config, defaults to %(default)s", default=default_value)
220 """
221 )
222 pytester.makeconftest(
223 """
224 pytest_plugins=("myplugin",)
225 def pytest_default_value():
226 return "default_value"
227 """
228 )
229 res = pytester.runpytest("--help")
230 res.stdout.fnmatch_lines(["*--config=CONFIG*default_value*"])
231
232
233 def test_default_markers(pytester: Pytester) -> None:
234 result = pytester.runpytest("--markers")
235 result.stdout.fnmatch_lines(["*tryfirst*first*", "*trylast*last*"])
236
237
238 def test_importplugin_error_message(
239 pytester: Pytester, pytestpm: PytestPluginManager
240 ) -> None:
241 """Don't hide import errors when importing plugins and provide
242 an easy to debug message.
243
244 See #375 and #1998.
245 """
246 pytester.syspathinsert(pytester.path)
247 pytester.makepyfile(
248 qwe="""\
249 def test_traceback():
250 raise ImportError('Not possible to import: ☺')
251 test_traceback()
252 """
253 )
254 with pytest.raises(ImportError) as excinfo:
255 pytestpm.import_plugin("qwe")
256
257 assert str(excinfo.value).endswith(
258 'Error importing plugin "qwe": Not possible to import: ☺'
259 )
260 assert "in test_traceback" in str(excinfo.traceback[-1])
261
262
263 class TestPytestPluginManager:
264 def test_register_imported_modules(self) -> None:
265 pm = PytestPluginManager()
266 mod = types.ModuleType("x.y.pytest_hello")
267 pm.register(mod)
268 assert pm.is_registered(mod)
269 values = pm.get_plugins()
270 assert mod in values
271 with pytest.raises(ValueError):
272 pm.register(mod)
273 with pytest.raises(ValueError):
274 pm.register(mod)
275 # assert not pm.is_registered(mod2)
276 assert pm.get_plugins() == values
277
278 def test_canonical_import(self, monkeypatch):
279 mod = types.ModuleType("pytest_xyz")
280 monkeypatch.setitem(sys.modules, "pytest_xyz", mod)
281 pm = PytestPluginManager()
282 pm.import_plugin("pytest_xyz")
283 assert pm.get_plugin("pytest_xyz") == mod
284 assert pm.is_registered(mod)
285
286 def test_consider_module(
287 self, pytester: Pytester, pytestpm: PytestPluginManager
288 ) -> None:
289 pytester.syspathinsert()
290 pytester.makepyfile(pytest_p1="#")
291 pytester.makepyfile(pytest_p2="#")
292 mod = types.ModuleType("temp")
293 mod.__dict__["pytest_plugins"] = ["pytest_p1", "pytest_p2"]
294 pytestpm.consider_module(mod)
295 p1 = pytestpm.get_plugin("pytest_p1")
296 assert p1 is not None
297 assert p1.__name__ == "pytest_p1"
298 p2 = pytestpm.get_plugin("pytest_p2")
299 assert p2 is not None
300 assert p2.__name__ == "pytest_p2"
301
302 def test_consider_module_import_module(
303 self, pytester: Pytester, _config_for_test: Config
304 ) -> None:
305 pytestpm = _config_for_test.pluginmanager
306 mod = types.ModuleType("x")
307 mod.__dict__["pytest_plugins"] = "pytest_a"
308 aplugin = pytester.makepyfile(pytest_a="#")
309 reprec = pytester.make_hook_recorder(pytestpm)
310 pytester.syspathinsert(aplugin.parent)
311 pytestpm.consider_module(mod)
312 call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)
313 assert call.plugin.__name__ == "pytest_a"
314
315 # check that it is not registered twice
316 pytestpm.consider_module(mod)
317 values = reprec.getcalls("pytest_plugin_registered")
318 assert len(values) == 1
319
320 def test_consider_env_fails_to_import(
321 self, monkeypatch: MonkeyPatch, pytestpm: PytestPluginManager
322 ) -> None:
323 monkeypatch.setenv("PYTEST_PLUGINS", "nonexisting", prepend=",")
324 with pytest.raises(ImportError):
325 pytestpm.consider_env()
326
327 @pytest.mark.filterwarnings("always")
328 def test_plugin_skip(self, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
329 p = pytester.makepyfile(
330 skipping1="""
331 import pytest
332 pytest.skip("hello", allow_module_level=True)
333 """
334 )
335 shutil.copy(p, p.with_name("skipping2.py"))
336 monkeypatch.setenv("PYTEST_PLUGINS", "skipping2")
337 result = pytester.runpytest("-p", "skipping1", syspathinsert=True)
338 assert result.ret == ExitCode.NO_TESTS_COLLECTED
339 result.stdout.fnmatch_lines(
340 ["*skipped plugin*skipping1*hello*", "*skipped plugin*skipping2*hello*"]
341 )
342
343 def test_consider_env_plugin_instantiation(
344 self,
345 pytester: Pytester,
346 monkeypatch: MonkeyPatch,
347 pytestpm: PytestPluginManager,
348 ) -> None:
349 pytester.syspathinsert()
350 pytester.makepyfile(xy123="#")
351 monkeypatch.setitem(os.environ, "PYTEST_PLUGINS", "xy123")
352 l1 = len(pytestpm.get_plugins())
353 pytestpm.consider_env()
354 l2 = len(pytestpm.get_plugins())
355 assert l2 == l1 + 1
356 assert pytestpm.get_plugin("xy123")
357 pytestpm.consider_env()
358 l3 = len(pytestpm.get_plugins())
359 assert l2 == l3
360
361 def test_pluginmanager_ENV_startup(
362 self, pytester: Pytester, monkeypatch: MonkeyPatch
363 ) -> None:
364 pytester.makepyfile(pytest_x500="#")
365 p = pytester.makepyfile(
366 """
367 import pytest
368 def test_hello(pytestconfig):
369 plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')
370 assert plugin is not None
371 """
372 )
373 monkeypatch.setenv("PYTEST_PLUGINS", "pytest_x500", prepend=",")
374 result = pytester.runpytest(p, syspathinsert=True)
375 assert result.ret == 0
376 result.stdout.fnmatch_lines(["*1 passed*"])
377
378 def test_import_plugin_importname(
379 self, pytester: Pytester, pytestpm: PytestPluginManager
380 ) -> None:
381 with pytest.raises(ImportError):
382 pytestpm.import_plugin("qweqwex.y")
383 with pytest.raises(ImportError):
384 pytestpm.import_plugin("pytest_qweqwx.y")
385
386 pytester.syspathinsert()
387 pluginname = "pytest_hello"
388 pytester.makepyfile(**{pluginname: ""})
389 pytestpm.import_plugin("pytest_hello")
390 len1 = len(pytestpm.get_plugins())
391 pytestpm.import_plugin("pytest_hello")
392 len2 = len(pytestpm.get_plugins())
393 assert len1 == len2
394 plugin1 = pytestpm.get_plugin("pytest_hello")
395 assert plugin1 is not None
396 assert plugin1.__name__.endswith("pytest_hello")
397 plugin2 = pytestpm.get_plugin("pytest_hello")
398 assert plugin2 is plugin1
399
400 def test_import_plugin_dotted_name(
401 self, pytester: Pytester, pytestpm: PytestPluginManager
402 ) -> None:
403 with pytest.raises(ImportError):
404 pytestpm.import_plugin("qweqwex.y")
405 with pytest.raises(ImportError):
406 pytestpm.import_plugin("pytest_qweqwex.y")
407
408 pytester.syspathinsert()
409 pytester.mkpydir("pkg").joinpath("plug.py").write_text("x=3", encoding="utf-8")
410 pluginname = "pkg.plug"
411 pytestpm.import_plugin(pluginname)
412 mod = pytestpm.get_plugin("pkg.plug")
413 assert mod is not None
414 assert mod.x == 3
415
416 def test_consider_conftest_deps(
417 self,
418 pytester: Pytester,
419 pytestpm: PytestPluginManager,
420 ) -> None:
421 mod = import_path(
422 pytester.makepyfile("pytest_plugins='xyz'"),
423 root=pytester.path,
424 consider_namespace_packages=False,
425 )
426 with pytest.raises(ImportError):
427 pytestpm.consider_conftest(mod, registration_name="unused")
428
429
430 class TestPytestPluginManagerBootstrapping:
431 def test_preparse_args(self, pytestpm: PytestPluginManager) -> None:
432 with pytest.raises(ImportError):
433 pytestpm.consider_preparse(["xyz", "-p", "hello123"])
434
435 # Handles -p without space (#3532).
436 with pytest.raises(ImportError) as excinfo:
437 pytestpm.consider_preparse(["-phello123"])
438 assert '"hello123"' in excinfo.value.args[0]
439 pytestpm.consider_preparse(["-pno:hello123"])
440
441 # Handles -p without following arg (when used without argparse).
442 pytestpm.consider_preparse(["-p"])
443
444 with pytest.raises(UsageError, match=r"^plugin main cannot be disabled$"):
445 pytestpm.consider_preparse(["-p", "no:main"])
446
447 def test_plugin_prevent_register(self, pytestpm: PytestPluginManager) -> None:
448 pytestpm.consider_preparse(["xyz", "-p", "no:abc"])
449 l1 = pytestpm.get_plugins()
450 pytestpm.register(42, name="abc")
451 l2 = pytestpm.get_plugins()
452 assert len(l2) == len(l1)
453 assert 42 not in l2
454
455 def test_plugin_prevent_register_unregistered_already_registered(
456 self, pytestpm: PytestPluginManager
457 ) -> None:
458 pytestpm.register(42, name="abc")
459 l1 = pytestpm.get_plugins()
460 assert 42 in l1
461 pytestpm.consider_preparse(["xyz", "-p", "no:abc"])
462 l2 = pytestpm.get_plugins()
463 assert 42 not in l2
464
465 def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister(
466 self, pytestpm: PytestPluginManager
467 ) -> None:
468 """From PR #4304: The only way to unregister a module is documented at
469 the end of https://docs.pytest.org/en/stable/how-to/plugins.html.
470
471 When unregister cacheprovider, then unregister stepwise too.
472 """
473 pytestpm.register(42, name="cacheprovider")
474 pytestpm.register(43, name="stepwise")
475 l1 = pytestpm.get_plugins()
476 assert 42 in l1
477 assert 43 in l1
478 pytestpm.consider_preparse(["xyz", "-p", "no:cacheprovider"])
479 l2 = pytestpm.get_plugins()
480 assert 42 not in l2
481 assert 43 not in l2
482
483 def test_blocked_plugin_can_be_used(self, pytestpm: PytestPluginManager) -> None:
484 pytestpm.consider_preparse(["xyz", "-p", "no:abc", "-p", "abc"])
485
486 assert pytestpm.has_plugin("abc")
487 assert not pytestpm.is_blocked("abc")
488 assert not pytestpm.is_blocked("pytest_abc")