Python django中的异常单元测试

Python django中的异常单元测试,python,django,django-rest-framework,Python,Django,Django Rest Framework,我正在为这段代码编写单元测试,我想知道有人会如何测试下面代码的任何异常。谢谢 class ExpiringTokenAuthentication(TokenAuthentication): """ Extends token auth with inactivity expiration mechanism. """ model = ExpiringToken def authenticate_credential

我正在为这段代码编写单元测试,我想知道有人会如何测试下面代码的任何异常。谢谢

class ExpiringTokenAuthentication(TokenAuthentication):
        """
        Extends token auth with inactivity expiration mechanism.
        """
        model = ExpiringToken

        def authenticate_credentials(self, key):

            try:
                token = self.model.objects.get(key=key)
            except self.model.DoesNotExist:
                raise exceptions.AuthenticationFailed('Invalid token')

            if not token.user.is_active:
                raise exceptions.AuthenticationFailed('Invalid user')

            if token.has_expired():
                raise exceptions.AuthenticationFailed('Token has expired')

            token.last_activity = timezone.now()
            token.save()
            return token.user, token

首先:您(想要)使用哪个测试框架?我正在使用Django。(内置lib TestCase)然后像unittest应该做的那样做:创建测试给定项(用户、令牌),创建类的实例,运行方法检查self.assertRaises(YourError):。这就是我在这里做的:我回答了另一个问题