Skip to content

Instantly share code, notes, and snippets.

@drillbits
Created June 18, 2013 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drillbits/5804272 to your computer and use it in GitHub Desktop.
Save drillbits/5804272 to your computer and use it in GitHub Desktop.
HttpResponse を返すようなビューで context を検証するやつ
# -*- coding: utf-8 -*-
from copy import copy
from django.test.signals import template_rendered
class AssertHttpResponseContext(object):
def __init__(self, test_case, context_key, context_value):
self.test_case = test_case
self.context_key = context_key
self.context_value = context_value
self.context = None
def on_template_render(self, sender, signal, template, context, **kwargs):
self.context = copy(context)
def test_key(self):
return self.context_key in self.context
def test_value(self):
return self.context.get(self.context_key) == \
self.context_value
def __enter__(self):
template_rendered.connect(self.on_template_render)
return self
def __exit__(self, exc_type, exc_value, traceback):
template_rendered.disconnect(self.on_template_render)
if exc_type is not None:
return
if not self.test_key():
self.test_case.fail(
"Context key '%s' was not found." % self.context_key)
if not self.test_value():
self.test_case.fail("AssertionError: '%s' != '%s'" % (
self.context.get(self.context_key),
self.context_value
))
class AssertViewMixin(object):
def assertHttpResponseContext(self, context_key=None, context_value=None):
if context_key is None and context_value is None:
raise TypeError(
'context_key and/or context_value argument must be provided')
return AssertHttpResponseContext(self, context_key, context_value)
# -*- coding: utf-8 -*-
from django.test import RequestFactory, TestCase
import testing
class SpamViewTest(TestCase, testing.AssertViewMixin):
url = '/spam/'
def _makeOne(self):
from spam import views
return views.spam
def _makeRequest(self, method, data={}):
if method == 'POST':
func = RequestFactory().post
else:
func = RequestFactory().get
request = func(self.url, data=data)
return request
def _callFUT(self, request):
func = self._makeOne()
return func(request)
def test_get(self):
request = self._makeRequest('GET')
with self.assertTemplateUsed('spam.html'):
with self.assertHttpResponseContext('ham', 'HAM'):
response = self._callFUT(request)
self.assertEqual(response.status_code, 200)
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template.context import RequestContext
def spam(request):
return render_to_response(
template_name='spam.html',
dictionary={'ham': 'HAM'},
context_instance=RequestContext(request),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment