我试图在change_list
视图中为管理员操作编写测试。我提到this question但无法让测试工作。这是我的代码和问题:
class StatusChangeTestCase(TestCase):
"""
Test case for batch changing 'status' to 'Show' or 'Hide'
"""
def setUp(self):
self.categories = factories.CategoryFactory.create_batch(5)
def test_status_hide(self):
"""
Test changing all Category instances to 'Hide'
"""
# Set Queryset to be hidden
to_be_hidden = models.Category.objects.values_list('pk', flat=True)
# Set POST data to be passed to changelist url
data = {
'action': 'change_to_hide',
'_selected_action': to_be_hidden
}
# Set change_url
change_url = self.reverse('admin:product_category_changelist')
# POST data to change_url
response = self.post(change_url, data, follow=True)
self.assertEqual(
models.Category.objects.filter(status='show').count(), 0
)
def tearDown(self):
models.Category.objects.all().delete()
我尝试使用print
查看响应是什么,这就是我得到的结果:
<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/product/category/">
它似乎需要我的登录凭据 - 我尝试在setUp()
中创建用户并按照Django docs的测试登录,但它似乎无法正常工作。
任何帮助将不胜感激!
答案 0 :(得分:0)
我找到了解决方案 - 当我创建超级用户时,我没有实例化Django的Client()
类,因此每当我登录时 - 它都不会在我的后续请求中持续存在。正确的代码应如下所示。
def test_status_hide(self):
"""
Test changing all Category instances to 'Hide'
"""
# Create user
user = User.objects.create_superuser(
username='new_user', email='test@example.com', password='password',
)
# Log in
self.client = Client()
self.client.login(username='new_user', password='password')
# Set Queryset to be hidden
to_be_hidden = models.Category.objects.values_list('pk', flat=True)
# Set POST data to be passed to changelist url
data = {
'action': 'change_to_hide',
'_selected_action': to_be_hidden
}
# Set change_url
change_url = self.reverse('admin:product_category_changelist')
# POST data to change_url
response = self.client.post(change_url, data, follow=True)
self.assertEqual(
models.Category.objects.filter(status='show').count(), 0
)