我尝试测试自定义操作。但是当我使用client
进入管理页面时,出现错误<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/donation/donation/">
class ExportToExcelTestCase(TestCase):
def setUp(self) -> None:
self.user = UserFactory()
def test_export_to_excel(self) -> None:
data = {'action': 'export_to_excel'}
change_url = '/admin/donation/donation/'
self.user.is_staff = True
self.user.is_superuser = True
self.user.save()
self.client.login(username=self.user.username, password=self.user.password)
response = self.client.post(change_url, data)
print(response) #<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/donation/donation/">
答案 0 :(得分:2)
您无法使用self.user.password
登录-这是用户的哈希值密码,而不是用户用于登录的密码-因此登录失败(您可以通过检查返回值login()
来验证这一点-它将是False
)。
由于您实际上并未在此处测试身份验证,因此应该只使用force_login
:
def test_export_to_excel(self) -> None:
data = {'action': 'export_to_excel'}
change_url = '/admin/donation/donation/'
self.user.is_staff = True
self.user.is_superuser = True
self.user.save()
self.client.force_login(self.user)
response = self.client.post(change_url, data)