tencent_cos.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import os
  2. from unittest.mock import MagicMock
  3. import pytest
  4. from _pytest.monkeypatch import MonkeyPatch
  5. from qcloud_cos import CosS3Client # type: ignore
  6. from qcloud_cos.streambody import StreamBody # type: ignore
  7. from tests.unit_tests.oss.__mock.base import (
  8. get_example_bucket,
  9. get_example_data,
  10. get_example_filename,
  11. get_example_filepath,
  12. )
  13. class MockTencentCosClass:
  14. def __init__(self, conf, retry=1, session=None):
  15. self.bucket_name = get_example_bucket()
  16. self.key = get_example_filename()
  17. self.content = get_example_data()
  18. self.filepath = get_example_filepath()
  19. self.resp = {
  20. "ETag": "ee8de918d05640145b18f70f4c3aa602",
  21. "Server": "tencent-cos",
  22. "x-cos-hash-crc64ecma": 16749565679157681890,
  23. "x-cos-request-id": "NWU5MDNkYzlfNjRiODJhMDlfMzFmYzhfMTFm****",
  24. }
  25. def put_object(self, Bucket, Body, Key, EnableMD5=False, **kwargs): # noqa: N803
  26. assert Bucket == self.bucket_name
  27. assert Key == self.key
  28. assert Body == self.content
  29. return self.resp
  30. def get_object(self, Bucket, Key, KeySimplifyCheck=True, **kwargs): # noqa: N803
  31. assert Bucket == self.bucket_name
  32. assert Key == self.key
  33. mock_stream_body = MagicMock(StreamBody)
  34. mock_raw_stream = MagicMock()
  35. mock_stream_body.get_raw_stream.return_value = mock_raw_stream
  36. mock_raw_stream.read.return_value = self.content
  37. mock_stream_body.get_stream_to_file = MagicMock()
  38. def chunk_generator(chunk_size=2):
  39. for i in range(0, len(self.content), chunk_size):
  40. yield self.content[i : i + chunk_size]
  41. mock_stream_body.get_stream.return_value = chunk_generator(chunk_size=4096)
  42. return {"Body": mock_stream_body}
  43. def object_exists(self, Bucket, Key): # noqa: N803
  44. assert Bucket == self.bucket_name
  45. assert Key == self.key
  46. return True
  47. def delete_object(self, Bucket, Key, **kwargs): # noqa: N803
  48. assert Bucket == self.bucket_name
  49. assert Key == self.key
  50. self.resp.update({"x-cos-delete-marker": True})
  51. return self.resp
  52. MOCK = os.getenv("MOCK_SWITCH", "false").lower() == "true"
  53. @pytest.fixture
  54. def setup_tencent_cos_mock(monkeypatch: MonkeyPatch):
  55. if MOCK:
  56. monkeypatch.setattr(CosS3Client, "__init__", MockTencentCosClass.__init__)
  57. monkeypatch.setattr(CosS3Client, "put_object", MockTencentCosClass.put_object)
  58. monkeypatch.setattr(CosS3Client, "get_object", MockTencentCosClass.get_object)
  59. monkeypatch.setattr(CosS3Client, "object_exists", MockTencentCosClass.object_exists)
  60. monkeypatch.setattr(CosS3Client, "delete_object", MockTencentCosClass.delete_object)
  61. yield
  62. if MOCK:
  63. monkeypatch.undo()