Django使用unittest模塊進行單元測試過程解析
Django測試框架非常簡單,首選方法是使用python標準庫中的unittest模塊。
Writing tests
Django的單元測試使用python的unittest模塊,這個模塊使用基于類的方法來定義測試。類名為django.test.TestCase,繼承于python的unittest.TestCase。
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"')
運行測試的時候,測試程序會在所有以test開頭的文件中查找所有的test cases(inittest.TestCase的子類),自動建立測試集然后運行測試。
注意:如果測試是基于數(shù)據(jù)庫訪問的(讀取、查詢Model),一定要用django.test.TestCase建立測試類,而不要用unittest.TestCase。
Runing tests
執(zhí)行目錄下所有的測試(所有的test*.py文件):
$ python manage.py test
執(zhí)行animals項目下tests包里的測試:
$ python manage.py test animals.tests
執(zhí)行animals項目里的test測試:
$ python manage.py test animals
單獨執(zhí)行某個test case:
$ python manage.py test animals.tests.AnimalTestCase
單獨執(zhí)行某個測試方法:
$ python manage.py test animals.tests.AnimalTestCase.test_animals_can_speak
為測試文件提供路徑:
$ python manage.py test animals/
通配測試文件名:
$ python manage.py test --pattern="tests_*.py"
啟用warnings提醒:
$ python -Wall manage.py test
數(shù)據(jù)庫
測試是需要數(shù)據(jù)庫的,django會為測試單獨生成數(shù)據(jù)庫。不管你的測試是否通過,當你所有的測試都執(zhí)行過后,這個測試數(shù)據(jù)庫就會被銷毀。
默認情況下,測試數(shù)據(jù)庫的名字是test_DATABASE_NAME,DATABASE_NAME是你在settings.py里配置的數(shù)據(jù)庫名.如果 你需要給測試數(shù)據(jù)庫一個其他的名字,在settings.py中指定TEST_DATABASE_NAME的值。使用sqlite3時,數(shù)據(jù)庫是在內(nèi)存中創(chuàng)建的。
除了數(shù)據(jù)庫是單獨創(chuàng)建的以外,測試工具會使用相同的數(shù)據(jù)庫配置--DATABASE_ENGINE, DATABASE_USER, DATABASE_HOST等等.創(chuàng)建測試數(shù)據(jù)庫的用戶DATABASE_USER(settings中)指定,所以你需要確認 DATABASE_USER有足夠的權(quán)限去創(chuàng)建數(shù)據(jù)庫。
測試執(zhí)行順序
為了保證所有的測試都從干凈的數(shù)據(jù)庫開始,執(zhí)行順序如下:
1.所有的TestCase子類首先運行。
2.所有其他的單元測試(unittest.TestCase,SimpleTestCase,TransactionTestCase)。
3.其它的測試(例如doctests等)
加速測試
可以將PASSWORD_HASHERS設(shè)置為更快的算法:
PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', )
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python基于similarities實現(xiàn)文本語義相似度計算和文本匹配搜索
similarities?實現(xiàn)了多種相似度計算、匹配搜索算法,支持文本、圖像,python3開發(fā),下面我們就來看看如何使用similarities實現(xiàn)文本語義相似度計算和文本匹配搜索吧2024-03-03據(jù)Python爬蟲不靠譜預(yù)測可知今年雙十一銷售額將超過6000億元
已經(jīng)是十一月十號了,雙十一即將到來,電商早已預(yù)熱多日,為了在實戰(zhàn)中獲得能力的提升,本篇文章手把手帶你用Python來預(yù)測一下今年雙十一的銷售額將會達到多少,大家可以在過程中查缺補漏,提升水平2021-11-11