lundi 3 septembre 2018

Django Testing: avoid copied test cases

I have a lot of views which are restricted to the logged in user. For example User1 has access to /cars/1/edit but User2 does not have access to this url.

For this reason I need a lot of similar tests for every view but also custom tests for the views.

My solution is the following code.

class TestPermission:

    def setUp(self):
        self.user = Mock(User)
        self.car = Mock(Car, user=self.user)
        self.url = self.get_url()

    def get_url(self):
        raise NotImplementedError("get_url() is missing")

    def test_permission_denied(self):
        other_user = Mock(User)
        self.client.force_login(other_user)
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)


class TestHome(TestPermission, TestCase):

    def get_url(self):
        return reverse('car:home', kwargs={
            'car': self.car.slug
        })

    # ... custom tests for this view

class TestUpdate(TestPermission, TestCase):

    def get_url(self):
        return reverse('car:update', kwargs={
            'car': self.car.slug
        })

    # ... custom tests for this view

I am not sure if this is the best solutioin or if you should avoid inheritance in tests?

Aucun commentaire:

Enregistrer un commentaire