Beispiel #1
0
    def setUp(self):
        transaction.enter_transaction_management()
        self.person = Person.objects.create(name='Reinhardt')

        # We have to commit here so that code in run_select_for_update can
        # see this data.
        transaction.commit()

        # We need another database connection to test that one connection
        # issuing a SELECT ... FOR UPDATE will block.
        new_connections = ConnectionHandler(settings.DATABASES)
        self.new_connection = new_connections[DEFAULT_DB_ALIAS]
        self.new_connection.enter_transaction_management()

        # We need to set settings.DEBUG to True so we can capture
        # the output SQL to examine.
        self._old_debug = settings.DEBUG
        settings.DEBUG = True
Beispiel #2
0
    def test_queries_limit(self):
        """
        Test that the backend doesn't store an unlimited number of queries.

        Regression for #12581.
        """
        old_queries_limit = BaseDatabaseWrapper.queries_limit
        BaseDatabaseWrapper.queries_limit = 3
        new_connections = ConnectionHandler(settings.DATABASES)
        new_connection = new_connections[DEFAULT_DB_ALIAS]

        # Initialize the connection and clear initialization statements.
        with new_connection.cursor():
            pass
        new_connection.queries_log.clear()

        try:
            with new_connection.cursor() as cursor:
                cursor.execute("SELECT 1" +
                               new_connection.features.bare_select_suffix)
                cursor.execute("SELECT 2" +
                               new_connection.features.bare_select_suffix)

            with warnings.catch_warnings(record=True) as w:
                self.assertEqual(2, len(new_connection.queries))
                self.assertEqual(0, len(w))

            with new_connection.cursor() as cursor:
                cursor.execute("SELECT 3" +
                               new_connection.features.bare_select_suffix)
                cursor.execute("SELECT 4" +
                               new_connection.features.bare_select_suffix)

            with warnings.catch_warnings(record=True) as w:
                self.assertEqual(3, len(new_connection.queries))
                self.assertEqual(1, len(w))
                self.assertEqual(
                    str(w[0].message), "Limit for query logging "
                    "exceeded, only the last 3 queries will be returned.")

        finally:
            BaseDatabaseWrapper.queries_limit = old_queries_limit
            new_connection.close()
Beispiel #3
0
    def setup_databases(self, **kwargs):
        ###
        # WARNING: NOT handling 'TEST_MIRROR', 'TEST_DEPENDENCIES'
        ###

        # get new connections to test database
        test_connections = ConnectionHandler(settings.TEST_DATABASES)

        for alias in django.db.connections:
            test_connection = test_connections[alias]

            # set django-wide connection to use test connection
            django.db.connections[alias] = test_connection

            # re-initialize database (this "replaces" the CREATE DATABASE which
            # cannot be issued on Heroku)
            cursor = test_connection.cursor()
            cursor.execute('DROP SCHEMA public CASCADE')
            cursor.execute('CREATE SCHEMA public')

            # code below taken from
            # django.test.simple.DjangoTestSuiteRunner.setup_databases and
            # django.db.backends.creation.create_test_db

            # make them tables
            call_command('migrate',
                         verbosity=0,
                         interactive=False,
                         database=test_connection.alias)

            call_command('flush',
                         verbosity=0,
                         interactive=False,
                         database=test_connection.alias)

            from django.core.cache import caches
            from django.core.cache.backends.db import BaseDatabaseCache
            for cache_alias in settings.CACHES:
                cache = caches[cache_alias]
                if isinstance(cache, BaseDatabaseCache):
                    call_command('createcachetable',
                                 cache._table,
                                 database=test_connection.alias)
Beispiel #4
0
    def test_take_exclusive_lock(self):
        with Transaction():
            Dummy().save()

        with Transaction() as tran1:
            instance1 = Model.objects.filter(
                type__in=Dummy.types).order_by("-id").first()

        tran2 = Transaction()
        other_connection = ConnectionHandler()[DEFAULT_DB_ALIAS]
        assert tran1.connection != other_connection
        tran2.connection = other_connection
        with tran2:
            instance2 = Model.objects.filter(
                type__in=Dummy.types).order_by("-id").first()

        assert instance1 == instance2
        assert id(instance1) != id(instance2)

        with tran1:
            instance1.take_exclusive_lock()
