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