mardi 30 janvier 2018

Extending/overriding Django TestCase class

My application has three levels of access (i.e. User, Manager, Admin). In my unit tests I have something like this:

from django.test import TestCase

class DocumentViewTest(TestCase):
    def setUp(self):
         # Create 3 users

    def test_view_url_exists_at_desired_location(self):
         self.client.login(username='manager', password='xx')
         resp = self.client.get(reverse('view_upload'))
         self.assertEqual(str(resp.context['user']), 'manager')

Testing all three levels could be defined by the same routine:

  1. login user
  2. post/get to some url
  3. create assertions to check the post/get response

I wanted to encapsulate all the steps in some wrapper class or extend the TestCase, so that redundancy is avoided. I was thinking about something like this:

from django.test import TestCase

class DocumentViewTest(TestCase):
    def setUp(self):
         # Create 3 users

    def test_view_url_exists_at_desired_location(self):
         self.client.login(username=['manager','admin','simple_user'], password=['xx','x','xxx'])
         resp_manager, resp_admin, resp_simple_user = self.client.get(reverse('view_upload'))
         self.assertEqual(str(resp_manager.context['user']), 'manager')
         self.assertEqual(str(resp_admin.context['user']), 'admin')
         self.assertEqual(str(resp.resp_simple_user['user']), 'simple_user')

Does anyone have suggestions how I could override get/post/login methods? Would creating a wrapper class around TestCase be easier? Any other suggestions?

Thanks!

Aucun commentaire:

Enregistrer un commentaire