Beispiel #5
0
    def test_connect_and_rollback(self):
        """
        PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
        transaction is rolled back (#17062).
        """
        databases = copy.deepcopy(settings.DATABASES)
        new_connections = ConnectionHandler(databases)
        new_connection = new_connections[DEFAULT_DB_ALIAS]

        try:
            # Ensure the database default time zone is different than
            # the time zone in new_connection.settings_dict. We can
            # get the default time zone by reset & show.
            cursor = new_connection.cursor()
            cursor.execute("RESET TIMEZONE")
            cursor.execute("SHOW TIMEZONE")
            db_default_tz = cursor.fetchone()[0]
            new_tz = 'Europe/Paris' if db_default_tz == 'UTC' else 'UTC'
            new_connection.close()

            # Invalidate timezone name cache, because the setting_changed
            # handler cannot know about new_connection.
            del new_connection.timezone_name

            # Fetch a new connection with the new_tz as default
            # time zone, run a query and rollback.
            with self.settings(TIME_ZONE=new_tz):
                new_connection.set_autocommit(False)
                cursor = new_connection.cursor()
                new_connection.rollback()

                # Now let's see if the rollback rolled back the SET TIME ZONE.
                cursor.execute("SHOW TIMEZONE")
                tz = cursor.fetchone()[0]
                self.assertEqual(new_tz, tz)

        finally:
            new_connection.close()
 def override_database_connections(databases):
     with mock.patch('analyticsdataserver.views.connections',
                     ConnectionHandler(databases)):
         yield
Beispiel #7
0
 def setUp(self):
     # Create a second connection to the default database
     new_connections = ConnectionHandler(settings.DATABASES)
     self.conn2 = new_connections[DEFAULT_DB_ALIAS]
     self.conn2.set_autocommit(False)
Beispiel #8
0
 def setUp(self):
     super(DBTestSettingsRenamedTests, self).setUp()
     self.handler = ConnectionHandler()
     self.db_settings = {'default': {}}
Beispiel #9
0
 def setUp(self):
     super(DBTestSettingsRenamedTests, self).setUp()
     self.handler = ConnectionHandler()
     self.db_settings = {'default': {}}
Beispiel #10
0
from io import StringIO
from unittest import mock

import pytest
from django.core.management import CommandError, call_command
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase

# Can't use @override_settings to swap out DATABASES, instead just mock.patch
# a new ConnectionHandler into the command module
command_connections = "django_mysql.management.commands.dbparams.connections"

sqlite = ConnectionHandler(
    {"default": {
        "ENGINE": "django.db.backends.sqlite3"
    }})

