19.1. Tests About
django.test.TestCaseAll Django tests run always with
DEBUG=Falsehttps://docs.djangoproject.com/en/stable/topics/testing/overview/
19.1.1. Structure
shop
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests
│ ├── __init__.py
│ ├── test_forms.py
│ ├── test_models.py
│ ├── test_templates.py
│ ├── test_urls.py
│ └── test_views.py
└── views.py
19.1.2. Types
SimpleTestCase- no database interactionTestCase- database interactionTransactionTestCase- wraps each test in a transactionLiveServerTestCase- runs a live server in the backgroundStaticLiveServerTestCase- runs a live server in the background with static files
19.1.3. TestCase
>>>
... from django.test import TestCase
... from shop.models import Customer
...
...
... class CustomerTestCase(TestCase):
... def setUp(self):
... mark = Customer.objects.create(firstname='Mark', lastname='Watney')
... melissa = Customer.objects.create(firstname='Melissa', lastname='Lewis')
...
... def test_customer_create(self):
... customer = Customer.objects.create(firstname="Mark", lastname="Watney")
... self.assertEqual(customer.firstname, 'Mark')
... self.assertEqual(customer.lastname, 'Watney')
...
... def test_customer_create_invalid(self):
... with self.assertRaises(IntegrityError):
... Customer.objects.create(firstname='Mark1', lastname='Watney')
... with self.assertRaises(IntegrityError):
... Customer.objects.create(firstname='Mark', lastname='Watney1')
... with self.assertRaises(IntegrityError):
... Customer.objects.create(firstname='Mark1', lastname='Watney1')
... with self.assertRaises(IntegrityError):
... Customer.objects.create(firstname='Mark', lastname='Watney', birthdate='2000-01-01')
...
... def test_customer_age(self):
... self.mark.birthdate = date(2000, 1, 1)
... self.assertEqual(self.mark.age, 24)
...
... def test_customer_friends(self):
... self.assertIn(self.melissa, self.mark.friends)
...
... def test_customer_isadult_when_senior(self):
... self.mark.birthdate = date(2000, 1, 1)
... self.assertTrue(c1.is_adult())
...
... def test_customer_isadult_when_junior(self):
... self.mark.birthdate = date(2024, 1, 1)
... self.assertFalse(c2.is_adult())
19.1.4. Python Assertions
assertEqual(a, b)- checks thata == bassertNotEqual(a, b)- checks thata != bassertTrue(x)- checks thatbool(x) is TrueassertFalse(x)- checks thatbool(x) is FalseassertIs(a, b)- checks thata is bassertIsNot(a, b)- checks thata is not bassertIsNone(x)- checks thatx is NoneassertIsNotNone(x)- checks thatx is not NoneassertIn(a, b)- checks thata in bassertNotIn(a, b)- checks thata not in bassertIsInstance(a, b)- checks thatisinstance(a, b)assertNotIsInstance(a, b)- checks thatnot isinstance(a, b)
19.1.5. Django Assertions
assertTemplateUsed(response, filename)