def test_nodb_cursor(self): """ The _nodb_cursor() fallbacks to the default connection database when access to the 'postgres' database is not granted. """ orig_connect = BaseDatabaseWrapper.connect def mocked_connect(self): if self.settings_dict["NAME"] is None: raise DatabaseError() return orig_connect(self) with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIsNone(cursor.db.settings_dict["NAME"]) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) # Now assume the 'postgres' db isn't available msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead.") with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with mock.patch.object( connection, "settings_dict", { **connection.settings_dict, "NAME": "postgres" }, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) self.assertIsNotNone(cursor.db.settings_dict["NAME"]) self.assertEqual(cursor.db.settings_dict["NAME"], connections["other"].settings_dict["NAME"]) # Cursor is yielded only for the first PostgreSQL database. with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection)
def restore_db(db_name): with connection._nodb_cursor() as cursor: close_active_connections(cursor, db_name) drop_database_if_exists(cursor, db_name) create_database(cursor, new_db=db_name, template_db=get_backup_db_name(db_name))
def save_db(db_name): db_name_backup = get_backup_db_name(db_name) # close my own active db connection to the database and get a connection to the dbms without selecting the db: db.connections.close_all() with connection._nodb_cursor() as cursor: close_active_connections(cursor, db_name) drop_database_if_exists(cursor, db_name_backup) create_database(cursor, new_db=db_name_backup, template_db=db_name)
def pytest_report_header(config): dot_version = ".".join(str(x) for x in django.VERSION) header = "Django version: " + dot_version with _blocking_manager.unblock(), connection._nodb_cursor() as cursor: cursor.execute("SELECT VERSION()") version = cursor.fetchone()[0] header += f"\nMySQL version: {version}" return header
def pytest_report_header(config): dot_version = ".".join(str(x) for x in django.VERSION) header = "Django version: " + dot_version with _blocking_manager.unblock(): if django.VERSION >= (3, 1): with connection._nodb_cursor() as cursor: cursor.execute("SELECT VERSION()") version = cursor.fetchone()[0] else: with closing(connection._nodb_connection) as conn: with conn.cursor() as cursor: cursor.execute("SELECT VERSION()") version = cursor.fetchone()[0] header += "\nMySQL version: {}".format(version) return header
def test_nodb_cursor_raises_postgres_authentication_failure(self): """ _nodb_cursor() re-raises authentication failure to the 'postgres' db when other connection to the PostgreSQL database isn't available. """ def mocked_connect(self): raise DatabaseError() def mocked_all(self): test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy( connection.settings_dict) test_connection.settings_dict['NAME'] = 'postgres' return [test_connection] msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead.") with self.assertWarnsMessage(RuntimeWarning, msg): mocker_connections_all = mock.patch( 'django.utils.connection.BaseConnectionHandler.all', side_effect=mocked_all, autospec=True, ) mocker_connect = mock.patch( 'django.db.backends.base.base.BaseDatabaseWrapper.connect', side_effect=mocked_connect, autospec=True, ) with mocker_connections_all, mocker_connect: with self.assertRaises(DatabaseError): with connection._nodb_cursor(): pass
def drop_and_create_db(db_name): db.connections.close_all() with connection._nodb_cursor() as cursor: close_active_connections(cursor, db_name) drop_database_if_exists(cursor, db_name) create_database(cursor, new_db=db_name)
text2 = SizedTextField(size_class=2) text3 = SizedTextField(size_class=3) text4 = SizedTextField(size_class=4) class Bit1Model(Model): flag_a = Bit1BooleanField(default=True) flag_b = Bit1BooleanField(default=False) class NullBit1Model(Model): flag = NullBit1BooleanField() if django.VERSION >= (3, 1): with connection._nodb_cursor() as cursor: supports_json_field = (not cursor.db.mysql_is_mariadb and cursor.db.mysql_version >= (5, 7)) else: nodb_conn = connection._nodb_connection try: supports_json_field = not connection_is_mariadb( nodb_conn) and nodb_conn.mysql_version >= (5, 7) finally: nodb_conn.close() class JSONModel(Model): # Something really weird and funky - change the fields on this model at # import time 😱 if supports_json_field:
def test_nodb_cursor_reraise_exceptions(self): with self.assertRaisesMessage(DatabaseError, "exception"): with connection._nodb_cursor(): raise DatabaseError("exception")