Django测试.在运行测试时从生产数据库中查找数据? [英] Django test. Finding data from your production database when running tests?

查看:121
本文介绍了Django测试.在运行测试时从生产数据库中查找数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于测试的Django 1.5文档说:

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.

推荐答案

您正在阅读:这看起来像是其中可能包含尴尬段落的协作在线书之一.

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

运行测试时,测试运行程序读取NAME,在"test_"之前加上"test_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',
        )

另一个细节:除非您发疯,并且直接在生产服务器上进行开发和测试,否则myDB不是生产数据库".更好的名称是开发数据库".

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

这篇关于Django测试.在运行测试时从生产数据库中查找数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