Django's self.client.login(…) does not work in unit tests

后端 未结 6 952
栀梦
栀梦 2020-12-02 09:50

I have created users for my unit tests in two ways:

1) Create a fixture for \"auth.user\" that looks roughly like this:

    { 
        \"pk\": 1, 
         


        
6条回答
  •  渐次进展
    2020-12-02 10:08

    Can you check like below,

    from django.test import TransactionTestCase, Client
    
    class UserHistoryTest(TransactionTestCase):
        self.user = User.objects.create(username='admin', password='pass@123', email='admin@admin.com')
        self.client = Client() # May be you have missed this line
    
        def test_history(self):
            self.client.login(username=self.user.username, password='pass@123')
            # get_history function having login_required decorator
            response = self.client.post(reverse('get_history'), {'user_id': self.user.id})
            self.assertEqual(response.status_code, 200)
    

    This test case worked for me.

提交回复
热议问题