Django test. Looking for data from your production database while running tests?

The Django 1.5 doc on testing said:

Looking for data from your production database while running tests?

If your code tries to access the database when its modules are compiled , it will happen before the test database is created, with potentially unexpected results. For example, if you have a database query at the code unit level and a real database exists, production data can pollute your tests. It's a bad idea to have import-time database queries like this in your code anyway - rewrite your code so it doesn't.

Can someone explain the bold text that I am unable to understand. Thank.

+2


source to share


1 answer


You are reading this: http://djbook.ru/rel1.5/topics/testing/overview.html

It looks like one of those co-op online books that can contain awkward passages.

First, your settings file sets up the database:

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME':    'myDB' ...

      



When you run tests, the test runner reads that NAME, adds "test_" to get "test_myDB", and creates an empty database for tests to play with.

But the test runner only does this after the module is loaded (NOT "compiled"). So that...

from django.test import TestCase

# Don't use the database here; it still myDB

class SimpleTest(TestCase):

    def setUp(self):
           # We are all about the test_myDB database, here
        self.user = User.objects.create_user(
            username='zaphod',
            email='zaphod@...',
            password='beeblebrox',
        )

      

One more detail: unless you are crazy about developing and testing directly on your production server, myDB is NOT a "production database". The best name would be "development database".

+1


source







All Articles