stub_service.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. from copy import deepcopy
  3. from fixtures.integrations import FIXTURE_DIRECTORY
  4. from sentry.utils import json
  5. class StubService:
  6. """
  7. A stub is a service that replicates the functionality of a real software
  8. system by returning valid data without actually implementing any business
  9. logic. For example, a stubbed random dice_roll function might always return
  10. 6. Stubs can make tests simpler and more reliable because they can replace
  11. flaky or slow networks call or allow you to have wider coverage in end-to-
  12. end tests.
  13. """
  14. stub_data_cache = {}
  15. service_name = None
  16. @staticmethod
  17. def get_stub_json(service_name, name):
  18. """
  19. Get the stubbed data as a JSON string.
  20. :param service_name: string
  21. :param name: string
  22. :return: string
  23. """
  24. path = os.path.join(FIXTURE_DIRECTORY, service_name, "stubs", name)
  25. with open(path) as f:
  26. return f.read()
  27. @staticmethod
  28. def get_stub_data(service_name, name):
  29. """
  30. Get the stubbed data as a python object.
  31. :param service_name: string
  32. :param name: string
  33. :return: object
  34. """
  35. cache_key = f"{service_name}.{name}"
  36. cached = StubService.stub_data_cache.get(cache_key)
  37. if cached:
  38. data = cached
  39. else:
  40. data = json.loads(StubService.get_stub_json(service_name, name))
  41. StubService.stub_data_cache[cache_key] = data
  42. return deepcopy(data)
  43. def _get_stub_data(self, name):
  44. return StubService.get_stub_data(self.service_name, name)