[Django]ユニットテスト

– from django.test import TestCaseでTestCaseを継承
– メソッドはtest_* にしなければならない
/sns/tests.py

from django.test import TestCase

class SnsTests(TestCase):

	def test_check(self):
		x = True
		self.assertTrue(x)
		y = 100
		self.assertGreater(y, 0)
		arr = [10, 20, 30]
		self.assertIn(20, arr)
		nn = None
		self.assertIsNone(nn)

$ python manage.py test sns
Creating test database for alias ‘default’…
System check identified no issues (0 silenced).
.
———————————————————————-
Ran 1 test in 0.001s

OK
Destroying test database for alias ‘default’…

### チェックメソッド
– assertTrue, assertFalse, assertIsl, assertIsNot, assertEqual, assertNoEqual, assertGreater, assertGreaterEqual, assertLess, assertLessEqual, assertIsNone, assertIsNotNone, assertIsIn, assertNotIn

### データベースのチェック

from django.test import TestCase

from django.contrib.auth.models import User
from .models import Message

class SnsTests(TestCase):

	def test_check(self):
		usr = User.object.first()
		self.assertIsNotNone(usr)
		msg = Message.objects.first()
		self.assertIsNotNone(msg)

– テスト用のデータベースを都度作って使用している

from django.test import TestCase

from django.contrib.auth.models import User
from .models import Group, Message

class SnsTests(TestCase):

	@classmethod
	def setUpClass(cls):
		super().setUpClass()
		(usr, grp) = cls.create_user_and_group()
		cls.create_message(usr, grp)

	@classmethod
	def create_user_and_group(cls):
		# Create public user & public group
		User(username="public", password="public", is_staff=False, is_active=True).save()
		pb_usr = User.objects.filter(username='public').first()
		Group(title='public', owner_id=pb_usr.id).save()
		pb_grp = Group.objects.filter(title='public').first()

		# Create test user
		User(username="test", password="test", is_staff=True, is_active=True).save()
		usr = User.objects.filter(username='test').first()

		return (usr, pb_grp)

	@classmethod
	def create_message(cls, usr, grp):
		# Create test massage
		Message(content='this is test message.', owner_id=usr.id, group_id=grp.id).save()
		Message(content='test', owner_id=usr.id, group_id=grp.id).save()
		Message(content="ok", owner_id=usr.id, group_id=grp.id).save()
		Message(content="ng", owner_id=usr.id, group_id=grp.id).save()
		Message(content='finish', owner_id=usr.id, group_id=grp.id).save()

	def test_check(self):
		usr = User.objects.first()
		self.assertIsNotNone(usr)
		msg = Message.objects.first()
		self.assertIsNotNone(msg)