linqu
linqu

Reputation: 11980

raw sql queries in django unittests

I wrote some custom SQL select queries in my code - we are using postgresql. It turned out that my unittests area failing because the test database does not contain the actual data. To illustrate this fact I wrote this little test case:

from django.db import connection
from django.test import TestCase

from highlights.models import Feature


class TestRaw(TestCase):
    def setUp(self):
        Feature(username="me", feature=True).save()

    def test_raw(self):
        # this check passes
        self.assertEqual(1, Feature.objects.all().count())

        # raw queries do not, 1 != 0
        with connection.cursor() as c:
            c.execute("SELECT count(*) FROM highlights_flag")
            r = c.fetchone()
            self.assertEqual(1, r[0])

The raw sql query does not see the Feature object that was stored in the setUp method of the TestCase class. I also confirmed with psql that the test database is empty.

I presume django's test framework creates a new db transaction for every test case and rollbacks it when it is finished – just guessing though.

Do you have an idea how I can make my custom sql code testable. In other words: can I do something to let this test case work?

Thanks

Upvotes: 3

Views: 2594

Answers (1)

catavaran
catavaran

Reputation: 45585

You are selecting from highlights_flag table but the model is named Feature. May be you should change your query to:

SELECT count(*) FROM highlights_feature

Upvotes: 2

Related Questions