According to the docs:
A TestCase, on the other hand, does not truncate tables and reload
initial data at the beginning of a test. Instead, it encloses the test
code in a database transaction that is rolled back at the end of the
test. It also prevents the code under test from issuing any commit or
rollback operations on the database, to ensure that the rollback at
the end of the test restores the database to its initial state. In
order to guarantee that all TestCase code starts with a clean
database, the Django test runner runs all TestCase tests first, before
any other tests (e.g. doctests) that may alter the database without
restoring it to its original state.
So if I have a test that looks like this:
class GeneralUserCreateTest(TestCase):
def setUp(self):
create_roletypes()
create_permissiontypes()
self.client = Client()
self.event = create_event()
def test_create(self):
create_url = reverse('event_user_signup', args=[self.event.slug])
post_data = {
'signup-account-email': 'foo@bar.com',
'signup-account-password': 'foobar',
'signup-account-password2': 'foobar',
'signup-account-first_name': 'Foo',
'signup-account-last_name': 'Bar',
}
response = self.client.post(create_url, data=post_data)
self.assertEqual(response.status_code, 302)
# check creation of user object
self.assertEqual(User.objects.filter(email=post_data['signup-account-email']).count(), 1)
user = User.objects.get(username=post_data['signup-account-email'])
# user and profile objects created
self.assertEqual(User.objects.all().count(), 1)
self.assertEqual(Profile.objects.all().count(), 1)
# get the first user and profile object to test against submitted field
user = User.objects.all()[0]
profile = Profile.objects.all()[0]
role = Role.objects.filter(event=self.event, profiles=profile)[0]
self.assertEqual(role.roletype.name, 'General')
self.assertEqual(user.username, post_data['signup-account-email'])
self.assertEqual(user.email, post_data['signup-account-email'])
self.assertEqual(profile.first_name, post_data['signup-account-first_name'])
self.assertEqual(profile.last_name, post_data['signup-account-last_name'])
Is it still necessary to run a teardown method or does the TestCase class take care of it? If so, when should one use the teardown method given the availability of the TestCase class?
For the purposes of the database,
tearDownis pretty pointless, because each test is run in a transaction. However, not everything in a test involves the database. You might test file creation/reading, spin off processes, open network connections, etc. These types of things usually require you to “close” them after you’re done. This is whattearDownis for, i.e. cleaning up stuff from yoursetUpmethod, not related to the database. (Though, if you were actually directly connecting to a database, i.e. as the actual Django tests must do to make sure all the DBAPI stuff works properly, you’d need to do clean up there too.)