Django的单元测试
1、单元测试框架
django-unittest
https://docs.djangoproject.com/en/1.9/topics/testing/overview/#speeding-up-the-tests
自动生成测试数据库时候,要注意编码问题,特别是数据库中存储了汉字信息。 需要在
"default": { "ENGINE": "django.db.backends.mysql", "NAME": "webplatform", "USER": "root", "PASSWORD": "123456", "HOST": "127.0.0.1", "PORT": "3306", 'TEST_CHARSET': "utf8", 'TEST_COLLATION': "utf8_general_ci", },
2、模拟数据
有两种办法,其一是通过api去手动生成;其二是通过fixture,让测试框架自动导数据到测试数据库中去
方法一,多用 model.mommy开源包
方法二,可能很多场合应该更适合,特别是数据表大的时候
https://docs.djangoproject.com/en/1.9/topics/testing/tools/#fixture-loading
注意导出真实数据库的auth数据时候,要用如下命令,具体原因:
python manage.py dumpdata auth --exclude auth.Permission --exclude contenttypes --indent=4 > auth.json
3、模拟浏览器
https://realpython.com/blog/python/testing-in-django-part-1-best-practices-and-examples/
https://realpython.com/blog/python/testing-in-django-part-2-model-mommy-vs-django-testing-fixtures/
https://realpython.com/blog/python/django-1-6-test-driven-development/