在DRF中多次调用setUpClass()

时间:2019-01-14 19:14:30

标签: django

也许我缺少逻辑,但是我想向模型添加两个唯一的记录,然后在API上运行测试。但是我的API抱怨.get()返回了2条记录,引发了错误。我注意到错误发生在我的.post()检查中,而get方法运行良好。是一个错误吗?

仅当我用.get()更改self.client.post时,它才不会抱怨。

我尝试了setUpTestData(),因为我的数据库支持事务无济于事。本质上,我想尝试get方法和post方法。所有的get操作都通过了,但是在后期测试中失败了。

class ResetPwdTest(APITestCase):
    """ Test module for resetting forgotten password """

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.valid_payload = '1234567890ABCDEF'

        cls.expired_payload = '1234567ACDES'

        cls.invalid_payload = 'invalid0000'
        user_info = {'first_name': 'John', 'email': 'kmsium@gmail.com','password' : 'kigali11', 'status': 1}

        user = User.objects.create_user(**user_info)

        PasswordReset.objects.all().delete() # delete any possible we have but having no effect so far

        # create valid password token
        password2 = PasswordReset(profile_id=user.id, unique_code=cls.valid_payload)
        password2.save()

        # create an expired passwod token

        password = PasswordReset(profile_id=user.id, unique_code=cls.expired_payload)
        password.save()

        password.createdon = '2018-01-12 21:11:38.997207'
        password.save()




    def test_valid_token(self):
        """
        GET Ensure a valid forgotten password reset token returns 200
        WORKING
        """
        response = self.client.get(reverse('new-pwd', kwargs= {'token' : self.valid_payload}))
        self.assertEqual(response.status_code, 200)


    def test_expired_token(self):
        """
        GET Ensure an expired token to reset a forgotten password returns 400
        WORKING
        """
        response = self.client.get(reverse('new-pwd', kwargs= {'token' : self.expired_payload}))
        self.assertEqual(response.status_code, 400)


    def test_invalid_token(self):
        """
        GET Ensure an invali token to reset a forgotten password returns 400
        WORKING
        """
        response = self.client.get(reverse('new-pwd', kwargs= {'token' : self.invalid_payload}))
        self.assertEqual(response.status_code, 400)


    def test_valid_token_change_pass(self):
        """
        POST Ensure a valid forgotten password with accepted passwords pass reset token returns 200
        FAILING BECAUSE TOKEN is not unique
        """

        passwords = {'pwd': 'letmein11', 'pwd_confirm': 'letmein11'}
        response = self.client.post(reverse('new-pwd', kwargs= {'token' : self.valid_payload}), passwords, format='json')
        self.assertEqual(response.status_code, 200)

视图:

class ResetPwd(APIView):

    permission_classes = []

    def get(self,request,token,format=None):

        status = 400
        reply = {}

        check_token = PasswordReset.objects.values('createdon','profile_id',).get(unique_code=token)
        # exists but is it valid or not? It cant be

        createdon = check_token["createdon"]

        if createdon > timezone.now() - timedelta(hours=USER_VALUES['PWD_RESET_LIFESPAN']):
            status = 200
            reply['detail'] = True
        else:
            reply['detail'] = _('errorPwdResetLinkExpired') 

        return JsonResponse(reply,status=status)


    def post(self,request,token,format=None):
        '''
        @input pwd: password
        @input pwd_confirm : confirmation password
        '''

        status = 400
        reply = {}

        k = PasswordReset.objects.filter(unique_code= token).count()
        print('total in db ', k) # shows 1

        check_token = PasswordReset.objects.values('createdon','profile_id',).get(unique_code=token)
        # error: returning 2!
        #exists but is it valid or not? It cant be

        createdon = check_token['createdon']




        if createdon > timezone.now() - timedelta(hours=USER_VALUES['PWD_RESET_LIFESPAN']):
            status = 200
        else:
            reply['detail'] = _('errorPwdResetLinkExpired')

        '''
        except:
            reply['detail'] = _('errorBadPwdResetLink')
        '''

        return JsonResponse(reply,status=status)

我希望所有测试都能通过。

0 个答案:

没有答案