django 的单元测试分为2种,一种是doc test ,一种是 unit test.html
这里只描述 unit test.python
这里是官方文档:https://docs.djangoproject.com/en/dev/topics/testing/overview/ git
其中的重点是:github
在咱们的项目模块中创建 test.py (这个很重要,django默认加载模块中的test.py文件来执行测试)。在其中定义模块继承 django.test.TestCase。python 会自动加载咱们定义的模块的以 test 开头的方法。sql
from django.test import TestCase from myapp.models import Animalclass 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"')
完成以后,执行命令数据库
./manage.py test
默认状况下,django的测试过程会 建立测试数据库,执行test。删除测试数据库 。django
这是一个很蛋疼的地方,由于测试数据库建立过程会花费很长的时间。app
对于这中状况,有2个解决办法:ide
1.使用内存数据库sqlite。在settings.py中配置单元测试
if 'test' in sys.argv: DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3',}
这样作,一样会建立测试数据库,可是时间会少不少。
2.使用django的testrunner。 在settings.py中配置
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
这样作,一样也会建立数据库,可是这个建立数据库的时间话费也很是的少。
3.git hub上面有个项目叫作 django-test-utils 。这个项目有一个功能叫作 复用默认的数据库,不过,我安装了这个代码,使用了这个功能后,提示说,模块没有keep-database 这个属性的错误。google 上也有人说这个问题。一样是,没有解决方案。因此,这个方法,没有跑通。
其实这个问题的缘由是,他这个项目的keep-database模块的写法太老,django没法读取。非要用这keep-database的这个逻辑的话,能够将 'django.test.runner.DiscoverRunner' 的复制出来,在里面把建立数据库和删除数据库的逻辑给干掉。
在上面方法1+方法2一块儿使用的时候,虽然建立了测试数据库,可是最终话费的时间是很是少的,因此,这个办法组合也算是解决了这个问题。