lostplaces-backend/lostplaces/lostplaces_app/tests/views/__init__.py
2020-09-13 19:43:47 +02:00

108 lines
3.3 KiB
Python

from django.test import TestCase
class ViewTestCase(TestCase):
'''
This is a mixni for testing views. It provides functionality to
test the context, forms and HTTP Response of responses.
All methods take responses, so this base class can be used
with django's RequestFactory and Test-Client
'''
view = None
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, key, form_class):
'''
Checks if response has a form under the given key and if
the forms class matches.
'''
self.assertContext(response, key)
self.assertEqual(
type(response.context[key]),
form_class,
msg='Expecting %s\'s context.%s to be of the type %s' % (
self.view.__name__,
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 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
)
self.assertTrue(
'location' in response,
msg='Expecting a redirect to have an location, got none'
)
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 assertHttpOK(self, response):
self.assertHttpCode(response, 200)
def assertHttpCreated(self, response):
self.assertHttpCode(response, 201)
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)