pythonpath.py 709 B

123456789101112131415161718192021222324
  1. import sys
  2. import pytest
  3. from pytest import Config
  4. from pytest import Parser
  5. def pytest_addoption(parser: Parser) -> None:
  6. parser.addini("pythonpath", type="paths", help="Add paths to sys.path", default=[])
  7. @pytest.hookimpl(tryfirst=True)
  8. def pytest_load_initial_conftests(early_config: Config) -> None:
  9. # `pythonpath = a b` will set `sys.path` to `[a, b, x, y, z, ...]`
  10. for path in reversed(early_config.getini("pythonpath")):
  11. sys.path.insert(0, str(path))
  12. @pytest.hookimpl(trylast=True)
  13. def pytest_unconfigure(config: Config) -> None:
  14. for path in config.getini("pythonpath"):
  15. path_str = str(path)
  16. if path_str in sys.path:
  17. sys.path.remove(path_str)