From 06a5bcc88ecdd78b093ce571ddd959a7ddba867e Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Mon, 16 Jan 2017 20:17:51 +0200 Subject: [PATCH] Add mediatype tests (#4813) --- rest_framework/utils/mediatypes.py | 6 ++---- tests/test_negotiation.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/rest_framework/utils/mediatypes.py b/rest_framework/utils/mediatypes.py index def4b9641..865c283cc 100644 --- a/rest_framework/utils/mediatypes.py +++ b/rest_framework/utils/mediatypes.py @@ -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): diff --git a/tests/test_negotiation.py b/tests/test_negotiation.py index 6b8fd5060..62f1cf40f 100644 --- a/tests/test_negotiation.py +++ b/tests/test_negotiation.py @@ -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