如何進行Django單元測試
阿新 • • 發佈:2018-12-07
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*.py檔案):執行測試的時候,測試程式會在所有以test開頭的檔案中查詢所有的test cases(inittest.TestCase的子類),自動建立測試集然後執行測試。
$ python manage.py test
執行animals專案下tests包裡的測試:
$ python manage.py testanimals.tests
執行animals專案裡的test測試:
$ python manage.py testanimals
單獨執行某個test case:
$ python manage.py testanimals.tests.AnimalTestCase
單獨執行某個測試方法:
$ python manage.py testanimals.tests.AnimalTestCase.test_animals_can_speak
為測試檔案提供路徑:
$ python manage.py testanimals/
通配測試檔名:
$ python manage.py test--pattern="tests_*.py"
啟用warnings提醒:
$ python -Wall manage.py test