3

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.