Django REST framework 单元测试实例解析
这篇文章主要介绍了DjangoRESTframework单元测试实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
环境
Win10
Python3.7
Django2.2
项目
参照官网快速开始写了一个demo
测试
参照官网测试
和Django的测试差不多
创建tutorial/tests/tests.py
importjson
fromdjango.testimportTestCase
fromrest_frameworkimportstatus
fromrest_framework.testimportAPIClient
classLittleTestCase(TestCase):
defsetUp(self):
self.click=APIClient()
deftest_users_post(self):
#/users/POST
data={
"username":"tom",
"email":"tom@example.com"
}
response=self.client.post("/users/",data)
self.assertEqual(response.status_code,status.HTTP_201_CREATED)
#/users/:idGET地址
response_content=json.loads(response.content)
user_url=response_content["url"]
#/users/:idGET检查新增用户是否符合预期
response=self.client.get(user_url)
response_content=json.loads(response.content)
self.assertEqual(response.status_code,200)
self.assertEqual("tom",response_content["username"])
self.assertEqual("tom@example.com",response_content["email"])
执行测试
pythonmanage.pytest<测试文件所在目录>
pythonmanage.pytesttests/
测试结果
执行一个测试成功
测试前创建测试数据库,测试完毕删除数据库
Creatingtestdatabaseforalias'default'... Systemcheckidentifiednoissues(0silenced). . ---------------------------------------------------------------------- Ran1testin0.022s OK Destroyingtestdatabaseforalias'default'...
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。