unit_tests.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from typing import List, Optional, Union
  2. from drf_spectacular.utils import extend_schema_serializer
  3. from typing_extensions import Literal, TypedDict
  4. from sentry.api.serializers import Serializer
  5. from sentry.apidocs.extensions import (
  6. SentryInlineResponseSerializerExtension,
  7. SentryResponseSerializerExtension,
  8. )
  9. from sentry.apidocs.utils import inline_sentry_response_serializer
  10. class NestedDict(TypedDict):
  11. zz: str
  12. class BasicSerializerOptional(TypedDict, total=False):
  13. a: int
  14. @extend_schema_serializer(exclude_fields=["excluded"])
  15. class BasicSerializerResponse(BasicSerializerOptional):
  16. b: str
  17. c: bool
  18. d: List[int]
  19. e: NestedDict
  20. f: Literal[3]
  21. g: Union[str, bool]
  22. h: Optional[str]
  23. excluded: str
  24. class BasicSerializer(Serializer):
  25. def serialize() -> BasicSerializerResponse:
  26. return {"a": 1, "b": "test", "c": True, "d": [1], "e": {"zz": "test"}}
  27. def test_sentry_response_serializer_extension():
  28. seralizer_extension = SentryResponseSerializerExtension(BasicSerializer)
  29. schema = seralizer_extension.map_serializer(None, None)
  30. assert schema == {
  31. "type": "object",
  32. "properties": {
  33. "a": {"type": "integer"},
  34. "b": {"type": "string"},
  35. "c": {"type": "boolean"},
  36. "d": {"type": "array", "items": {"type": "integer"}},
  37. "e": {"type": "object", "properties": {"zz": {"type": "string"}}, "required": ["zz"]},
  38. "f": {"enum": [3], "type": "integer"},
  39. "g": {"oneOf": [{"type": "string"}, {"type": "boolean"}]},
  40. "h": {"type": "string", "nullable": True},
  41. },
  42. "required": ["b", "c", "d", "e", "f", "g", "h"],
  43. }
  44. def test_sentry_inline_response_serializer_extension():
  45. inline_serializer = inline_sentry_response_serializer(
  46. "BasicStuff", List[BasicSerializerResponse]
  47. )
  48. seralizer_extension = SentryInlineResponseSerializerExtension(inline_serializer)
  49. schema = seralizer_extension.map_serializer(None, None)
  50. assert schema == {
  51. "type": "array",
  52. "items": {
  53. "type": "object",
  54. "properties": {
  55. "a": {"type": "integer"},
  56. "b": {"type": "string"},
  57. "c": {"type": "boolean"},
  58. "d": {"type": "array", "items": {"type": "integer"}},
  59. "e": {
  60. "type": "object",
  61. "properties": {"zz": {"type": "string"}},
  62. "required": ["zz"],
  63. },
  64. "f": {"enum": [3], "type": "integer"},
  65. "g": {"oneOf": [{"type": "string"}, {"type": "boolean"}]},
  66. "h": {"type": "string", "nullable": True},
  67. },
  68. "required": ["b", "c", "d", "e", "f", "g", "h"],
  69. },
  70. }