conftest.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. import os.path
  3. import sys
  4. import pytest
  5. import borg.cache
  6. # needed to get pretty assertion failures in unit tests:
  7. if hasattr(pytest, 'register_assert_rewrite'):
  8. pytest.register_assert_rewrite('borg.testsuite')
  9. # This is a hack to fix path problems because "borg" (the package) is in the source root.
  10. # When importing the conftest an "import borg" can incorrectly import the borg from the
  11. # source root instead of the one installed in the environment.
  12. # The workaround is to remove entries pointing there from the path and check whether "borg"
  13. # is still importable. If it is not, then it has not been installed in the environment
  14. # and the entries are put back.
  15. original_path = list(sys.path)
  16. for entry in original_path:
  17. if entry == '' or entry == os.path.dirname(__file__):
  18. sys.path.remove(entry)
  19. try:
  20. import borg
  21. except ImportError:
  22. sys.path = original_path
  23. @pytest.fixture(autouse=True)
  24. def clean_env(tmpdir_factory, monkeypatch):
  25. # avoid that we access / modify the user's normal .config / .cache directory:
  26. monkeypatch.setenv('XDG_CONFIG_HOME', tmpdir_factory.mktemp('xdg-config-home'))
  27. monkeypatch.setenv('XDG_CACHE_HOME', tmpdir_factory.mktemp('xdg-cache-home'))
  28. # also avoid to use anything from the outside environment:
  29. keys = [key for key in os.environ if key.startswith('BORG_')]
  30. for key in keys:
  31. monkeypatch.delenv(key, raising=False)
  32. class DefaultPatches:
  33. def __init__(self, request):
  34. self.org_cache_wipe_cache = borg.cache.Cache.wipe_cache
  35. def wipe_should_not_be_called(*a, **kw):
  36. raise AssertionError("Cache wipe was triggered, if this is part of the test add @pytest.mark.allow_cache_wipe")
  37. if 'allow_cache_wipe' not in request.keywords:
  38. borg.cache.Cache.wipe_cache = wipe_should_not_be_called
  39. request.addfinalizer(self.undo)
  40. def undo(self):
  41. borg.cache.Cache.wipe_cache = self.org_cache_wipe_cache
  42. @pytest.fixture(autouse=True)
  43. def default_patches(request):
  44. return DefaultPatches(request)