问题描述
这是我在Django中的第一个测试-这是一个简单的视图测试,用于断言响应为200.
This is my first test in Django - it's a simple view test to assert that the response in 200.
我正在使用身份验证,因此首先要创建一个测试用户:
I'm using the authentication so I'm creating a test user in the first place:
class SettingsTests(TestCase):
def setUp(self):
self.client = Client()
self.username = 'test_user'
self.email = 'test@whatever.com'
self.password = 'test'
self.user = User.objects.create_user(self.username, self.email, self.password)
def tearDown(self):
self.user.delete()
这是我要测试视图的实际测试:
Here's the actual test where I'm trying to test the view:
def test_settings_view_is_diplayed_correctly(self):
login = self.client.login(username = self.username, password = self.password)
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
这总是返回404,但是如果我在 shell
中尝试相同的方法,它将返回200!
This always returns 404, however if I try the same in the shell
it works and returns 200!
有人可以告诉我这是怎么回事吗?
Can somebody please tell me what's wrong here?
推荐答案
Alasdair提出的问题是视图.我有一个get_object_or_404快捷方式,但未提供所需的对象.因此,视图返回404并且测试失败...
The problem, as suggested by Alasdair was the view. I had a get_object_or_404 shortcut and did not provide the needed object. Hence, the view was returning 404 and the test was failing...
这篇关于Django测试客户端获取返回404但是在shell中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!