  from StringIO import StringIO
  import datetime
  from decimal import Decimal
  
  DUMMYSTATUS = status.HTTP_200_OK
  DUMMYCONTENT = 'dummycontent'
  
  RENDERER_A_SERIALIZER = lambda x: 'Renderer A: %s' % x
  RENDERER_B_SERIALIZER = lambda x: 'Renderer B: %s' % x
  
  
  class RendererA(BaseRenderer):
      media_type = 'mock/renderera'
      format = "formata"
  
      def render(self, obj=None, media_type=None):
          return RENDERER_A_SERIALIZER(obj)
  
  
  class RendererB(BaseRenderer):
      media_type = 'mock/rendererb'
      format = "formatb"
  
      def render(self, obj=None, media_type=None):
          return RENDERER_B_SERIALIZER(obj)
  
  
  class MockView(ResponseMixin, DjangoView):
      renderers = (RendererA, RendererB)
  
      def get(self, request, **kwargs):
          response = Response(DUMMYSTATUS, DUMMYCONTENT)
          return self.render(response)
  
  
  class MockGETView(View):
  
      def get(self, request, **kwargs):
          return {'foo': ['bar', 'baz']}
  
  
  class HTMLView(View):
      renderers = (DocumentingHTMLRenderer, )
  
      def get(self, request, **kwargs):
          return 'text' 
  
  
  class HTMLView1(View):
      renderers = (DocumentingHTMLRenderer, JSONRenderer)
  
      def get(self, request, **kwargs):
          return 'text' 
  
  urlpatterns = patterns('',
      url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderers=[RendererA, RendererB])),
      url(r'^$', MockView.as_view(renderers=[RendererA, RendererB])),
      url(r'^jsonp/jsonrenderer$', MockGETView.as_view(renderers=[JSONRenderer, JSONPRenderer])),
      url(r'^jsonp/nojsonrenderer$', MockGETView.as_view(renderers=[JSONPRenderer])),
      url(r'^html$', HTMLView.as_view()),
      url(r'^html1$', HTMLView1.as_view()),
  )
  
  
  class RendererIntegrationTests(TestCase):
      """
      End-to-end testing of renderers using an RendererMixin on a generic view.
      """
  
      urls = 'djangorestframework.tests.renderers'
  
      def test_default_renderer_serializes_content(self):
          """If the Accept header is not set the default renderer should serialize the response."""
          resp = self.client.get('/')
          self.assertEquals(resp['Content-Type'], RendererA.media_type)
          self.assertEquals(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_head_method_serializes_no_content(self):
          """No response must be included in HEAD requests."""
          resp = self.client.head('/')
          self.assertEquals(resp.status_code, DUMMYSTATUS)
          self.assertEquals(resp['Content-Type'], RendererA.media_type)
          self.assertEquals(resp.content, '')
  
      def test_default_renderer_serializes_content_on_accept_any(self):
          """If the Accept header is set to */* the default renderer should serialize the response."""
          resp = self.client.get('/', HTTP_ACCEPT='*/*')
          self.assertEquals(resp['Content-Type'], RendererA.media_type)
          self.assertEquals(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_specified_renderer_serializes_content_default_case(self):
          """If the Accept header is set the specified renderer should serialize the response.
          (In this case we check that works for the default renderer)"""
          resp = self.client.get('/', HTTP_ACCEPT=RendererA.media_type)
          self.assertEquals(resp['Content-Type'], RendererA.media_type)
          self.assertEquals(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_specified_renderer_serializes_content_non_default_case(self):
          """If the Accept header is set the specified renderer should serialize the response.
          (In this case we check that works for a non-default renderer)"""
          resp = self.client.get('/', HTTP_ACCEPT=RendererB.media_type)
          self.assertEquals(resp['Content-Type'], RendererB.media_type)
          self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_specified_renderer_serializes_content_on_accept_query(self):
          """The '_accept' query string should behave in the same way as the Accept header."""
          resp = self.client.get('/?_accept=%s' % RendererB.media_type)
          self.assertEquals(resp['Content-Type'], RendererB.media_type)
          self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_unsatisfiable_accept_header_on_request_returns_406_status(self):
          """If the Accept header is unsatisfiable we should return a 406 Not Acceptable response."""
          resp = self.client.get('/', HTTP_ACCEPT='foo/bar')
          self.assertEquals(resp.status_code, status.HTTP_406_NOT_ACCEPTABLE)
  
      def test_specified_renderer_serializes_content_on_format_query(self):
          """If a 'format' query is specified, the renderer with the matching
          format attribute should serialize the response."""
          resp = self.client.get('/?format=%s' % RendererB.format)
          self.assertEquals(resp['Content-Type'], RendererB.media_type)
          self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_specified_renderer_serializes_content_on_format_kwargs(self):
          """If a 'format' keyword arg is specified, the renderer with the matching
          format attribute should serialize the response."""
          resp = self.client.get('/something.formatb')
          self.assertEquals(resp['Content-Type'], RendererB.media_type)
          self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_specified_renderer_is_used_on_format_query_with_matching_accept(self):
          """If both a 'format' query and a matching Accept header specified,
          the renderer with the matching format attribute should serialize the response."""
          resp = self.client.get('/?format=%s' % RendererB.format,
                                 HTTP_ACCEPT=RendererB.media_type)
          self.assertEquals(resp['Content-Type'], RendererB.media_type)
          self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_conflicting_format_query_and_accept_ignores_accept(self):
          """If a 'format' query is specified that does not match the Accept
          header, we should only honor the 'format' query string."""
          resp = self.client.get('/?format=%s' % RendererB.format,
                                 HTTP_ACCEPT='dummy')
          self.assertEquals(resp['Content-Type'], RendererB.media_type)
          self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
      def test_bla(self):
          resp = self.client.get('/?format=formatb',
              HTTP_ACCEPT='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
          self.assertEquals(resp['Content-Type'], RendererB.media_type)
          self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
          self.assertEquals(resp.status_code, DUMMYSTATUS)
  
  _flat_repr = '{"foo": ["bar", "baz"]}'
  _indented_repr = '{\n  "foo": [\n    "bar",\n    "baz"\n  ]\n}'
  
  
 
</s> remove     _ACCEPT_QUERY_PARAM = '_accept'        # Allow override of Accept header in URL query params
    _IGNORE_IE_ACCEPT_HEADER = True

 </s> add  </s> remove 
        try:
            renderer, media_type = self._determine_renderer(self.request)
        except ErrorResponse, exc:
            renderer = self._default_renderer(self)
            media_type = renderer.media_type
            response = exc.response

        # Set the media type of the response
        # Note that the renderer *could* override it in .render() if required.
        response.media_type = renderer.media_type

        # Serialize the response content
        if response.has_content_body:
            content = renderer.render(response.cleaned_content, media_type)
        else:
            content = renderer.render()

        # Build the HTTP Response
        resp = HttpResponse(content, mimetype=response.media_type, status=response.status)
        for (key, val) in response.headers.items():
            resp[key] = val

        return resp

    def _determine_renderer(self, request):
        """
        Determines the appropriate renderer for the output, given the client's 'Accept' header,
        and the :attr:`renderers` set on this class.

        Returns a 2-tuple of `(renderer, media_type)`

        See: RFC 2616, Section 14 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
        """

        if self._ACCEPT_QUERY_PARAM and request.GET.get(self._ACCEPT_QUERY_PARAM, None):
            # Use _accept parameter override
            accept_list = [request.GET.get(self._ACCEPT_QUERY_PARAM)]
        elif (self._IGNORE_IE_ACCEPT_HEADER and
              'HTTP_USER_AGENT' in request.META and
              MSIE_USER_AGENT_REGEX.match(request.META['HTTP_USER_AGENT'])):
            # Ignore MSIE's broken accept behavior and do something sensible instead
            accept_list = ['text/html', '*/*']
        elif 'HTTP_ACCEPT' in request.META:
            # Use standard HTTP Accept negotiation
            accept_list = [token.strip() for token in request.META['HTTP_ACCEPT'].split(',')]
        else:
            # No accept header specified
            accept_list = ['*/*']

        # Check the acceptable media types against each renderer,
        # attempting more specific media types first
        # NB. The inner loop here isn't as bad as it first looks :)
        #     Worst case is we're looping over len(accept_list) * len(self.renderers)
        renderers = [renderer_cls(self) for renderer_cls in self.renderers]

        for accepted_media_type_lst in order_by_precedence(accept_list):
            for renderer in renderers:
                for accepted_media_type in accepted_media_type_lst:
                    if renderer.can_handle_response(accepted_media_type):
                        return renderer, accepted_media_type

        # No acceptable renderers were found
        raise ErrorResponse(status.HTTP_406_NOT_ACCEPTABLE,
                                {'detail': 'Could not satisfy the client\'s Accept header',
                                 'available_types': self._rendered_media_types})
 </s> add         return response </s> remove         format = self.view.kwargs.get(self._FORMAT_QUERY_PARAM, None)
        if format is None:
 </s> add         # TODO: format overriding must go out of here
        format = None
        if self.view is not None:
            format = self.view.kwargs.get(self._FORMAT_QUERY_PARAM, None)
        if format is None and self.view is not None: </s> remove     def __init__(self, status=200, content=None, headers=None):
        self.status = status
        self.media_type = None
 </s> add     _ACCEPT_QUERY_PARAM = '_accept'        # Allow override of Accept header in URL query params
    _IGNORE_IE_ACCEPT_HEADER = True

    def __init__(self, content=None, status=None, request=None, renderers=None):
        """
        content is the raw content.

        The set of renderers that the response can handle.

        Should be a tuple/list of classes as described in the :mod:`renderers` module.
        """
        # First argument taken by `SimpleTemplateResponse.__init__` is template_name,
        # which we don't need
        super(Response, self).__init__(None, status=status)
        # We need to store our content in raw content to avoid overriding HttpResponse's
        # `content` property
        self.raw_content = content 
  from StringIO import StringIO
  import datetime
  from decimal import Decimal
  




























































































































































  
  _flat_repr = '{"foo": ["bar", "baz"]}'
  _indented_repr = '{\n  "foo": [\n    "bar",\n    "baz"\n  ]\n}'
  
  
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
 Response as a subclass of HttpResponse - first draft, not quite there yet. 
djangorestframework/tests/renderers.py