How do you run a raw SQL query inside a Django unittest?
I find if I use a cursor, it seems to break the unittest's transaction so that any changes to the Sqlite database aren't reverted at the end of the unittest.
My unittest looks like:
class Tests(TestCase):
def test_first(self):
print('FIRST:', MyModel.objects.all().count())
cursor = connection.cursor()
try:
cursor.execute('SELECT * FROM myapp_mymodel;')
r = cursor.fetchone()
finally:
cursor.close()
MyModel.objects.create(name='abc')
def test_second(self):
print('SECOND:', MyModel.objects.all().count())
and it currently outputs the unexpected:
FIRST: 0
SECOND: 1
and if I comment out the cursor code, then it outputs the correct result:
FIRST: 0
SECOND: 0
What black magic is going on here? Is connection.cursor
not support inside Django's special unittest transaction?