Exemplo n.º 1
0
    def test_connect_isolation_level(self):
        read_committed = 'read committed'
        repeatable_read = 'repeatable read'
        isolation_values = {
            level: level.replace(' ', '-').upper()
            for level in (read_committed, repeatable_read)
        }
        configured_level = connection.isolation_level or isolation_values[repeatable_read]
        configured_level = configured_level.upper()
        other_level = read_committed if configured_level != isolation_values[read_committed] else repeatable_read

        self.assertEqual(self.get_isolation_level(connection), configured_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level
        try:
            self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level])
        finally:
            new_connection.close()

        # Upper case values are also accepted in 'isolation_level'.
        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level.upper()
        try:
            self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level])
        finally:
            new_connection.close()
Exemplo n.º 2
0
    def test_connect_isolation_level(self):
        read_committed = 'read committed'
        repeatable_read = 'repeatable read'
        isolation_values = {
            level: level.replace(' ', '-').upper()
            for level in (read_committed, repeatable_read)
        }
        configured_level = connection.isolation_level or isolation_values[
            repeatable_read]
        configured_level = configured_level.upper()
        other_level = read_committed if configured_level != isolation_values[
            read_committed] else repeatable_read

        self.assertEqual(self.get_isolation_level(connection),
                         configured_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS'][
            'isolation_level'] = other_level
        try:
            self.assertEqual(self.get_isolation_level(new_connection),
                             isolation_values[other_level])
        finally:
            new_connection.close()

        # Upper case values are also accepted in 'isolation_level'.
        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS'][
            'isolation_level'] = other_level.upper()
        try:
            self.assertEqual(self.get_isolation_level(new_connection),
                             isolation_values[other_level])
        finally:
            new_connection.close()
Exemplo n.º 3
0
    def test_connect_isolation_level(self):
        """
        Regression test for #18130 and #24318.
        """
        from psycopg2.extensions import (
            ISOLATION_LEVEL_READ_COMMITTED as read_committed,
            ISOLATION_LEVEL_SERIALIZABLE as serializable,
        )

        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.

        # Check the level on the psycopg2 connection, not the Django wrapper.
        self.assertEqual(connection.connection.isolation_level, read_committed)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level, serializable)
        finally:
            new_connection.close()
Exemplo n.º 4
0
    def test_connect_isolation_level(self):
        """
        The transaction level can be configured with
        DATABASES ['OPTIONS']['isolation_level'].
        """
        from psycopg2.extensions import (
            ISOLATION_LEVEL_SERIALIZABLE as serializable, )

        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.
        # Check the level on the psycopg2 connection, not the Django wrapper.
        self.assertIsNone(connection.connection.isolation_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS'][
            'isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level,
                             serializable)
        finally:
            new_connection.close()
