I've gotten back to playing with this.  What I've ended up doing is 
monkey-patching render to send the signal django.test.Client is expecting 
from the template backend.  Paraphrasing my (python 3.7) code:

from unittest.mock import patch
from django.test.signals import template_rendered
from django.shortcuts import render

class TimelineViewTest(TestCase):
    @patch('spi.views.render')
    def test_context_includes_tag_list(self, mock_render):

        def render_patch(request, template, context):
            template_rendered.send(sender=self, template=template, 
context=context)
            return render(request, template, context)

        mock_render.side_effect = render_patch

At least doing it this way puts all the weird stuff in my test code.  I 
didn't have to touch anything in my production view code (or in either 
django or jinja).
On Thursday, February 4, 2021 at 7:29:23 PM UTC-5 Roy Smith wrote:

> I started my current project using native django templates and now I'm 
> converting to jinja2. For the most part, it has gone smoothly. 
>
> The surprising roadblock was that this broke all my unit tests. The issue 
> is that django.template.backends.jinja2.Jinja2 doesn't populate 
> response.context.
>
> One thought I had was to patch django.shortcuts.render() with 
> unittest.mock. That didn't work out so well.
>
> Where I seem to be heading now is to have each of my View subclasses have 
> a build_context() static method, put most of the logic in that, and then I 
> can call that directly in my unit tests. This seems to be workable, but 
> it's kind of ugly that I need to alter my production code to make it 
> testable.
>
> Any wisdom from people who have gone through this would be appreciated.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b228c0ca-e7d4-4a0f-8649-859961864163n%40googlegroups.com.

Reply via email to