我用UserPassesTestMixin保護了一個基於django類的視圖。它的test_func接收一個名爲division的參數,並檢查當前用戶是否是該部門的負責人。用django測試客戶端測試UserPassesTestMixin
視圖在網站中完美運行,但我一直無法寫出成功的測試。似乎在client.get和test_func之間,用戶正在消失。
我試過這與RequestFactory和客戶端。我試過強迫登錄。確保正確的中間件就位。
mixin的測試沒有幫助我看到問題。 (https://github.com/django/django/blob/29f607927fe82e2c8baab171dfa8baf710cd9b83/tests/auth_tests/test_mixins.py)
現在我陷入了無法測試UserPassesTestMixin保護的視圖的各種角色。我很感激任何見解,爲什麼當我登錄使用client.login(用戶名='div1chair',密碼='basicpassword'),在視圖本身中有一個空的self.request.user。
def test_permissions_to_access_division_summary_view(self):
"""
This test ensures that only department chairs and the division
director for the specific division detail can see the division
summary.
"""
url = "/division1"
client = Client()
client.login(username='div1chair', password='basicpassword')
# ipdb here confirms that div1chair is logged in
# ETA: ut oh. looks like this is not accurate. Now I'm really confused. client.login is giving False.
response = client.get(url,follow=True)
self.assertEqual(response.status_code, 200) # AssertionError: 404 != 200
這是我測試的視圖。
class DivisionDirectorView(UserPassesTestMixin, View):
def test_func(self):
division = Division.objects.get(short_name=self.kwargs['division'])
# ipdb here confirms that there is no user, or at least username is ''
if self.request.user == division.director:
return True
return False
埃塔:這裏是urls.py:
from django.conf.urls import url
from fds.apps.professionalmetrics import views
urlpatterns = [
url(r'^$', views.metrics_default, name='metrics_default'),
# SNIP
url(r'(?P<division>[\w-]+)/$',
views.DivisionDirectorView.as_view(),
name='div-metric-summary'),
]
謝謝,阿拉斯代爾!我已經按照你的建議簡化了test_func代碼,並且效果很好。我仍然不明白爲什麼當測試使用client.login(username ='div1chair',password ='basicpassword')登錄時,視圖本身有一個空的self.request.user。我附上了urls.py,儘管我的猜測是這不是。 test_func失敗,因爲self.request.user爲空。我感謝您的評論! – robline
你怎麼知道'client.login(...)'成功了?你有沒有檢查過,以確保它返回「真」?我沒有看到你的測試中的'/ division1'是如何匹配你發佈的任何url。 – Alasdair
就是這樣!謝謝。問題是我需要強制登錄。我早些時候嘗試過,但不知怎的,它做錯了。此外,道歉剔除urls.py的錯誤部分。我會更新這個問題,雖然事實證明,強迫登錄解決它。 – robline