test_s3_gateway.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # -*- coding: utf-8 -*-
  2. # (c) Nelen & Schuurmans
  3. import io
  4. from datetime import datetime
  5. from unittest import mock
  6. import boto3
  7. import pytest
  8. from botocore.exceptions import ClientError
  9. from clean_python import DoesNotExist
  10. from clean_python import Filter
  11. from clean_python import PageOptions
  12. from clean_python.s3 import S3BucketOptions
  13. from clean_python.s3 import S3BucketProvider
  14. from clean_python.s3 import S3Gateway
  15. @pytest.fixture(scope="session")
  16. def s3_settings(s3_url):
  17. minio_settings = {
  18. "url": s3_url,
  19. "access_key": "cleanpython",
  20. "secret_key": "cleanpython",
  21. "bucket": "cleanpython-test",
  22. "region": None,
  23. }
  24. if not minio_settings["bucket"].endswith("-test"): # type: ignore
  25. pytest.exit("Not running against a test minio bucket?! 😱")
  26. return minio_settings.copy()
  27. @pytest.fixture(scope="session")
  28. def s3_bucket(s3_settings):
  29. s3 = boto3.resource(
  30. "s3",
  31. endpoint_url=s3_settings["url"],
  32. aws_access_key_id=s3_settings["access_key"],
  33. aws_secret_access_key=s3_settings["secret_key"],
  34. )
  35. bucket = s3.Bucket(s3_settings["bucket"])
  36. # ensure existence
  37. try:
  38. bucket.create()
  39. except ClientError as e:
  40. if "BucketAlreadyOwnedByYou" in str(e):
  41. pass
  42. return bucket
  43. @pytest.fixture
  44. def s3_provider(s3_bucket, s3_settings):
  45. # wipe contents before each test
  46. s3_bucket.objects.all().delete()
  47. return S3BucketProvider(S3BucketOptions(**s3_settings))
  48. @pytest.fixture
  49. def s3_gateway(s3_provider):
  50. return S3Gateway(s3_provider)
  51. @pytest.fixture
  52. def object_in_s3(s3_bucket):
  53. s3_bucket.upload_fileobj(io.BytesIO(b"foo"), "object-in-s3")
  54. return "object-in-s3"
  55. @pytest.fixture
  56. def local_file(tmp_path):
  57. path = tmp_path / "test-upload.txt"
  58. path.write_bytes(b"foo")
  59. return path
  60. async def test_upload_file(s3_gateway: S3Gateway, local_file):
  61. object_name = "test-upload-file"
  62. await s3_gateway.upload_file(object_name, local_file)
  63. assert (await s3_gateway.get(object_name))["size"] == 3
  64. async def test_upload_file_does_not_exist(s3_gateway: S3Gateway, tmp_path):
  65. path = tmp_path / "test-upload.txt"
  66. object_name = "test-upload-file"
  67. with pytest.raises(FileNotFoundError):
  68. await s3_gateway.upload_file(object_name, path)
  69. async def test_download_file(s3_gateway: S3Gateway, object_in_s3, tmp_path):
  70. path = tmp_path / "test-download.txt"
  71. await s3_gateway.download_file(object_in_s3, path)
  72. assert path.read_bytes() == b"foo"
  73. async def test_download_file_path_already_exists(
  74. s3_gateway: S3Gateway, object_in_s3, tmp_path
  75. ):
  76. path = tmp_path / "test-download.txt"
  77. path.write_bytes(b"bar")
  78. with pytest.raises(FileExistsError):
  79. await s3_gateway.download_file(object_in_s3, path)
  80. assert path.read_bytes() == b"bar"
  81. async def test_download_file_does_not_exist(s3_gateway: S3Gateway, s3_bucket, tmp_path):
  82. path = tmp_path / "test-download-does-not-exist.txt"
  83. with pytest.raises(DoesNotExist):
  84. await s3_gateway.download_file("some-nonexisting", path)
  85. assert not path.exists()
  86. async def test_remove(s3_gateway: S3Gateway, s3_bucket, object_in_s3):
  87. await s3_gateway.remove(object_in_s3)
  88. assert await s3_gateway.get(object_in_s3) is None
  89. async def test_remove_does_not_exist(s3_gateway: S3Gateway, s3_bucket):
  90. await s3_gateway.remove("non-existing")
  91. @pytest.fixture
  92. def multiple_objects(s3_bucket):
  93. s3_bucket.upload_fileobj(io.BytesIO(b"a"), "raster-1/bla")
  94. s3_bucket.upload_fileobj(io.BytesIO(b"ab"), "raster-2/bla")
  95. s3_bucket.upload_fileobj(io.BytesIO(b"abc"), "raster-2/foo")
  96. s3_bucket.upload_fileobj(io.BytesIO(b"abcde"), "raster-2/bz")
  97. return ["raster-1/bla", "raster-2/bla", "raster-2/foo", "raster-2/bz"]
  98. async def test_remove_multiple(s3_gateway: S3Gateway, multiple_objects):
  99. await s3_gateway.remove_multiple(multiple_objects[:2])
  100. for key in multiple_objects[:2]:
  101. assert await s3_gateway.get(key) is None
  102. for key in multiple_objects[2:]:
  103. assert await s3_gateway.get(key) is not None
  104. async def test_remove_multiple_empty_list(s3_gateway: S3Gateway, s3_bucket):
  105. await s3_gateway.remove_multiple([])
  106. async def test_remove_filtered_all(s3_gateway: S3Gateway, multiple_objects):
  107. await s3_gateway.remove_filtered([])
  108. for key in multiple_objects:
  109. assert await s3_gateway.get(key) is None
  110. async def test_remove_filtered_prefix(s3_gateway: S3Gateway, multiple_objects):
  111. await s3_gateway.remove_filtered([Filter(field="prefix", values=["raster-2/"])])
  112. assert await s3_gateway.get(multiple_objects[0]) is not None
  113. for key in multiple_objects[1:]:
  114. assert await s3_gateway.get(key) is None
  115. @mock.patch("clean_python.s3.s3_gateway.AWS_LIMIT", new=1)
  116. async def test_remove_filtered_pagination(s3_gateway: S3Gateway, multiple_objects):
  117. await s3_gateway.remove_filtered([Filter(field="prefix", values=["raster-2/"])])
  118. assert await s3_gateway.get(multiple_objects[0]) is not None
  119. for key in multiple_objects[1:]:
  120. assert await s3_gateway.get(key) is None
  121. async def test_filter(s3_gateway: S3Gateway, multiple_objects):
  122. actual = await s3_gateway.filter([], params=PageOptions(limit=10))
  123. assert len(actual) == 4
  124. assert actual[0]["id"] == "raster-1/bla"
  125. assert isinstance(actual[0]["last_modified"], datetime)
  126. assert actual[0]["etag"] == "0cc175b9c0f1b6a831c399e269772661"
  127. assert actual[0]["size"] == 1
  128. async def test_filter_empty(s3_gateway: S3Gateway, s3_bucket):
  129. actual = await s3_gateway.filter([], params=PageOptions(limit=10))
  130. assert actual == []
  131. async def test_filter_with_limit(s3_gateway: S3Gateway, multiple_objects):
  132. actual = await s3_gateway.filter([], params=PageOptions(limit=2))
  133. assert len(actual) == 2
  134. assert actual[0]["id"] == "raster-1/bla"
  135. assert actual[1]["id"] == "raster-2/bla"
  136. async def test_filter_with_cursor(s3_gateway: S3Gateway, multiple_objects):
  137. actual = await s3_gateway.filter(
  138. [], params=PageOptions(limit=3, cursor="raster-2/bla")
  139. )
  140. assert len(actual) == 2
  141. assert actual[0]["id"] == "raster-2/bz"
  142. assert actual[1]["id"] == "raster-2/foo"
  143. async def test_filter_by_prefix(s3_gateway: S3Gateway, multiple_objects):
  144. actual = await s3_gateway.filter([Filter(field="prefix", values=["raster-1/"])])
  145. assert len(actual) == 1
  146. actual = await s3_gateway.filter([Filter(field="prefix", values=["raster-2/"])])
  147. assert len(actual) == 3
  148. async def test_get(s3_gateway: S3Gateway, object_in_s3):
  149. actual = await s3_gateway.get(object_in_s3)
  150. assert actual["id"] == "object-in-s3"
  151. assert isinstance(actual["last_modified"], datetime)
  152. assert actual["etag"] == "acbd18db4cc2f85cedef654fccc4a4d8"
  153. assert actual["size"] == 3
  154. async def test_get_does_not_exist(s3_gateway: S3Gateway):
  155. actual = await s3_gateway.get("non-existing")
  156. assert actual is None