2015-02-11 82 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

相關問題