conftest.py 2.1 KB

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