19.1. Tests About

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 interaction

  • TestCase - database interaction

  • TransactionTestCase - wraps each test in a transaction

  • LiveServerTestCase - runs a live server in the background

  • StaticLiveServerTestCase - 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 that a == b

  • assertNotEqual(a, b) - checks that a != b

  • assertTrue(x) - checks that bool(x) is True

  • assertFalse(x) - checks that bool(x) is False

  • assertIs(a, b) - checks that a is b

  • assertIsNot(a, b) - checks that a is not b

  • assertIsNone(x) - checks that x is None

  • assertIsNotNone(x) - checks that x is not None

  • assertIn(a, b) - checks that a in b

  • assertNotIn(a, b) - checks that a not in b

  • assertIsInstance(a, b) - checks that isinstance(a, b)

  • assertNotIsInstance(a, b) - checks that not isinstance(a, b)

19.1.5. Django Assertions

  • assertTemplateUsed(response, filename)