'How do I write setUpClass() and tearDownClass() creating and logging in a user?(Django Rest FrameWork)

I have this test case written for two models with local permission_classes, [IsAdminUser] and [IsAuthenticated] respectively. After running the test cases both the test are failed and according to the exception messages, it is clear that the user is not getting logged in.

class PermissionClassesTest(APITestCase):
    
    @classmethod
    def setUpClass(cls):
        super(PermissionClassesTest, cls).setUpClass()
        print('running before tests')
        cls.user = User.objects.create_user(username='admin', password='qwefghbnm', is_staff= True)
        cls.client = APIClient()
        cls.client.login(username=cls.user.username, password='qwefghbnm')

    @classmethod
    def tearDownClass(cls):
        super(PermissionClassesTest,cls).tearDownClass()
        print('running after test')
        
    def test_SalaryDetail_local_permission(self):
        response = self.client.get('/salaryDetails/')
        self.assertEqual(json.dumps(response.data), '{"detail": "You do not have permission to perform this action."}')

    def test_EmployeeDetail_local_permission(self):
        response = self.client.get('/employeeDetails/')
        self.assertTrue(status.is_success(response.status_code))```


Solution 1:[1]

Django will set self.client per default to an instance of django.test.client.Client. You should make your client available at a different name eg. cls.api_client = APIClient(). Note that if you are setting up data in in setUpClass() you are also responsible for removing it again in tearDownClass(), for example remove the user you created as Django will not handle this for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bernhard Vallant