Django test. Finding data from your production dat

2019-07-15 11:41发布

Django 1.5 document about testing said:

Finding data from your production database when running tests?

If your code attempts to access the database when its modules are compiled, this will occur before the test database is set up, with potentially unexpected results. For example, if you have a database query in module-level code and a real database exists, production data could pollute your tests. It is a bad idea to have such import-time database queries in your code anyway - rewrite your code so that it doesn’t do this.

Can someone explain bold text which i can't understand. Thank you.

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-15 12:30

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

That looks like one of those collaborative online books that might contain awkward passages.

Firstly, your settings file sets up a database:

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

When you run tests, the test runner reads that NAME, prepends "test_" to get "test_myDB", and creates a blank database for tests to play with.

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

from django.test import TestCase

# Don't use the database here; it's 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',
        )

Another detail: Unless you are insane, and are deving and testing directly on your production server, myDB is NOT the "production database." A better name would be the "development database."

查看更多
登录 后发表回答