I want to speed up my Class Based Views tests. I wrote this small test-mixin. It seems to work pretty well and is actually doing all i need. Question to more experienced players here. Is that a method safe, without any actual drawbacks? ................................................................................................................................................................
class TemplateResponseTestMixin(object):
"""
Basic test checking if correct response, template,
form, is rendered for the given view.
Can be used for any CBV that inherits from TemplateResponseMixin.
"""
# required
view_class = None
url_name = ''
# optional (all below)
template_name = ''
form_class = None
csrf_token = True
get_status_code = 200
post_status_code = 405
def setUp(self):
self.client = Client()
#############
# SHORTCUTS #
#############
def get_response(self):
""" returns response for given view """
return self.client.get(reverse(self.url_name))
#########
# TESTS #
#########
def test_view_used(self):
""" check if correct view is used to render response """
resp = self.get_response()
self.assertIsInstance(resp.context['view'], self.view_class)
if template_name:
def test_template_used(self):
""" check if correct template is used to render response """
resp = self.get_response()
self.assertTemplateUsed(resp, self.template_name)
if form_class:
def test_form_used(self):
""" check if correct form is used to render response """
resp = self.get_response()
self.assertIsInstance(resp.context['form'], self.form_class)
if csrf_token:
def test_if_csrf_token_is_used(self):
""" check if csrf_token is used to render response """
resp = self.get_response()
self.assertIn('csrf_token', resp.context)
if get_status_code:
def test_get_response(self):
""" check if we receive correct status_code for GET request """
resp = self.get_response()
self.assertEqual(resp.status_code, self.get_status_code)
if post_status_code:
def test_post_response(self):
""" check if we receive correct status_code for POST request """
resp = self.client.post(reverse(self.url_name), data={})
self.assertEqual(resp.status_code, self.post_status_code)
################# THEN ##################
class RegistrationViewBasicTestCase(TemplateResponseTestMixin, SimpleTestCase):
view_class = RegistrationView
url_name = 'registration_form'
template_name = 'registration/registration_form.html'
form_class = RegistrationForm
get_response_code = 200
post_response_code = 200
Aucun commentaire:
Enregistrer un commentaire