full_db = ConnectionHandler({
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "mydatabase",
        "USER": "******",
        "PASSWORD": "******",
        "HOST": "ahost.example.com",
        "PORT": "12345",
        "OPTIONS": {
            "read_default_file": "/tmp/defaults.cnf",
            "ssl": {
                "ca": "/tmp/mysql.cert"
            },
        },
Beispiel #11
0
 def setUp(self):
     self.handler = ConnectionHandler()
     self.db_settings = {'default': {}}
Beispiel #12
0
from django.core.management import CommandError, call_command
from django.db import connection
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase, TestCase, TransactionTestCase

from django_mysql.management.commands.fix_datetime_columns import parse_create_table
from django_mysql.utils import connection_is_mariadb

# Can't use @override_settings to swap out DATABASES, instead just mock.patch
# a new ConnectionHandler into the command module

command_connections = (
    "django_mysql.management.commands.fix_datetime_columns.connections")

sqlite = ConnectionHandler(
    {"default": {
        "ENGINE": "django.db.backends.sqlite3"
    }})


def run_it(*args, **kwargs):
    run_args = ["fix_datetime_columns"]
    run_args.extend(args)

    out = StringIO()
    run_kwargs = {"stdout": out, "skip_checks": True}
    run_kwargs.update(kwargs)

    call_command(*run_args, **run_kwargs)

    return out.getvalue()
Beispiel #13
0
from django.core import exceptions
from django.db.models.fields.related import ForeignKey
from django.db.utils import ConnectionHandler, ConnectionRouter
#from django.db.models import ForeignKey
connection = ConnectionHandler()
router = ConnectionRouter()

class SpanningForeignKey(ForeignKey):
def validate(self, value, model_instance):
if self.remote_field.parent_link:
  return
  # Call the grandparent rather than the parent to skip validation
  super(ForeignKey, self).validate(value, model_instance)

   if value is None:
        return
    using = router.db_for_read(self.remote_field.model, instance=model_instance)
    qs = self.remote_field.model._default_manager.using(using).filter(
        **{self.remote_field.field_name: value}
    )

    qs = qs.complex_filter(self.get_limit_choices_to())
   
   if not qs.exists():
        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={
                'model': self.remote_field.model._meta.verbose_name, 
                'pk': value,
                'field': self.remote_field.field_name, 'value': value,
Beispiel #14
0
def reload_settings(settings, databases=None):
    """Special routine to reload django settings.

    Including:
    urlconf module, context processor, templatetags settings, database settings.
    """
    if databases:
        settings.DATABASES.update(databases)

    # check if there's settings to reload
    if hasattr(settings, 'ROOT_URLCONF'):
        if settings.ROOT_URLCONF in sys.modules:
            imp.reload(sys.modules[settings.ROOT_URLCONF])
        import django
        if hasattr(django, 'setup'):
            django.setup()
        import_module(settings.ROOT_URLCONF)
        set_urlconf(settings.ROOT_URLCONF)
        settings.LANGUAGE_CODE = 'en'  # all tests should be run with English by default

        # Make the ConnectionHandler use the new settings, otherwise the ConnectionHandler will have old configuraton.
        from django.db.utils import ConnectionHandler
        import django.db
        from django.db.utils import load_backend
        import django.db.transaction
        import django.db.models
        import django.db.models.sql.query
        import django.core.management.commands.syncdb
        import django.db.models.sql.compiler
        import django.db.backends
        import django.db.backends.mysql.base
        import django.core.management.commands.loaddata

        # all modules which imported django.db.connections should be changed to get new ConnectionHanlder
        django.db.models.sql.compiler.connections = django.db.models.connections = \
            django.core.management.commands.loaddata.connections = \
            django.db.backends.connections = django.db.backends.mysql.base.connections = \
            django.core.management.commands.syncdb.connections = django.db.transaction.connections = \
            django.db.connections = django.db.models.base.connections = django.db.models.sql.query.connections = \
            ConnectionHandler(settings.DATABASES)

        # default django connection and backend should be also changed
        django.db.connection = django.db.connections[django.db.DEFAULT_DB_ALIAS]
        django.db.backend = load_backend(django.db.connection.settings_dict['ENGINE'])

        import django.core.cache
        django.core.cache.cache = django.core.cache.get_cache(django.core.cache.DEFAULT_CACHE_ALIAS)

        # clear django urls cache
        clear_url_caches()
        # clear django contextprocessors cache
        context._standard_context_processors = None
        # clear django templatetags cache
        base.templatetags_modules = None

        # reload translation files
        imp.reload(translation)
        imp.reload(trans_real)

        # clear django template loaders cache
        loader.template_source_loaders = None
        from django.template.loaders import app_directories
        imp.reload(app_directories)
    def handle_inspection(self, options):
        dbs = copy.copy(settings.DATABASES)
        dbs['brapischemadbfile'] = {'ENGINE': 'django.db.backends.sqlite3',
                                    'NAME': options['dbfile']}
        conns = ConnectionHandler(dbs)
        connection = conns['brapischemadbfile']

        # connection = connections[options['database']]
        # 'table_name_filter' is a stealth option
        table_name_filter = options.get('table_name_filter')

        def table2model(table_name):
            return re.sub(r'[^a-zA-Z0-9]', '', table_name.title())

        def strip_prefix(s):
            return s[1:] if s.startswith("u'") else s

        with connection.cursor() as cursor:
            yield "# This is an auto-generated Django model module."
            yield "# You'll have to do the following manually to clean this up:"
            yield "#   * Rearrange models' order"
            yield "#   * Make sure each model has one field with primary_key=True"
            yield "#   * Make sure each ForeignKey has `on_delete` set to the desired behavior."
            yield (
                "#   * Remove `managed = False` lines if you wish to allow "
                "Django to create, modify, and delete the table"
            )
            yield "# Feel free to rename the models, but don't rename db_table values or field names."
            yield "from __future__ import unicode_literals"
            yield ''
            yield 'from %s import models' % self.db_module
            known_models = []
            tables_to_introspect = options['table'] or connection.introspection.table_names(cursor)

            for table_name in tables_to_introspect:
                if table_name_filter is not None and callable(table_name_filter):
                    if not table_name_filter(table_name):
                        continue
                try:
                    try:
                        relations = connection.introspection.get_relations(cursor, table_name)
                    except NotImplementedError:
                        relations = {}
                    try:
                        constraints = connection.introspection.get_constraints(cursor, table_name)
                    except NotImplementedError:
                        constraints = {}
                    primary_key_column = connection.introspection.get_primary_key_column(cursor, table_name)
                    unique_columns = [
                        c['columns'][0] for c in constraints.values()
                        if c['unique'] and len(c['columns']) == 1
                    ]
                    table_description = connection.introspection.get_table_description(cursor, table_name)
                except Exception as e:
                    yield "# Unable to inspect table '%s'" % table_name
                    yield "# The error was: %s" % force_text(e)
                    continue

                yield ''
                yield ''
                yield 'class %s(models.Model):' % table2model(table_name)
                known_models.append(table2model(table_name))
                used_column_names = []  # Holds column names used in the table so far
                column_to_field_name = {}  # Maps column names to names of model fields
                for row in table_description:
                    comment_notes = []  # Holds Field notes, to be displayed in a Python comment.
                    extra_params = OrderedDict()  # Holds Field parameters such as 'db_column'.
                    column_name = row[0]
                    is_relation = column_name in relations

                    att_name, params, notes = self.normalize_col_name(
                        column_name, used_column_names, is_relation)
                    extra_params.update(params)
                    comment_notes.extend(notes)

                    used_column_names.append(att_name)
                    column_to_field_name[column_name] = att_name

                    # Add primary_key and unique, if necessary.
                    # print (('------>', column_name, primary_key_column))
                    if column_name == primary_key_column or ('dbid' in column_name.lower() and column_name.lower().replace('dbid', '') == table_name.lower()) or column_name == 'id':
                        extra_params['primary_key'] = True
                        # extra_params['unique'] = True
                        # extra_params['blank'] = True
                        # print (('--->',column_name))
                    elif column_name in unique_columns:
                        extra_params['unique'] = True

                    if is_relation:
                        rel_to = (
                            "self" if relations[column_name][1] == table_name
                            else table2model(relations[column_name][1])
                        )
                        if rel_to in known_models:
                            field_type = "ForeignKey('%s', on_delete=models.CASCADE" % rel_to
                        else:
                            field_type = "ForeignKey('%s', on_delete=models.CASCADE" % rel_to
                    else:
                        # Calling `get_field_type` to get the field type string and any
                        # additional parameters and notes.
                        field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
                        extra_params.update(field_params)
                        comment_notes.extend(field_notes)

                        field_type += '('

                    # Don't output 'id = meta.AutoField(primary_key=True)', because
                    # that's assumed if it doesn't exist.
                    if att_name == 'id' and extra_params == {'primary_key': True}:
                        if field_type == 'AutoField(':
                            continue
                        elif field_type == 'IntegerField(' and not connection.features.can_introspect_autofield:
                            comment_notes.append('AutoField?')

                    # Add 'null' and 'blank', if the 'null_ok' flag was present in the
                    # table description.
                    if row[6]:  # If it's NULL...
                        if field_type == 'BooleanField(':
                            field_type = 'NullBooleanField('
                        else:
                            if not field_type.startswith('ForeignKey'):
                                extra_params['blank'] = True
                            # extra_params['null'] = True

                    field_desc = '%s = %s%s' % (
                        att_name,
                        # Custom fields will have a dotted path
                        '' if '.' in field_type else 'models.',
                        field_type,
                    )
                    # if field_type.startswith('ForeignKey('):
                    #     field_desc += ', models.DO_NOTHING'
                    extra_params['verbose_name'] = ' ' + column_name  # add one initial space to avoid capitalization in admin UI

                    if extra_params:
                        if not field_desc.endswith('('):
                            field_desc += ', '
                        field_desc += ', '.join(
                            '%s=%s' % (k, strip_prefix(repr(v)))
                            for k, v in extra_params.items())
                    field_desc += ')'
                    if comment_notes:
                        field_desc += '  # ' + ' '.join(comment_notes)
                    yield '    %s' % field_desc
                for meta_line in self.get_meta(table_name, constraints, column_to_field_name):
                    yield meta_line
import mock
from unittest import skipIf

import django
import pytest
from django.core.management import CommandError, call_command
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase
from django.utils.six.moves import StringIO

# Can't use @override_settings to swap out DATABASES, instead just mock.patch
# a new ConnectionHandler into the command module
command_connections = 'django_mysql.management.commands.dbparams.connections'

sqlite = ConnectionHandler(
    {'default': {
        'ENGINE': 'django.db.backends.sqlite3'
    }})

full_db = ConnectionHandler({
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': '******',
        'PASSWORD': '******',
        'HOST': 'ahost.example.com',
        'PORT': '12345',
        'OPTIONS': {
            'read_default_file': '/tmp/defaults.cnf',
            'ssl': {
                'ca': '/tmp/mysql.cert'
            }
Beispiel #17
0
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase, TestCase, TransactionTestCase
from django.utils.six.moves import StringIO

from django_mysql.management.commands.fix_datetime_columns import \
    parse_create_table

# Can't use @override_settings to swap out DATABASES, instead just mock.patch
# a new ConnectionHandler into the command module

command_connections = (
    'django_mysql.management.commands.fix_datetime_columns.connections'
)

sqlite = ConnectionHandler({
    'default': {'ENGINE': 'django.db.backends.sqlite3'}
})


def run_it(*args, **kwargs):
    run_args = ['fix_datetime_columns']
    run_args.extend(args)

    out = StringIO()
    run_kwargs = {'stdout': out, 'skip_checks': True}
    run_kwargs.update(kwargs)

    call_command(*run_args, **run_kwargs)

    return out.getvalue()
Beispiel #18
0
class DBTestSettingsRenamedTests(IgnoreAllDeprecationWarningsMixin, TestCase):

    mismatch_msg = ("Connection 'test-deprecation' has mismatched TEST "
                    "and TEST_* database settings.")

    @classmethod
    def setUpClass(cls):
        # Silence "UserWarning: Overriding setting DATABASES can lead to
        # unexpected behavior."
        cls.warning_classes.append(UserWarning)

    def setUp(self):
        super(DBTestSettingsRenamedTests, self).setUp()
        self.handler = ConnectionHandler()
        self.db_settings = {'default': {}}

    def test_mismatched_database_test_settings_1(self):
        # if the TEST setting is used, all TEST_* keys must appear in it.
        self.db_settings.update(
            {'test-deprecation': {
                'TEST': {},
                'TEST_NAME': 'foo',
            }})
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured,
                                          self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_2(self):
        # if the TEST setting is used, all TEST_* keys must match.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {
                    'NAME': 'foo'
                },
                'TEST_NAME': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured,
                                          self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_3(self):
        # Verifies the mapping of an aliased key.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {
                    'CREATE_DB': 'foo'
                },
                'TEST_CREATE': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured,
                                          self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_4(self):
        # Verifies the mapping of an aliased key when the aliased key is missing.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_CREATE': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured,
                                          self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_settings_old_none(self):
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {
                    'CREATE_DB': None
                },
                'TEST_CREATE': '',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured,
                                          self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_settings_new_none(self):
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_CREATE': None,
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured,
                                          self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_matched_test_settings(self):
        # should be able to define new settings and the old, if they match
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {
                    'NAME': 'foo'
                },
                'TEST_NAME': 'foo',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_new_settings_only(self):
        # should be able to define new settings without the old
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {
                    'NAME': 'foo'
                },
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_old_settings_only(self):
        # should be able to define old settings without the new
        self.db_settings.update({
            'test-deprecation': {
                'TEST_NAME': 'foo',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_empty_settings(self):
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('default')
Beispiel #19
0
class DBTestSettingsRenamedTests(IgnoreAllDeprecationWarningsMixin, TestCase):

    mismatch_msg = ("Connection 'test-deprecation' has mismatched TEST "
                    "and TEST_* database settings.")

    @classmethod
    def setUpClass(cls):
        super(DBTestSettingsRenamedTests, cls).setUpClass()
        # Silence "UserWarning: Overriding setting DATABASES can lead to
        # unexpected behavior."
        cls.warning_classes.append(UserWarning)

    def setUp(self):
        super(DBTestSettingsRenamedTests, self).setUp()
        self.handler = ConnectionHandler()
        self.db_settings = {'default': {}}

    def test_mismatched_database_test_settings_1(self):
        # if the TEST setting is used, all TEST_* keys must appear in it.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_NAME': 'foo',
            }
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_2(self):
        # if the TEST setting is used, all TEST_* keys must match.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'NAME': 'foo'},
                'TEST_NAME': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_3(self):
        # Verifies the mapping of an aliased key.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'CREATE_DB': 'foo'},
                'TEST_CREATE': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_4(self):
        # Verifies the mapping of an aliased key when the aliased key is missing.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_CREATE': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_settings_old_none(self):
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'CREATE_DB': None},
                'TEST_CREATE': '',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_settings_new_none(self):
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_CREATE': None,
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_matched_test_settings(self):
        # should be able to define new settings and the old, if they match
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'NAME': 'foo'},
                'TEST_NAME': 'foo',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_new_settings_only(self):
        # should be able to define new settings without the old
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'NAME': 'foo'},
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_old_settings_only(self):
        # should be able to define old settings without the new
        self.db_settings.update({
            'test-deprecation': {
                'TEST_NAME': 'foo',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_empty_settings(self):
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('default')
Beispiel #20
0
from django_evolution.compat.db import (atomic, create_index_name,
                                        create_index_together_name, digest,
                                        sql_create, sql_delete, truncate_name)
from django_evolution.compat.models import (all_models,
                                            get_model_name,
                                            get_remote_field,
                                            get_remote_field_model,
                                            set_model_name)
from django_evolution.db import EvolutionOperationsMulti
from django_evolution.signature import (AppSignature, ModelSignature,
                                        ProjectSignature)
from django_evolution.tests import models as evo_test
from django_evolution.utils import execute_sql, write_sql


test_connections = ConnectionHandler(settings.TEST_DATABASES)


def register_models(database_state, models, register_indexes=False,
                    new_app_label='tests', db_name='default', app=evo_test):
    """Register models for testing purposes.

    Args:
        database_state (django_evolution.db.state.DatabaseState):
            The database state to populate with model information.

        models (list of django.db.models.Model):
            The models to register.

        register_indexes (bool, optional):
            Whether indexes should be registered for any models. Defaults to
            if database['ENGINE'] == 'postgresql_psycopg2':
                full_engine = 'django.contrib.gis.db.backends.postgis'
            elif database['ENGINE'] == 'sqlite3':
                full_engine = 'django.contrib.gis.db.backends.spatialite'
            else:
                full_engine = 'django.contrib.gis.db.backends.%s' % database[
                    'ENGINE']
        else:
            warnings.warn(
                "Short names for ENGINE in database configurations are deprecated. "
                "Prepend %s.ENGINE with 'django.db.backends.'" % alias,
                DeprecationWarning)
            full_engine = "django.db.backends.%s" % database['ENGINE']
        database['ENGINE'] = full_engine

connections = ConnectionHandler(settings.DATABASES)

router = ConnectionRouter(settings.DATABASE_ROUTERS)

# `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
# for backend bits.

# DatabaseWrapper.__init__() takes a dictionary, not a settings module, so
# we manually create the dictionary from the settings, passing only the
# settings that the database backends care about. Note that TIME_ZONE is used
# by the PostgreSQL backends.
# we load all these up for backwards compatibility, you should use
# connections['default'] instead.
connection = connections[DEFAULT_DB_ALIAS]
backend = load_backend(connection.settings_dict['ENGINE'])
Beispiel #22
0
 def test_no_default_database(self):
     DATABASES = {'other': {}}
     conns = ConnectionHandler(DATABASES)
     msg = "You must define a 'default' database."
     with self.assertRaisesMessage(ImproperlyConfigured, msg):
         conns['other'].ensure_connection()
Beispiel #23
0
    InterfaceError,
    InternalError,
    NotSupportedError,
    OperationalError,
    ProgrammingError,
)

__all__ = [
    'backend', 'connection', 'connections', 'router', 'DatabaseError',
    'IntegrityError', 'InternalError', 'ProgrammingError', 'DataError',
    'NotSupportedError', 'Error', 'InterfaceError', 'OperationalError',
    'DEFAULT_DB_ALIAS', 'DJANGO_VERSION_PICKLE_KEY'
]

# 管理各种alias的请求
connections = ConnectionHandler()

# 路由
router = ConnectionRouter()

# `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
# for backend bits.


# DatabaseWrapper.__init__() takes a dictionary, not a settings module, so we
# manually create the dictionary from the settings, passing only the settings
# that the database backends care about.
# We load all these up for backwards compatibility, you should use
# connections['default'] instead.
class DefaultConnectionProxy(object):
    """
Beispiel #24
0
class DBTestSettingsRenamedTests(TestCase):

    mismatch_msg = ("Connection 'test-deprecation' has mismatched TEST "
                    "and TEST_* database settings.")

    def setUp(self):
        super(DBTestSettingsRenamedTests, self).setUp()
        self.handler = ConnectionHandler()
        self.db_settings = {'default': {}}

    def test_mismatched_database_test_settings_1(self):
        # if the TEST setting is used, all TEST_* keys must appear in it.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_NAME': 'foo',
            }
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_2(self):
        # if the TEST setting is used, all TEST_* keys must match.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'NAME': 'foo'},
                'TEST_NAME': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_3(self):
        # Verifies the mapping of an aliased key.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'CREATE_DB': 'foo'},
                'TEST_CREATE': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_database_test_settings_4(self):
        # Verifies the mapping of an aliased key when the aliased key is missing.
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_CREATE': 'bar',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_settings_old_none(self):
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'CREATE_DB': None},
                'TEST_CREATE': '',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_mismatched_settings_new_none(self):
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {},
                'TEST_CREATE': None,
            },
        })
        with override_settings(DATABASES=self.db_settings):
            with self.assertRaisesMessage(ImproperlyConfigured, self.mismatch_msg):
                self.handler.prepare_test_settings('test-deprecation')

    def test_matched_test_settings(self):
        # should be able to define new settings and the old, if they match
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'NAME': 'foo'},
                'TEST_NAME': 'foo',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_new_settings_only(self):
        # should be able to define new settings without the old
        self.db_settings.update({
            'test-deprecation': {
                'TEST': {'NAME': 'foo'},
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    @ignore_warnings(category=RemovedInDjango19Warning)
    def test_old_settings_only(self):
        # should be able to define old settings without the new
        self.db_settings.update({
            'test-deprecation': {
                'TEST_NAME': 'foo',
            },
        })
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('test-deprecation')

    def test_empty_settings(self):
        with override_settings(DATABASES=self.db_settings):
            self.handler.prepare_test_settings('default')