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
网友评论