108 lines
3.3 KiB
Python
108 lines
3.3 KiB
Python
from django.test import Client
|
|
|
|
class ViewTestCaseMixin:
|
|
'''
|
|
This is a mixni for testing views. It provides functionality to
|
|
test the context, forms and HTTP Response of responses.
|
|
Also works with django's ReqeustFactory and provides a self.client
|
|
'''
|
|
view = None
|
|
|
|
def setUp(self):
|
|
self.view_name = self.view.__name__
|
|
self.client = Client()
|
|
|
|
def assertContext(self, response, key, value=None):
|
|
'''
|
|
Checks weather the response's context has the given key
|
|
and, if passed, checks the value
|
|
'''
|
|
self.assertTrue(
|
|
key in response.context,
|
|
msg='Expecting the context of %s to have an attribute \'%s\'' % (
|
|
self.view_name,
|
|
key
|
|
)
|
|
)
|
|
|
|
if value:
|
|
self.assertEqual(
|
|
value,
|
|
response.context[key],
|
|
msg='Expecting the context of %s to have %s set to \'%s\'' % (
|
|
self.view_name,
|
|
key,
|
|
str(value)
|
|
)
|
|
)
|
|
|
|
def assertHasForm(self, response, context_key, form_class):
|
|
'''
|
|
Checks if response has a form under the given key and if
|
|
the forms class matches.
|
|
'''
|
|
self.assertContext(response, context_key)
|
|
self.assertEqual(
|
|
type(response.context[context_key]),
|
|
form_class,
|
|
msg='Expecting %s\'s context.%s to be of the type %s' % (
|
|
self.view_name,
|
|
context_key,
|
|
form_class.__name__
|
|
)
|
|
)
|
|
|
|
def assertHttpCode(self, response, code):
|
|
'''
|
|
Checks if the response has the given status code
|
|
'''
|
|
self.assertEqual(
|
|
response.status_code, code,
|
|
"Expected an HTTP %s response, but got HTTP %s" % (
|
|
code,
|
|
response.status_code
|
|
)
|
|
)
|
|
|
|
def assertHttpOK(self, response):
|
|
self.assertHttpCode(response, 200)
|
|
|
|
def assertHttpCreated(self, response):
|
|
self.assertHttpCode(response, 201)
|
|
|
|
def assertHttpRedirect(self, response, redirect_to=None):
|
|
'''
|
|
Checks weather the response redirected, and if passed,
|
|
if it redirected to the expected loaction
|
|
'''
|
|
|
|
self.assertTrue(
|
|
300 <= response.status_code < 400,
|
|
'Expected an HTTP 3XX (redirect) response, but got HTTP %s' %
|
|
response.status_code
|
|
)
|
|
if redirect_to:
|
|
self.assertEqual(
|
|
response['Location'],
|
|
redirect_to,
|
|
msg='Expecing the response to redirect to %s, where redirected to %s instea' % (
|
|
str(redirect_to),
|
|
str(response['Location'])
|
|
)
|
|
)
|
|
|
|
|
|
def assertHttpBadRequest(self, response):
|
|
self.assertHttpCode(response, 400)
|
|
|
|
def assertHttpUnauthorized(self, response):
|
|
self.assertHttpCode(response, 401)
|
|
|
|
def assertHttpForbidden(self, response):
|
|
self.assertHttpCode(response, 403)
|
|
|
|
def assertHttpNotFound(self, response):
|
|
self.assertHttpCode(response, 404)
|
|
|
|
def assertHttpMethodNotAllowed(self, response):
|
|
self.assertHttpCode(response, 405) |