Add mediatype tests (#4813)

This commit is contained in:
Artem Muterko 2017-01-16 20:17:51 +02:00 committed by Tom Christie
parent e965270f51
commit 06a5bcc88e
2 changed files with 25 additions and 4 deletions

View File

@ -49,10 +49,8 @@ def order_by_precedence(media_type_lst):
@python_2_unicode_compatible
class _MediaType(object):
def __init__(self, media_type_str):
if media_type_str is None:
media_type_str = ''
self.orig = media_type_str
self.full_type, self.params = parse_header(media_type_str.encode(HTTP_HEADER_ENCODING))
self.orig = '' if (media_type_str is None) else media_type_str
self.full_type, self.params = parse_header(self.orig.encode(HTTP_HEADER_ENCODING))
self.main_type, sep, self.sub_type = self.full_type.partition('/')
def match(self, other):

View File

@ -6,6 +6,7 @@ from rest_framework.negotiation import DefaultContentNegotiation
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from rest_framework.utils.mediatypes import _MediaType
factory = APIRequestFactory()
@ -55,3 +56,25 @@ class TestAcceptedMediaType(TestCase):
accepted_renderer, accepted_media_type = self.select_renderer(request)
assert accepted_media_type == 'application/openapi+json;version=2.0'
assert accepted_renderer.format == 'swagger'
def test_match_is_false_if_main_types_not_match(self):
mediatype = _MediaType('test_1')
anoter_mediatype = _MediaType('test_2')
assert mediatype.match(anoter_mediatype) is False
def test_mediatype_match_is_false_if_keys_not_match(self):
mediatype = _MediaType(';test_param=foo')
another_mediatype = _MediaType(';test_param=bar')
assert mediatype.match(another_mediatype) is False
def test_mediatype_precedence_with_wildcard_subtype(self):
mediatype = _MediaType('test/*')
assert mediatype.precedence == 1
def test_mediatype_string_representation(self):
mediatype = _MediaType('test/*; foo=bar')
params_str = ''
for key, val in mediatype.params.items():
params_str += '; %s=%s' % (key, val)
expected = 'test/*' + params_str
assert str(mediatype) == expected