Django - 单元测试

Django - 单元测试

Unit tests VS doctest

  • Unit tests —— unittest.TestCase 或 Django自定义的TestCase的子类的方法,更多
    import unittest

      class MyFuncTestCase(unittest.TestCase):
          def testBasic(self):
              a = ['larry', 'curly', 'moe']
              self.assertEqual(my_func(a, 0), 'larry')
              self.assertEqual(my_func(a, 1), 'curly')
    
  • Doctest —— 内嵌在函数帮助文档中的测试,写法类似Python解释器的语法,更多
    def my_func(a_list, idx):
    """
    >>> a = ['larry', 'curly', 'moe']
    >>> my_func(a, 0)
    'larry'
    >>> my_func(a, 1)
    'curly'
    """
    return a_list[idx]

大多数情况下,应该选择单元测试,只有在进行简单测试时才适合选择Doctest

Testing Django Applications (文档)

对于一个Django应用程序(注1),测试执行进程从两个地方寻找单元测试的代码:

  • models.py文件, 测试执行进程在这个模块中寻找unittest.TestCase的子类
  • Django应用程序目录下的tests.py文件,测试执行进程在这个模块中寻找unittest.TestCase的子类

注1: Django应用程序的路径即注册在配置文件(manage.py)中INSTALLED_APPS属性中的项

Django自带的django.test.TestCase会在每次单元测试中创建临时的测试数据库。

运行单元测试
$ python manage.py test     #运行项目中所有APP的单元测试
$ python manage.py test app1    #运行app1下的单元测试
$ python manage.py test app1.A1TestCase  #运行app1下的A1TestCase用例
$ python manage.py test app1.A1TestCase.mehthod1  #同上了类推

Testing Tools

测试客户端

可以使用测试客户端模拟HTTP请求,与Django视图进行交互

  • 模拟GET和POST请求,获取HTTP响应。
  • 查看重定向链,在每一步重定向检查URL和状态码
  • 检查用于模板渲染的模板上下文环境

Django的测试客户端专注于一下两点:

  1. 确保用于渲染模板的模板上下文是正确的
  2. 专注与服务端的返回值,至于页面渲染等HTML,JS测试应该使用其他工具

django.test.client.Client
client实例有post和get方法

class Client(enforce_csrf_checks=False, **defaults)

get(path, data={}, follow=False, **extra)   # **extra关键字参数可以用于指定HTTP头信息中的字段值

post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)      # 传递JSON数据,content_type=application/json

head(path, data={}, follow=False, **extra)

options(path, data='', content_type='application/octet-stream', follow=False, **extra)

put(path, data='', content_type='application/octet-stream', follow=False, **extra)

delete(path, data='', content_type='application/octet-stream', follow=False, **extra)

注: 增加HTTP 头信息:

  • AUTHORIZATION: HTTP_AUTHORIZATION
  • USER_AGENT: HTTP_USER_AGENT
Testing response

class Response 有以下属性

  • client
  • content
  • context
  • request
  • status_code
  • templates
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 为什么需要自动化测试 对于大项目,对每个单元进行测试可以快速定位错误,确保项目质 量 在 python 中,利用 ...
    null_fca6阅读 11,658评论 0 2
  • 一、django单元测试框架: 编写测试用例: 引用TestCase基类:django.test继承了python...
    EldonZhao阅读 8,796评论 0 0
  • Django的单元测试使用python的unittest模块,这个模块使用基于类的方法来定义测试。类名为djang...
    nine_9阅读 3,395评论 2 0
  • 本文主要介绍基于Django框架开发的web程序进行单元测试。 因为使用django程序的view函数的参数一般为...
    C3_b262阅读 4,112评论 0 0
  • Django自带单元测试的模块django.test,该模块使用了Python的标准库unitest,基于类的方法...
    LeeDa李阅读 4,601评论 0 0