Skip to content

Instantly share code, notes, and snippets.

@maxpoletaev
Created June 20, 2017 20:07
Show Gist options
  • Save maxpoletaev/325745756d1d496c6786cf53d9da34e6 to your computer and use it in GitHub Desktop.
Save maxpoletaev/325745756d1d496c6786cf53d9da34e6 to your computer and use it in GitHub Desktop.
Flex test mixin for Django
import os
from django.conf import settings
from django.http import HttpRequest
import flex
from flex.core import validate_api_call
from flex.exceptions import ValidationError
APISPEC_PATH = os.path.join(settings.BASE_DIR, 'apispec', 'swagger.yml')
flex_schema = flex.load(APISPEC_PATH)
class FlexTestMixin:
def assertSwaggerSchema(self, response, request=None):
if not response.is_rendered:
response.render()
# 204 No Content response without content-type
# but flex expected that header
if 'Content-Type' not in response:
response['Content-Type'] = ''
try:
validate_api_call(flex_schema,
raw_request=(request or response.wsgi_request), raw_response=response)
except ValidationError as e:
self.fail(e)
# Patch original request object for prevent exception:
# "You cannot access body after reading from request's data stream"
def patched_read(self, *args, **kwargs):
self._body = original_read(self, *args, **kwargs)
return self._body
original_read = HttpRequest.read
HttpRequest.read = patched_read
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment