Django 单元测试

Client

django.test.Client 模拟了一个web用户的行为,通过模拟GET与POST请求,以浏览器的视角追踪url跳转、返回结果

使用方法:

模拟请求:
c = Client()
response = c.get(path, data=None, follow=False, secure=False, **extra)
response = c.post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra)

其中,response的属性有:

  • client:发起模拟请求的client
  • content:也就是reponse的body
  • context:返回的网页渲染使用的数据
  • json:将body解析为json格式
  • request:模拟请求时request中的data
  • status_code:http状态码
  • templates:返回的网页渲染使用的模板
  • resolver_match:判断实际处理请求的view是否是预期的view,不能直接用于使用as_view生成的视图
# my_view here is a function based view
self.assertEqual(response.resolver_match.func, my_view)

# class-based views need to be compared by name, as the functions
# generated by as_view() won't be equal
self.assertEqual(response.resolver_match.func.__name__, MyView.as_view().__name__)
测试Django登录系统:
c.login(username='fred', password='secret')
c.force_login(user, backend=None)
c.logout()
Testcase

使用方法:

  • classmethod TestCase.setUpTestData():更改全局的测试数据
  • TestCase.setUp():每个测试函数执行前执行,为测试做准备
  • TestCase.tearDown():每个测试函数执行后执行,清理场景

基于比较的断言:

  • assertEqual()
  • assertTrue()
  • assertHTMLEqual(html1, html2, msg=None)
  • assertHTMLNotEqual(html1, html2, msg=None)
  • assertXMLEqual(xml1, xml2, msg=None)
  • assertXMLNotEqual(xml1, xml2, msg=None)
  • assertJSONEqual(raw, expected_data, msg=None)
  • assertJSONNotEqual(raw, expected_data, msg=None)
  • assertQuerysetEqual(qs, values, transform=repr, ordered=True, msg=None)

基于异常的断言:

  • assertRaisesMessage(expected_exception, expected_message, callable, *args, **kwargs)
  • assertRaisesMessage(expected_exception, expected_message)

基于输入的特定field的断言:

  • assertFieldOutput(fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value='')
运行单元测试:
# 测试整一个工程
$ python manage.py test 
# 只测试某个应用
$ python manage.py test app --keepdb
# 只测试一个Case
$ python manage.py test MyTestCase
# 只测试一个方法
$ python manage.py test My_test_func

参考资料:https://docs.djangoproject.com/en/2.0/topics/testing/tools/
https://www.jianshu.com/p/34267dd79ad6

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、django单元测试框架: 编写测试用例: 引用TestCase基类:django.test继承了python...
    EldonZhao阅读 8,824评论 0 0
  • Django - 单元测试 Unit tests VS doctest Unit tests —— unittes...
    BlockGeeks阅读 8,632评论 0 50
  • 相关资源 Django官方文档unittest文档 简单的例子 关于django的单元测试,需要知道的是 对于每一...
    Ljian1992阅读 13,896评论 0 14
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,124评论 19 139
  • 《同读一本书.王朋彦》2017-2-15-032《管理的觉醒》 原文:存在是绝对的,显现是相对的。绝对的存在每时每...
    王朋彦阅读 1,715评论 4 1

友情链接更多精彩内容