Django 单元测试

2018-10-13  本文已影响0人  SSRSGJYD
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的属性有:

# 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

使用方法:

基于比较的断言:

基于异常的断言:

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

运行单元测试:
# 测试整一个工程
$ 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

上一篇 下一篇

猜你喜欢

热点阅读