2015-02-11 85 views
1

中验证我试图测试一个*未经认证/未经授权用户访问在Django的API。在API中我有以下代码如何获得的Django单元测试

class myAPIView(TimezoneAwareMixin, RetrieveUpdateAPIView): 

    model = mymodel 
    serializer_class = mymodelSerializer 
    permission_classes = (IsAuthenticated, IsCompanyActive, HasRole) 
    get_roles = ('mymodel-view',) 

    def get_queryset(self): 
     """ 
     Allow only users within a company to see only their objects 
     """ 

     return mymodel.objects.filter(company=self.request.user.active_company) 

然后在我的测试中我继承的TestCase并尝试以下

client = client_class() # no headers so its anonymous 
client.get(url) 

,但我得到的测试

AttributeError: 'AnonymousUser' object has no attribute 'attribute_name' 

IM期待在接下来的一个403 Forbidden或一个401 Unauthorized

代替追溯

我怎样才能得到正确的响应

+0

听起来像你的测试工作,它显示你有一个错误。 – 2015-02-11 10:24:24

回答

2

这很简单:

c = Client() 
c.login(username='fred', password='secret') 

https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.client.Client.login

你应该修改你的观点:

from django.contrib.auth.decorators import login_required 

@login_required 
def get_queryset(self): 
    ... 
+0

我想测试*** UNAUTHORIZED ****访问,所以我需要得到一个403或401它的所有工程很好,当用户验证 – 2015-02-11 10:20:42

+0

请显示查看方法,你正在测试。 – 2015-02-11 10:31:09

+0

已添加代码 – 2015-02-11 10:44:26