Django Rest Framework - 测试中的AssertionError

时间:2015-03-27 12:24:39

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

Django Rest Framework的测试存在问题。我有以下观点:

class AccountDetail(generics.RetrieveUpdateAPIView):
    model = Account
    serializer_class = AccountSerializer
    lookup_field = 'username'
    permission_classes = (permissions.AllowAny,)
    def get_queryset(self):
        return Account.objects.filter(username=self.kwargs.get('username'))

我的网址包括以下内容:

account_urls = patterns('',
    url(r'^/(?P<username>[0-9a-zA-Z_-]+)/$', AccountDetail.as_view(), name='account-detail'),
    url(r'^/$', AccountList.as_view(), name='account-list')
)

urlpatterns = patterns('',
    url(r'^api/v1/users', include(account_urls)),
)

当我使用可浏览的API时,一切正常,但是当我编写以下测试时,我收到错误:

class TestAccoundDetail(APITestCase):
    def setUp(self):
        factory = APIRequestFactory()
        #set up normal user and token
        self.normal_user = Account.objects.create_user(email="user@example.com", username="useri", password="man")
        request = factory.post('/api/v1/auth/login/', {'email': 'user@example.com', 'password': 'man'})
        response = obtain_jwt_token(request)
        self.normal_token = response.data['token']

    def test_details(self):
        factory = APIRequestFactory()
        view = AccountDetail.as_view()

        #unauthenticated
        url = reverse('account-detail', kwargs={'username': 'useri'})
        request = factory.get(url)
        response = view(request)
        self.assertEqual(response.status_code, 200)

AssertionError:使用名为&#34; username&#34;的URL关键字参数调用的预期视图AccountDetail。修复您的网址,或者在视图上正确设置.lookup_field属性。

网址似乎很好,而且lookup_field就在那里。我错过了什么?

修改

我使用了APIClient而且它有效:

        client = APIClient()

        response = client.get('/api/v1/users/useri/')
        self.assertEqual(response.status_code, 200)

但是,我仍然不明白为什么我的原始测试不起作用。

2 个答案:

答案 0 :(得分:4)

扩展@linovias回答,关键是将额外的参数传递给您的视图

response = (view, username='useri')

完整测试

def test_details(self):
    factory = APIRequestFactory()
    view = AccountDetail.as_view()

    #unauthenticated
    url = reverse('account-detail', kwargs={'username': 'useri'})
    request = factory.get(url)

    response = view(request, username='useri')

    self.assertEqual(response.status_code, 200)

答案 1 :(得分:3)

RequestFactory是单元测试视图。它绕过了中间件和url层。因此,您需要自己提供额外的参数,同时使用ClientFactory urls.py为您完成。

编辑: 换句话说,

response = view(request)

应该是

response = view(request, "useri")