test_storages.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import pytest
  2. from django.core.files.base import ContentFile
  3. from s3file.storages_optimized import S3OptimizedUploadStorage
  4. class S3OptimizedMockStorage(S3OptimizedUploadStorage):
  5. created_objects = {}
  6. def _compress_content(self, content):
  7. return content
  8. class bucket:
  9. name = "test-bucket"
  10. class Object:
  11. def __init__(self, key):
  12. self.key = key
  13. self.copy_from_bucket = None
  14. self.copy_from_key = None
  15. S3OptimizedMockStorage.created_objects[self.key] = self
  16. def copy(self, s3_object, ExtraArgs):
  17. self.copy_from_bucket = s3_object["Bucket"]
  18. self.copy_from_key = s3_object["Key"]
  19. class TestStorages:
  20. url = "/__s3_mock__/"
  21. def test_post__save_optimized(self):
  22. storage = S3OptimizedMockStorage()
  23. obj = storage.bucket.Object("tmp/s3file/s3_file.txt")
  24. class Content:
  25. def __init__(self, obj):
  26. self.obj = obj
  27. content = Content(obj)
  28. key = storage._save("tmp/s3file/s3_file_copied.txt", content)
  29. stored_object = storage.created_objects[
  30. "custom/location/tmp/s3file/s3_file_copied.txt"
  31. ]
  32. assert key == "tmp/s3file/s3_file_copied.txt"
  33. assert stored_object.copy_from_bucket == storage.bucket.name
  34. assert stored_object.copy_from_key == "tmp/s3file/s3_file.txt"
  35. def test_post__save_optimized_gzip(self):
  36. storage = S3OptimizedMockStorage()
  37. obj = storage.bucket.Object("tmp/s3file/s3_file.css")
  38. storage.gzip = True
  39. class Content:
  40. def __init__(self, obj):
  41. self.obj = obj
  42. content = Content(obj)
  43. key = storage._save("tmp/s3file/s3_file_copied.css", content)
  44. stored_object = storage.created_objects[
  45. "custom/location/tmp/s3file/s3_file_copied.css"
  46. ]
  47. assert key == "tmp/s3file/s3_file_copied.css"
  48. assert stored_object.copy_from_bucket == storage.bucket.name
  49. assert stored_object.copy_from_key == "tmp/s3file/s3_file.css"
  50. def test_post__save_optimized_fail(self):
  51. storage = S3OptimizedMockStorage()
  52. with pytest.raises(TypeError) as excinfo:
  53. storage._save("tmp/s3file/s3_file_copied.txt", ContentFile(b"s3file"))
  54. assert "The content object must be a S3 object and contain a valid key." in str(
  55. excinfo.value
  56. )