django 测试客户端所有 url 均返回 404
我正在使用 django 测试进行第一个实验,我遇到的问题是,无论我使用哪个 url(甚至 /),我总是得到 404 模板。 如果我将完全相同的代码放入 django shell 中,它就会按预期工作,并且始终向我显示所请求的 url 的内容。
class SimpleTest(TestCase):
def setUp(self):
self.user = User.objects.create_user('test', 'test', 'test')
self.user.is_staff = True
self.user.save()
self.client = Client()
def test_something(self):
self.assertTrue(self.client.login(username='test', password= 'test'))
self.client.get("/")
登录返回True,但get()失败。有任何提示我在这里做错了什么吗?
I am doing my first experiments with django testing and I am having the problem that I always get the 404 template regardless which url (even /) I am using.
If I throw the very same code into the django shell it's working as expected and always presents me the contents of the requested url.
class SimpleTest(TestCase):
def setUp(self):
self.user = User.objects.create_user('test', 'test', 'test')
self.user.is_staff = True
self.user.save()
self.client = Client()
def test_something(self):
self.assertTrue(self.client.login(username='test', password= 'test'))
self.client.get("/")
The login returns True, but the get() fails. Any hints what I am doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住,大多数视图都使用
get_object_or_404
、get_list_or_404
之类的内容,或者在访问某个对象或另一个对象出现问题时简单地引发Http404
。您需要确保测试数据库中填充了足够的对象来满足所有这些要求,以使视图不会返回 404。请记住,运行测试时,数据库会在每次测试后回滚(使用事务) ),因此每个测试方法必须独立,或者
setUp
方法必须使用任何所需的依赖项填充数据库。Keep in mind that most views use something like
get_object_or_404
,get_list_or_404
, or simply raiseHttp404
when there's a problem accessing some object or another. You'll need to make sure that your test database is populated with sufficient objects to fulfill all these requirements to make the view not return a 404.Remember, when running tests, the database is rolled back after each test (using transactions), so each test method must stand on its own or the
setUp
method must populate the database with any required dependencies.