【发布时间】:2012-01-27 13:32:11
【问题描述】:
我有一个这样的通用视图:
class SaveView(CreateView):
def get_initial(self):
# Get the initial dictionary from the superclass method
initial = super(SaveView, self).get_initial()
# Copy the dictionary so we don't accidentally change a mutable dict
initial = initial.copy()
initial['user'] = self.request.user
return initial
此视图具有 login_required 装饰器,因此 self.request.user 始终有效。
当我使用浏览器访问该页面时,一切正常,但我的测试失败了。我有以下测试设置:
from django.test import TestCase, client
class MyTest(TestCase):
def setUp(self):
self.client = client.Client()
def test1(self):
self.assertTrue(self.client.login(username='user1',password='password1'))
data = {'name':'test 1'}
response = self.client.post('/app/save/', data)
self.assertEqual(response.status_code, 302)
'/app/save/' 是调用该视图的 url(它在浏览器上运行良好 我的模型有 2 个必填字段“名称”和“用户”,所以这应该会重定向到创建的对象页面,因为我已经通过数据传递了名称,并且应该从 get_initial 方法获取用户。
这确实是“现实生活”中发生的事情,即浏览器。
我可以使这个测试成功通过数据字典中的“用户”的唯一方法。
这是 django.test 模块中的错误还是这是预期的行为,为什么?
提前致谢
【问题讨论】:
标签: django testing django-generic-views