DRF APIRequestFactory错误

时间:2017-10-06 19:49:38

标签: django unit-testing django-rest-framework django-testing django-unittest

我的观点如下,

class LoginAPI(APIView):
    def post(self, request):
        """
        Provides login functionality.
        INPUT:
            {
                "username":"user_name",
                "password":"secret"
            }
        OUTPUT:
                if successful:
                    {'success': True, 'message': 'User authenticated.'}
                else:
                    {'success': False, 'message': 'Authentication failed.'}
        """
        details = request.data
        try:
            user = authenticate(username=details['username'], password=details['password'])
            login(request, user)
            return Response({'success': True, 'message': 'User authenticated.', 'user_id': user.id})
        except:
            return Response({'success': False, 'message': 'Authentication failed.'}, status=status.HTTP_401_UNAUTHORIZED)

我写了如下简单的测试用例,

class APIViewsTestBase(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.api_client = Client()
        self.username = "test_user"
        self.password = "test_password"
        self.dev = Developer.objects.create(username=self.username, is_staff=True)
        self.dev.set_password(raw_password=self.password)
        self.dev.save()

class TestLoginAPI(APIViewsTestBase):
    def test_LoginAPI(self):
        url = '/api/v1/login/'
        data = {"username": "test_user", "password": "test_password"}
        request = self.factory.post(path=url, data=data, format='json')
        view = LoginAPI.as_view()
        response = view(request)        
        self.assertEqual(response.status_code, 200)

当我运行测试时,我总是得到401错误代码。幸运或不幸的是,当我尝试使用django的测试模块附带的Client()时,测试通过了。我在django shell中执行了相同的指令但是,我得到了同样的错误。 (不是错误,response.status_code401

我的逻辑或代码有问题吗?有人请帮帮我吗?

0 个答案:

没有答案