18.1. Tests About
django.test.TestCase
All Django tests run always with
DEBUG=False
https://docs.djangoproject.com/en/stable/topics/testing/overview/
18.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
18.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
18.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())
18.1.4. Python Assertions
assertEqual(a, b)
- checks thata == b
assertNotEqual(a, b)
- checks thata != b
assertTrue(x)
- checks thatbool(x) is True
assertFalse(x)
- checks thatbool(x) is False
assertIs(a, b)
- checks thata is b
assertIsNot(a, b)
- checks thata is not b
assertIsNone(x)
- checks thatx is None
assertIsNotNone(x)
- checks thatx is not None
assertIn(a, b)
- checks thata in b
assertNotIn(a, b)
- checks thata not in b
assertIsInstance(a, b)
- checks thatisinstance(a, b)
assertNotIsInstance(a, b)
- checks thatnot isinstance(a, b)
18.1.5. Django Assertions
assertTemplateUsed(response, filename)