Django test. Finding data from your production database when running tests?

99封情书 提交于 2019-12-11 01:29:47

问题


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:


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."



来源:https://stackoverflow.com/questions/19714521/django-test-finding-data-from-your-production-database-when-running-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!