Djangoでのテスト実施
Djangoのテスト
Djangoにおけるテストについての勉強記録です。 誤記や不足はコメントで指摘いただければ幸いです!
テスト実行コマンド
python manage.py test [[アプリケーション名]]
testコマンドを実行すると・・・
- Djangoは "test" ではじまるモジュールを見つける
- そのモジュール内でdjango.test.TestCaseクラスを継承したクラスを見つける
- その後、TestCaseクラスに定義されているメソッドを実行
TestCaseクラスのメソッド
- setUp → テストメソッドが呼ばれるたびに実行される
- tearDown → テストメソッド終了後、結果が記録された後に呼ばれる
- test○○ → アサーションメソッドを用いてテスト実行するメソッド
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="li——on") cat = Animal.objects.get(name="cat") self.assertEqual(lion.speak(), 'The lion says "roar"') self.assertEqual(cat.speak(), 'The cat says "meow"')
Pythonユニットテストでのモック作成
- バージョン3.3で追加されたunittest.mockライブラリを使えばいけそうです。
実装例:
from unittest.mock import MagicMock thing = ProductionClass() thing.method = MagicMock(return_value=3) thing.method(3, 4, 5, key='value') thing.method.assert_called_with(3, 4, 5, key='value')
- 「関数の実行時にモックが何回呼ばれたか」をテストできます
- 参考元→https://docs.python.org/ja/3/library/unittest.mock.html