Exemplo n.º 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).
        """
        new_connection = connection.copy()
        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.
            with new_connection.cursor() as 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)
                new_connection.rollback()

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

        finally:
            new_connection.close()
Exemplo n.º 6
0
    def test_connect_and_rollback(self):
        """
        PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
        transaction is rolled back (#17062).
        """
        new_connection = connection.copy()
        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.
            with new_connection.cursor() as 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)
                new_connection.rollback()

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

        finally:
            new_connection.close()
Exemplo n.º 7
0
    def test_queries_limit(self):
        """
        The backend doesn't store an unlimited number of queries (#12581).
        """
        old_queries_limit = BaseDatabaseWrapper.queries_limit
        BaseDatabaseWrapper.queries_limit = 3
        new_connection = connection.copy()

        # 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)

            msg = "Limit for query logging exceeded, only the last 3 queries will be returned."
            with self.assertWarnsMessage(UserWarning, msg):
                self.assertEqual(3, len(new_connection.queries))

        finally:
            BaseDatabaseWrapper.queries_limit = old_queries_limit
            new_connection.close()
Exemplo n.º 8
0
    def test_connect_isolation_level(self):
        """
        Regression test for #18130 and #24318.
        """
        import psycopg2
        from psycopg2.extensions import (
            ISOLATION_LEVEL_READ_COMMITTED as read_committed,
            ISOLATION_LEVEL_SERIALIZABLE as serializable,
        )

        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.

        # Check the level on the psycopg2 connection, not the Django wrapper.
        default_level = read_committed if psycopg2.__version__ < '2.7' else None
        self.assertEqual(connection.connection.isolation_level, default_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS'][
            'isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level,
                             serializable)
        finally:
            new_connection.close()
Exemplo n.º 9
0
    def test_queries_limit(self):
        """
        The backend doesn't store an unlimited number of queries (#12581).
        """
        old_queries_limit = BaseDatabaseWrapper.queries_limit
        BaseDatabaseWrapper.queries_limit = 3
        new_connection = connection.copy()

        # 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)

            msg = "Limit for query logging exceeded, only the last 3 queries will be returned."
            with self.assertWarnsMessage(UserWarning, msg):
                self.assertEqual(3, len(new_connection.queries))

        finally:
            BaseDatabaseWrapper.queries_limit = old_queries_limit
            new_connection.close()
Exemplo n.º 10
0
 def test_isolation_level_validation(self):
     new_connection = connection.copy()
     new_connection.settings_dict['OPTIONS']['isolation_level'] = 'xxx'
     msg = ("Invalid transaction isolation level 'xxx' specified.\n"
            "Use one of 'read committed', 'read uncommitted', "
            "'repeatable read', 'serializable', or None.")
     with self.assertRaisesMessage(ImproperlyConfigured, msg):
         new_connection.cursor()
Exemplo n.º 11
0
    def setUp(self):
        # This is executed in autocommit mode so that code in
        # run_select_for_update can see this data.
        self.person = Person.objects.create(name='Reinhardt')

        # We need another database connection in transaction to test that one
        # connection issuing a SELECT ... FOR UPDATE will block.
        self.new_connection = connection.copy()
Exemplo n.º 12
0
    def setUp(self):
        # This is executed in autocommit mode so that code in
        # run_select_for_update can see this data.
        self.person = Person.objects.create(name='Reinhardt')

        # We need another database connection in transaction to test that one
        # connection issuing a SELECT ... FOR UPDATE will block.
        self.new_connection = connection.copy()
Exemplo n.º 13
0
 def test_connect_no_is_usable_checks(self):
     new_connection = connection.copy()
     try:
         with mock.patch.object(new_connection, 'is_usable') as is_usable:
             new_connection.connect()
         is_usable.assert_not_called()
     finally:
         new_connection.close()
Exemplo n.º 14
0
 def test_isolation_level_validation(self):
     new_connection = connection.copy()
     new_connection.settings_dict['OPTIONS']['isolation_level'] = 'xxx'
     msg = (
         "Invalid transaction isolation level 'xxx' specified.\n"
         "Use one of 'read committed', 'read uncommitted', "
         "'repeatable read', 'serializable', or None."
     )
     with self.assertRaisesMessage(ImproperlyConfigured, msg):
         new_connection.cursor()
Exemplo n.º 15
0
    def setUp(self):
        # This is executed in autocommit mode so that code in
        # run_select_for_update can see this data.
        self.country1 = Country.objects.create(name='Belgium')
        self.country2 = Country.objects.create(name='France')
        self.city1 = City.objects.create(name='Liberchies', country=self.country1)
        self.city2 = City.objects.create(name='Samois-sur-Seine', country=self.country2)
        self.person = Person.objects.create(name='Reinhardt', born=self.city1, died=self.city2)

        # We need another database connection in transaction to test that one
        # connection issuing a SELECT ... FOR UPDATE will block.
        self.new_connection = connection.copy()
Exemplo n.º 16
0
    def setUp(self):
        # This is executed in autocommit mode so that code in
        # run_select_for_update can see this data.
        self.country1 = Country.objects.create(name='Belgium')
        self.country2 = Country.objects.create(name='France')
        self.city1 = City.objects.create(name='Liberchies', country=self.country1)
        self.city2 = City.objects.create(name='Samois-sur-Seine', country=self.country2)
        self.person = Person.objects.create(name='Reinhardt', born=self.city1, died=self.city2)
        self.person_profile = PersonProfile.objects.create(person=self.person)

        # We need another database connection in transaction to test that one
        # connection issuing a SELECT ... FOR UPDATE will block.
        self.new_connection = connection.copy()
Exemplo n.º 17
0
    def test_connect_non_autocommit(self):
        """
        The connection wrapper shouldn't believe that autocommit is enabled
        after setting the time zone when AUTOCOMMIT is False (#21452).
        """
        new_connection = connection.copy()
        new_connection.settings_dict['AUTOCOMMIT'] = False

        try:
            # Open a database connection.
            new_connection.cursor()
            self.assertFalse(new_connection.get_autocommit())
        finally:
            new_connection.close()
Exemplo n.º 18
0
    def test_connect_non_autocommit(self):
        """
        The connection wrapper shouldn't believe that autocommit is enabled
        after setting the time zone when AUTOCOMMIT is False (#21452).
        """
        new_connection = connection.copy()
        new_connection.settings_dict['AUTOCOMMIT'] = False

        try:
            # Open a database connection.
            new_connection.cursor()
            self.assertFalse(new_connection.get_autocommit())
        finally:
            new_connection.close()
Exemplo n.º 19
0
def get_connection():
    new_connection = connection.copy()
    yield new_connection
    new_connection.close()
Exemplo n.º 20
0
 def setUp(self):
     # Create a second connection to the default database
     self.conn2 = connection.copy()
     self.conn2.set_autocommit(False)
Exemplo n.º 21
0
 def test_connect_no_is_usable_checks(self):
     new_connection = connection.copy()
     with mock.patch.object(new_connection, 'is_usable') as is_usable:
         new_connection.connect()
     is_usable.assert_not_called()
Exemplo n.º 22
0
def get_connection():
    new_connection = connection.copy()
    yield new_connection
    new_connection.close()
Exemplo n.º 23
0
def connection():
    from django.db import connection
    new_connection = connection.copy()
    yield new_connection
    new_connection.close()
Exemplo n.º 24
0
Arquivo: tests.py Projeto: 01-/django
 def setUp(self):
     # Create a second connection to the default database
     self.conn2 = connection.copy()
     self.conn2.set_autocommit(False)
Exemplo n.º 25
0
 def test_get_database_version(self):
     new_connection = connection.copy()
     new_connection.pg_version = 110009
     self.assertEqual(new_connection.get_database_version(), (11, 9))