Testing template context processors

155 views
Skip to first unread message

Gergely Polonkai

unread,
Mar 17, 2015, 12:53:22 PM3/17/15
to django...@googlegroups.com

Hello,

I wrote a context processor which makes some global variables of mine available for templates. I cannot find a good (cough… any) article on how to test such processors. Could you give me some directions on where to start with writing one?

Thanks in advance!

Best,
Gergely

Carl Meyer

unread,
Mar 17, 2015, 1:00:05 PM3/17/15
to django...@googlegroups.com
Hi Gergely,

On 03/17/2015 10:52 AM, Gergely Polonkai wrote:
> I wrote a context processor which makes some global variables of mine
> available for templates. I cannot find a good (cough… any) article on
> how to test such processors. Could you give me some directions on where
> to start with writing one?

Writing a unit test for a context processor is quite simple. Construct a
fake request (you can use RequestFactory, though if your context
processor only accesses one or two attributes of the request, it might
be simpler to just build a custom fake or use a library like pretend
[1]), then call the context processor function in your test, passing in
the fake request, and assert that the returned dictionary contains what
you expect.

If your templates require the values from the context processor in order
to render correctly, you can also write a higher-level integration or
functional test by using the test client to access a view that renders a
template that needs the context processor, and then assert the right
value is found in the rendered HTML.

Carl

[1] https://pypi.python.org/pypi/pretend

signature.asc

Gergely Polonkai

unread,
Mar 17, 2015, 1:38:13 PM3/17/15
to django...@googlegroups.com

Hello,

My processor sets some template variables based on request.user and some DB/redis query results, which are displayed on each page on a header bar, so I only need to create a mocked request with user set to something (AnonymousUser or a valid user object).

I'm already using Mock[2] for middleware testing, funny that I didn't think of this way (especially as I implemented it today), so thanks for pointing out!

[2] https://pypi.python.org/pypi/mock

--
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...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/55085D7A.5040007%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages