apidocs_test_case.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. from django.conf import settings
  3. from openapi_core import create_spec
  4. from openapi_core.contrib.django import DjangoOpenAPIRequest, DjangoOpenAPIResponse
  5. from openapi_core.validation.response.validators import ResponseValidator
  6. from sentry.testutils.cases import APITestCase
  7. from sentry.testutils.helpers.datetime import before_now, iso_format
  8. from sentry.testutils.skips import requires_snuba
  9. from sentry.utils import json
  10. @requires_snuba
  11. class APIDocsTestCase(APITestCase):
  12. cached_schema = None
  13. def create_schema(self):
  14. if not APIDocsTestCase.cached_schema:
  15. path = os.path.join(os.path.dirname(__file__), "../tests/apidocs/openapi-derefed.json")
  16. with open(path) as json_file:
  17. data = json.load(json_file)
  18. data["servers"][0]["url"] = settings.SENTRY_OPTIONS["system.url-prefix"]
  19. del data["components"]
  20. APIDocsTestCase.cached_schema = create_spec(data)
  21. return APIDocsTestCase.cached_schema
  22. def validate_schema(self, request, response):
  23. assert 200 <= response.status_code < 300, response.status_code
  24. if isinstance(response.data, list):
  25. assert len(response.data) > 0, "Cannot validate an empty list"
  26. response["Content-Type"] = "application/json"
  27. result = ResponseValidator(self.create_schema()).validate(
  28. DjangoOpenAPIRequest(request), DjangoOpenAPIResponse(response)
  29. )
  30. result.raise_for_errors()
  31. assert result.errors == []
  32. def create_event(self, name, **kwargs):
  33. # Somewhat sane default data.
  34. data = {
  35. "event_id": (name * 32)[:32],
  36. "fingerprint": ["1"],
  37. "sdk": {"version": "5.17.0", "name": "sentry.javascript.browser"},
  38. "timestamp": iso_format(before_now(seconds=1)),
  39. "user": {"id": self.user.id, "email": self.user.email},
  40. "release": name,
  41. }
  42. data.update(kwargs)
  43. return self.store_event(data=data, project_id=self.project.id)