原文地址:
https://docs.djangoproject.com/en/1.11/topics/testing/
自动化测试是非常有用的,你可以使用测试套件来解决,避免许多问题,例如:
由于网络应用逻辑比较负责,且涉及到很多方面,例如:http请求路由、表单校验,应用逻辑处理,页面渲染,因此测试网页应用是非常复杂的。Django提供了许多测试工具,这些工具可以:模拟网络请求、插入测试数据、检验应用输出、代码校验。
本文分为如下几个部分:
https://docs.djangoproject.com/en/1.11/topics/testing/overview/
Django单元测试使用来Python标准库:unittest。
例子:
from django.test import TestCase
from myapp.models import Animal
class AnimalTestCase(TestCase):
def setUp(self):
Animal.objects.create(name="lion", sound="roar")
Animal.objects.create(name="cat", sound="meow")
def test_animals_can_speak(self):
"""Animals that can speak are correctly identified"""
lion = Animal.objects.get(name="lion")
cat = Animal.objects.get(name="cat")
self.assertEqual(lion.speak(), 'The lion says "roar"')
self.assertEqual(cat.speak(), 'The cat says "meow"')
在测试时,默认是寻找所有的nittest.TestCase的子类,然后构造相关的测试用例进行测试。
Django运行测试用例的顺序为:
test client 是一个Python 类,该类描述了一个简单的web 浏览器,你可以使用该类来测试你的视图处理函数view ,测试和你的应用交互逻辑。该类的用法包括:
注意:Django test client 不是 Selenium 或是其他内置浏览器的替代品。
先来一个简单的例子:
>>> from django.test import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
>>> response.status_code
200
>>> response = c.get('/customer/details/')
>>> response.content
b'
注意:运行上述测试用例都不需要Webserver处于运行状态。实际上,上述代码避免了和HTTP 和与Django框架交互的开销。
类声明:
class Client(enforce_csrf_checks=False, **defaults)
创建 django.test.Client实例
c = Client(HTTP_USER_AGENT='Mozilla/5.0')
(2)类实例方法:
>>> c = Client()
>>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
等同于请求:/customers/details/?name=fred&age=7
extra参数可用定义 http请求header。
当follow为true 时,会跟踪重定向请求。
>>> c = Client()
>>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
data中指定post数据;另外,要提交file数据,需要指定文件指针,例如:
>>> c = Client()
>>> with open('wishlist.doc') as fp:
... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
client发送请求后,返回的是一个Response对象(注意,该对象不是一个HttpResponse类实例)。该response对象具有如下属性:
状态的持久化
test client 是有状态的。如果某个response返回了cookie数据,则cookie数据会保存起来,后续的get/post请求会将cookie数据发送出去。
这些cookie数据不会过期。如果你想让某些数据过期,则需要手动的删除,或是创建一个client对象。
这些状态数据存储在:Client.cookies,Client.session 属性中。
import unittest
from django.test import Client
class SimpleTest(unittest.TestCase):
def setUp(self):
# Every test needs a client.
self.client = Client()
def test_details(self):
# Issue a GET request.
response = self.client.get('/customer/details/')
# Check that the response is 200 OK.
self.assertEqual(response.status_code, 200)
# Check that the rendered context contains 5 customers.
self.assertEqual(len(response.context['customers']), 5)
如果数据库里没有数据,那么对于一个基于数据库的网站来说,test case并无多大的用处.为了给测试数据库加入测试数据更方便,django提供了载入fixtures的方法.
fixture是一系列的数据集合,django知道如何将它导入数据库。
创建fixture最直接的方法就是使用manage.py dumpdata.当然,这假设你的实际数据库里已经有数据了.
注意:
如果你运行过manage.py syncdb命令,那么你已经使用过fixture了–只是你不知道而已。当你使用syncdb去创建数据库时,会创建一个叫initial_data的fixture。
其他名字的Fixture可以通过manage.py loaddata命令手动安装.
一旦建立了一个fixture,并将它放在了某个django app的fixtures目录中,你就可以在你的测试类里使用它了:
from django.test import TestCase
from myapp.models import Animal
class AnimalTestCase(TestCase):
fixtures = ['mammals.json', 'birds']
def setUp(self):
# Test definitions as before.
call_setup_methods()
def testFluffyAnimals(self):
# A test that uses the fixtures.
call_some_test_code()
这是具体发生的过程:
除了python中的assertEqual()和assertTrue()外,django的TestCase还提供了几个额外的assert方法。
assertContains(response, text, count=None, status_code=200, msg_prefix=’’, html=False)
断言response是否与status_code和text内容相应。将html设为True会将text作为html处理。
assertJSONEqual(raw, expected_data, msg=None)
断言Json片段raw和expected_data是否相当。
RequestFacTory 和test client 具有相同的API。test client 是行为表现和浏览器类型,但是RequestFacTory是直接生成一个能被view接受的 request实例。因此,你可以想测试其他函数一样,测试你的应用函数。
相比test client 来说,requestfactory的功能比较受限,具体表现在:
使用示例:
from django.contrib.auth.models import AnonymousUser, User
from django.test import TestCase, RequestFactory
from .views import MyView, my_view
class SimpleTest(TestCase):
def setUp(self):
# Every test needs access to the request factory.
self.factory = RequestFactory()
self.user = User.objects.create_user(
username='jacob', email='jacob@…', password='top_secret')
def test_details(self):
# Create an instance of a GET request.
request = self.factory.get('/customer/details')
# Recall that middleware are not supported. You can simulate a
# logged-in user by setting request.user manually.
request.user = self.user
# Or you can simulate an anonymous user by setting request.user to
# an AnonymousUser instance.
request.user = AnonymousUser()
# Test my_view() as if it were deployed at /customer/details
response = my_view(request)
# Use this syntax for class-based views.
response = MyView.as_view()(request)
self.assertEqual(response.status_code, 200)
虽然Django 没有显示的声明支持除了unit test之外的测试框架,但是Django提供了激活测试用例的方式,这些测试用例运行起来就好像是Django的普通测试用例。
当运行 ./manage.py test
脚本时,Django 寻找TEST_RUNNER
设置,决定运行动作。默认情况下,TEST_RUNNER 指向django.test.runner.DiscoverRunner
。该类指定类Django的默认测试行为,包括:
test*.py
的测试文件;