stub_service.py 1.6 KB

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