SimpleTestCase that tries to access the database?from django.test import SimpleTestCase from myapp.models import MyModel class MySimpleTest(SimpleTestCase): def test_db_access(self): count = MyModel.objects.count() self.assertEqual(count, 0)
SimpleTestCase does not set up or use the test database. Any database access inside it will raise an error.
Only TestCase sets up a test database and allows database queries.
TestCase class, what will be the count of MyModel objects in the second test method?from django.test import TestCase from myapp.models import MyModel class MyTest(TestCase): def test_create(self): MyModel.objects.create(name='test') self.assertEqual(MyModel.objects.count(), 1) def test_count(self): count = MyModel.objects.count() print(count)
Django's TestCase resets the test database after each test method, so the second test sees an empty database.
TestCase with a setup method that creates a model instance before each test?Django expects the setup method to be named exactly setUp with camel case.
Other variations like setup, SetUp, or set_up are ignored.
AttributeError: 'Client' object has no attribute 'login'?from django.test import SimpleTestCase class MySimpleTest(SimpleTestCase): def test_login(self): logged_in = self.client.login(username='user', password='pass') self.assertTrue(logged_in)
The login method requires database access to check user credentials.
SimpleTestCase does not set up the database, so login fails with AttributeError.
SimpleTestCase instead of TestCase in Django testing?SimpleTestCase is faster because it does not set up or use the test database.
It is suitable for tests that do not require database access.
