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

你可能感兴趣的:(Django - 单元测试)