correct way to setup teardown login logout in django
Question: To test a polling app that I made using django, the pre-requisite for
voting/viewing_results is that the user should be logged in. I wanted to
create a testsuite where setup involves creating testuser, logging him in and
teardown involves logging out the user and deleting the user.

I came across the setUp() and tearDown() methods - but got to know that they
are done for each method in the test. I wanted to have this functionality at
the class level and saw that django has setUpClass and tearDownClass - but as
they are class methods I cannot do self.client.login , self.client.logout on
them. I then created a LoginMixin which has setUp and tearDown methods.

I wanted to know which of these 2 methods is more pythonic and is there a
better alternative rather than logging in and out before every test?

  1. Have setUp, tearDown methods:
    
        def setUp(self):
        self.user = utils.create_user()
        self.client.login(username='testuser', password='testpasswd')
    
    def tearDown(self):
        self.client.logout()
        utils.delete_user(self.user)
    

  2. Have a LoginMixin and let each test class derive from it:
    
        class LoginMixin():
    
      def setUp(self):
        self.user = create_user()
        self.client.login(username='testuser', password='testpasswd')
    
      def tearDown(self):
        self.client.logout()
    
    class MyTest(LoginMixin, TestCase):
       ....
       ....
    

I am using django_nose as the TestRunner.


Answer: If the only reason you're not using the `setUpClass` classmethod is because
you don't have access to the default Client, you could just create your own
and refer to that:

    
    
    from django.test.client import Client
    
    class LoginMixin():
        client = Client()
        # ...
    

