local.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. import shutil
  3. from pathlib import Path
  4. from unittest.mock import MagicMock, mock_open, patch
  5. import pytest
  6. from _pytest.monkeypatch import MonkeyPatch
  7. from tests.unit_tests.oss.__mock.base import (
  8. get_example_data,
  9. get_example_filename,
  10. get_example_filepath,
  11. get_example_folder,
  12. )
  13. class MockLocalFSClass:
  14. def write_bytes(self, data):
  15. assert data == get_example_data()
  16. def read_bytes(self):
  17. return get_example_data()
  18. @staticmethod
  19. def copyfile(src, dst):
  20. assert src == os.path.join(get_example_folder(), get_example_filename())
  21. assert dst == get_example_filepath()
  22. @staticmethod
  23. def exists(path):
  24. assert path == os.path.join(get_example_folder(), get_example_filename())
  25. return True
  26. @staticmethod
  27. def remove(path):
  28. assert path == os.path.join(get_example_folder(), get_example_filename())
  29. MOCK = os.getenv("MOCK_SWITCH", "false").lower() == "true"
  30. @pytest.fixture
  31. def setup_local_fs_mock(monkeypatch: MonkeyPatch):
  32. if MOCK:
  33. monkeypatch.setattr(Path, "write_bytes", MockLocalFSClass.write_bytes)
  34. monkeypatch.setattr(Path, "read_bytes", MockLocalFSClass.read_bytes)
  35. monkeypatch.setattr(shutil, "copyfile", MockLocalFSClass.copyfile)
  36. monkeypatch.setattr(os.path, "exists", MockLocalFSClass.exists)
  37. monkeypatch.setattr(os, "remove", MockLocalFSClass.remove)
  38. os.makedirs = MagicMock()
  39. with patch("builtins.open", mock_open(read_data=get_example_data())):
  40. yield
  41. if MOCK:
  42. monkeypatch.undo()