test.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from contextlib import ExitStack
  2. from functools import wraps
  3. from unittest.mock import patch
  4. from .useracl import get_user_acl
  5. __all__ = ["patch_user_acl"]
  6. class patch_user_acl(ExitStack):
  7. """Testing utility that patches get_user_acl results
  8. Can be used as decorator or context manager.
  9. Accepts one or two arguments:
  10. - patch_user_acl(acl_patch)
  11. - patch_user_acl(user, acl_patch)
  12. Patch should be a dict or callable.
  13. """
  14. def __init__(self, *patches):
  15. super().__init__()
  16. self._patches = patches
  17. def patched_get_user_acl(self, user, cache_versions):
  18. user_acl = get_user_acl(user, cache_versions)
  19. self.apply_acl_patches(user, user_acl)
  20. return user_acl
  21. def apply_acl_patches(self, user, user_acl):
  22. for acl_patch in self._patches:
  23. self.apply_acl_patch(user, user_acl, acl_patch)
  24. def apply_acl_patch(self, user, user_acl, acl_patch):
  25. if callable(acl_patch):
  26. acl_patch(user, user_acl)
  27. else:
  28. user_acl.update(acl_patch)
  29. def __enter__(self):
  30. super().__enter__()
  31. self.enter_context(
  32. patch(
  33. "misago.acl.useracl.get_user_acl",
  34. side_effect=self.patched_get_user_acl,
  35. )
  36. )
  37. def __call__(self, f):
  38. @wraps(f)
  39. def inner(*args, **kwargs):
  40. with self:
  41. with patch(
  42. "misago.acl.useracl.get_user_acl",
  43. side_effect=self.patched_get_user_acl,
  44. ):
  45. return f(*args, **kwargs)
  46. return inner