我正在使用 Django REST 框架的 RetrieveUpdateDestroyAPIView 发出删除请求。
如果对象存在,则响应代码应为 204“无内容”。如果我再次发出 DELETE 请求,响应码应该是 404。
这些实际上是我在使用 Chrome 扩展 POSTMAN 时得到的状态码。有用!是的!
然后我进入tests.py,我需要做一个单元测试,所以我认为python的Requests库是最好的。但是,当我运行删除操作时,我不断收到“200”ok 状态代码,即使我在单元测试中连续删除同一个对象 3 次。
Requests 库和 Chrome 扩展 POSTMAN 给出不同的状态代码有什么原因吗?我在这里做错了什么?
#create a role, then delete it
#response = self.test_POST_role()
#print 'response in json of the test_role_POST() is %s : ' % response.json()
url = 'http://127.0.0.1:8000/lakeshoreProperties/roles/'
payload = {
"name": "test",
"description": "someone who tests"
}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
responseDict = response.json()
newly_created_role_id = responseDict['id']
print 'newly created role id is: %s ' % newly_created_role_id
#delete this newly created role
url = 'http://127.0.0.1:8000/lakeshoreProperties/role/' + str(newly_created_role_id)
print 'going to delete using this url: %s ' % url
#headers = {'content-type': 'application/json'}
delete_response = requests.delete(url)
print 'delete_response text delete is : %s' % delete_response.text
print 'delete_response code after first delete is is: %d' % delete_response.status_code
# self.assertEquals(delete_response.status_code, 200)#should be 204 no content, but who knows why???
#delete again, and get a 404 not found
delete_response = requests.delete(url)
#should be 404 no content b/c you just deleted twice, obj should not be there!
print 'delete_response code after second delete is: %d' % delete_response.status_code
# self.assertEquals(delete_response.status_code, 404)
print 'delete_response code after third delete is: %d' % delete_response.status_code
self.assertEquals(delete_response.status_code, 404)
* *以上单元测试中的所有status_codes都是200 *
运行 tests.py 时在控制台中打印的一些日志记录如下:
.newly created role id is: 59
going to delete using this url: http://127.0.0.1:8000/lakeshoreProperties/role/59
delete_response text delete is : {"id": 59, "name": "test", "description": "someone who tests"}
delete_response code after first delete is is: 200
delete_response code after second delete is: 200
delete_response code after third delete is: 200
F.{"id": 60, "name": "test", "description": "someone who tests"}