apidocs_test_case.py 1.9 KB

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