我正在尝试测试访问django中的API的 *未经身份验证的 / 未经授权的用户。在API中我有以下代码
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'
我期待403 Forbidden或401 Unauthorized
而不是追溯
我怎样才能得到正确的答案
答案 0 :(得分: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):
...