Fixed SonarQube Bugs and API test cases.

This commit is contained in:
Akshay Joshi 2024-01-25 12:46:55 +05:30
parent d55c35c0e8
commit cafe69c235
8 changed files with 62 additions and 63 deletions

View File

@ -13,7 +13,7 @@ from functools import wraps
import json import json
from flask import render_template, make_response, request, jsonify from flask import render_template, make_response, request, jsonify
from flask_babel import gettext as _ from flask_babel import gettext
import pgadmin.browser.server_groups.servers.databases as database import pgadmin.browser.server_groups.servers.databases as database
from config import PG_DEFAULT_DRIVER from config import PG_DEFAULT_DRIVER
@ -54,7 +54,7 @@ class PackageModule(SchemaChildModule):
""" """
_NODE_TYPE = 'package' _NODE_TYPE = 'package'
_COLLECTION_LABEL = _("Packages") _COLLECTION_LABEL = gettext("Packages")
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
@ -152,7 +152,7 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
# If DB not connected then return error to browser # If DB not connected then return error to browser
if not self.conn.connected(): if not self.conn.connected():
return precondition_required( return precondition_required(
_( gettext(
"Connection to the server has been lost." "Connection to the server has been lost."
) )
) )
@ -399,7 +399,7 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
return make_json_response( return make_json_response(
status=400, status=400,
success=0, success=0,
errormsg=_( errormsg=gettext(
"Could not find the required parameter ({})." "Could not find the required parameter ({})."
).format(arg) ).format(arg)
) )
@ -475,7 +475,7 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
elif not res['rows']: elif not res['rows']:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_( errormsg=gettext(
'Error: Object not found.' 'Error: Object not found.'
), ),
info=self.not_found_error_msg() info=self.not_found_error_msg()
@ -497,7 +497,7 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
return make_json_response( return make_json_response(
success=1, success=1,
info=_("Package dropped") info=gettext("Package dropped")
) )
except Exception as e: except Exception as e:
@ -577,7 +577,7 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
return make_json_response( return make_json_response(
status=400, status=400,
success=0, success=0,
errormsg=_( errormsg=gettext(
"Could not find the required parameter ({})." "Could not find the required parameter ({})."
).format(arg) ).format(arg)
) )

View File

@ -10,7 +10,7 @@
""" Implements Utility class for Compound Triggers. """ """ Implements Utility class for Compound Triggers. """
from flask import render_template from flask import render_template
from flask_babel import gettext as _ from flask_babel import gettext
from pgadmin.utils.ajax import internal_server_error from pgadmin.utils.ajax import internal_server_error
from pgadmin.utils.exception import ObjectGone, ExecuteError from pgadmin.utils.exception import ObjectGone, ExecuteError
from pgadmin.browser.server_groups.servers.databases.schemas.utils \ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
@ -108,7 +108,7 @@ def get_sql(conn, data, tid, trid, datlastsysoid, template_path=None):
raise ExecuteError(res) raise ExecuteError(res)
elif len(res['rows']) == 0: elif len(res['rows']) == 0:
raise ObjectGone( raise ObjectGone(
_('Could not find the compound trigger in the table.')) gettext('Could not find the compound trigger in the table.'))
old_data = dict(res['rows'][0]) old_data = dict(res['rows'][0])
# If name is not present in data then # If name is not present in data then
@ -133,7 +133,7 @@ def get_sql(conn, data, tid, trid, datlastsysoid, template_path=None):
for arg in required_args: for arg in required_args:
if arg not in data: if arg not in data:
return _('-- definition incomplete') return gettext('-- definition incomplete')
# If the request for new object which do not have did # If the request for new object which do not have did
SQL = render_template("/".join([template_path, 'create.sql']), SQL = render_template("/".join([template_path, 'create.sql']),
@ -166,7 +166,7 @@ def get_reverse_engineered_sql(conn, **kwargs):
if len(res['rows']) == 0: if len(res['rows']) == 0:
raise ObjectGone( raise ObjectGone(
_('Could not find the compound trigger in the table.')) gettext('Could not find the compound trigger in the table.'))
data = dict(res['rows'][0]) data = dict(res['rows'][0])
# Adding parent into data dict, will be using it while creating sql # Adding parent into data dict, will be using it while creating sql

View File

@ -14,7 +14,7 @@ from functools import wraps
import pgadmin.browser.server_groups.servers.databases as database import pgadmin.browser.server_groups.servers.databases as database
from flask import render_template, make_response, request, jsonify from flask import render_template, make_response, request, jsonify
from flask_babel import gettext as _ from flask_babel import gettext
from pgadmin.browser.collection import CollectionNodeModule from pgadmin.browser.collection import CollectionNodeModule
from pgadmin.browser.server_groups.servers.databases.schemas.tables.\ from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
constraints.type import ConstraintRegistry constraints.type import ConstraintRegistry
@ -49,7 +49,7 @@ class CheckConstraintModule(CollectionNodeModule):
Check node is initialized. Check node is initialized.
""" """
_NODE_TYPE = 'check_constraint' _NODE_TYPE = 'check_constraint'
_COLLECTION_LABEL = _("Check Constraints") _COLLECTION_LABEL = gettext("Check Constraints")
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
@ -306,7 +306,7 @@ class CheckConstraintView(PGChildNodeView):
_, rset = self.conn.execute_2darray(SQL) _, rset = self.conn.execute_2darray(SQL)
if len(rset['rows']) == 0: if len(rset['rows']) == 0:
return gone(_("""Could not find the check constraint.""")) return gone(gettext("""Could not find the check constraint."""))
if "convalidated" in rset['rows'][0] and \ if "convalidated" in rset['rows'][0] and \
rset['rows'][0]["convalidated"]: rset['rows'][0]["convalidated"]:
@ -437,7 +437,7 @@ class CheckConstraintView(PGChildNodeView):
return res return res
if len(res) == 0: if len(res) == 0:
return gone(_( return gone(gettext(
"""Could not find the check constraint in the table.""" """Could not find the check constraint in the table."""
)) ))
@ -481,7 +481,7 @@ class CheckConstraintView(PGChildNodeView):
return True, make_json_response( return True, make_json_response(
status=400, status=400,
success=0, success=0,
errormsg=_( errormsg=gettext(
"Could not find the required parameter ({})." "Could not find the required parameter ({})."
).format(arg), ).format(arg),
), data ), data
@ -527,7 +527,7 @@ class CheckConstraintView(PGChildNodeView):
data['table'] = self.table data['table'] = self.table
# Checking whether the table is deleted via query tool # Checking whether the table is deleted via query tool
if len(data['table']) == 0: if len(data['table']) == 0:
return gone(_(self.not_found_error_msg('Table'))) return gone(gettext(self.not_found_error_msg('Table')))
try: try:
if 'name' not in data or data['name'] == "": if 'name' not in data or data['name'] == "":
@ -630,10 +630,10 @@ class CheckConstraintView(PGChildNodeView):
if not res['rows']: if not res['rows']:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_( errormsg=gettext(
'Error: Object not found.' 'Error: Object not found.'
), ),
info=_( info=gettext(
'The specified check constraint ' 'The specified check constraint '
'could not be found.\n' 'could not be found.\n'
) )
@ -650,7 +650,7 @@ class CheckConstraintView(PGChildNodeView):
return make_json_response( return make_json_response(
success=1, success=1,
info=_("Check constraint dropped.") info=gettext("Check constraint dropped.")
) )
except Exception as e: except Exception as e:
@ -739,7 +739,7 @@ class CheckConstraintView(PGChildNodeView):
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
return gone( return gone(
_("Could not find the object on the server.") gettext("Could not find the object on the server.")
) )
data = res['rows'][0] data = res['rows'][0]
@ -880,7 +880,7 @@ class CheckConstraintView(PGChildNodeView):
return make_json_response( return make_json_response(
success=1, success=1,
info=_("Check constraint updated."), info=gettext("Check constraint updated."),
data={ data={
'id': cid, 'id': cid,
'tid': tid, 'tid': tid,

View File

@ -14,7 +14,7 @@ from functools import wraps
import pgadmin.browser.server_groups.servers.databases as database import pgadmin.browser.server_groups.servers.databases as database
from flask import render_template, make_response, request, jsonify from flask import render_template, make_response, request, jsonify
from flask_babel import gettext as _ from flask_babel import gettext
from pgadmin.browser.server_groups.servers.databases.schemas.tables.\ from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
constraints.type import ConstraintRegistry, ConstraintTypeModule constraints.type import ConstraintRegistry, ConstraintTypeModule
from pgadmin.browser.utils import PGChildNodeView from pgadmin.browser.utils import PGChildNodeView
@ -51,7 +51,7 @@ class ExclusionConstraintModule(ConstraintTypeModule):
""" """
_NODE_TYPE = 'exclusion_constraint' _NODE_TYPE = 'exclusion_constraint'
_COLLECTION_LABEL = _("Exclusion Constraints") _COLLECTION_LABEL = gettext("Exclusion Constraints")
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
""" """
@ -272,7 +272,7 @@ class ExclusionConstraintView(PGChildNodeView):
return res return res
if len(res) == 0: if len(res) == 0:
return gone(_( return gone(gettext(
"""Could not find the exclusion constraint in the table.""" """Could not find the exclusion constraint in the table."""
)) ))
@ -377,7 +377,7 @@ class ExclusionConstraintView(PGChildNodeView):
_, rset = self.conn.execute_2darray(SQL) _, rset = self.conn.execute_2darray(SQL)
if len(rset['rows']) == 0: if len(rset['rows']) == 0:
return gone(_("""Could not find the exclusion constraint.""")) return gone(gettext("""Could not find the exclusion constraint."""))
res = self.blueprint.generate_browser_node( res = self.blueprint.generate_browser_node(
rset['rows'][0]['oid'], rset['rows'][0]['oid'],
@ -529,7 +529,7 @@ class ExclusionConstraintView(PGChildNodeView):
return make_json_response( return make_json_response(
status=400, status=400,
success=0, success=0,
errormsg=_( errormsg=gettext(
"Could not find required parameter ({})." "Could not find required parameter ({})."
).format(arg_missing) ).format(arg_missing)
) )
@ -695,10 +695,10 @@ class ExclusionConstraintView(PGChildNodeView):
if not res['rows']: if not res['rows']:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_( errormsg=gettext(
'Error: Object not found.' 'Error: Object not found.'
), ),
info=_( info=gettext(
'The specified exclusion constraint could not ' 'The specified exclusion constraint could not '
'be found.\n' 'be found.\n'
) )
@ -718,7 +718,7 @@ class ExclusionConstraintView(PGChildNodeView):
return make_json_response( return make_json_response(
success=1, success=1,
info=_("Exclusion constraint dropped.") info=gettext("Exclusion constraint dropped.")
) )
except Exception as e: except Exception as e:
@ -795,7 +795,7 @@ class ExclusionConstraintView(PGChildNodeView):
if not status: if not status:
return rows return rows
if len(rows) == 0: if len(rows) == 0:
return gone(_("Could not find the exclusion constraint.")) return gone(gettext("Could not find the exclusion constraint."))
data = rows[0] data = rows[0]
data['schema'] = self.schema data['schema'] = self.schema
@ -854,7 +854,7 @@ class ExclusionConstraintView(PGChildNodeView):
if not status: if not status:
return internal_server_error(errormsg=result) return internal_server_error(errormsg=result)
if len(result['rows']) == 0: if len(result['rows']) == 0:
return gone(_("Could not find the exclusion constraint.")) return gone(gettext("Could not find the exclusion constraint."))
data = result['rows'][0] data = result['rows'][0]
name = data['name'] name = data['name']

View File

@ -10,7 +10,7 @@
""" Implements Utility class for Indexes. """ """ Implements Utility class for Indexes. """
from flask import render_template from flask import render_template
from flask_babel import gettext as _ from flask_babel import gettext
from pgadmin.utils.ajax import internal_server_error from pgadmin.utils.ajax import internal_server_error
from pgadmin.utils.exception import ObjectGone, ExecuteError from pgadmin.utils.exception import ObjectGone, ExecuteError
from functools import wraps from functools import wraps
@ -204,7 +204,7 @@ def _get_create_sql(data, template_path, conn, mode, name,
err = True err = True
# Check if we have at least one column # Check if we have at least one column
if err: if err:
return _('-- definition incomplete'), name return gettext('-- definition incomplete'), name
# If the request for new object which do not have did # If the request for new object which do not have did
sql = render_template( sql = render_template(
@ -253,7 +253,7 @@ def get_sql(conn, **kwargs):
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
raise ObjectGone(_('Could not find the index in the table.')) raise ObjectGone(gettext('Could not find the index in the table.'))
old_data = dict(res['rows'][0]) old_data = dict(res['rows'][0])
@ -320,7 +320,7 @@ def get_reverse_engineered_sql(conn, **kwargs):
raise ExecuteError(res) raise ExecuteError(res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
raise ObjectGone(_('Could not find the index in the table.')) raise ObjectGone(gettext('Could not find the index in the table.'))
data = dict(res['rows'][0]) data = dict(res['rows'][0])
# Adding parent into data dict, will be using it while creating sql # Adding parent into data dict, will be using it while creating sql

View File

@ -10,7 +10,7 @@
""" Implements Utility class for row level security. """ """ Implements Utility class for row level security. """
from flask import render_template from flask import render_template
from flask_babel import gettext as _ from flask_babel import gettext
from pgadmin.utils.ajax import internal_server_error from pgadmin.utils.ajax import internal_server_error
from pgadmin.utils.exception import ObjectGone, ExecuteError from pgadmin.utils.exception import ObjectGone, ExecuteError
from functools import wraps from functools import wraps
@ -82,7 +82,7 @@ def get_sql(conn, **kwargs):
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
raise ObjectGone(_('Could not find the policy in the table.')) raise ObjectGone(gettext('Could not find the policy in the table.'))
old_data = dict(res['rows'][0]) old_data = dict(res['rows'][0])
old_data['schema'] = schema old_data['schema'] = schema
@ -126,7 +126,7 @@ def get_reverse_engineered_sql(conn, **kwargs):
raise ExecuteError(res) raise ExecuteError(res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
raise ObjectGone(_('Could not find the policy in the table.')) raise ObjectGone(gettext('Could not find the policy in the table.'))
data = dict(res['rows'][0]) data = dict(res['rows'][0])
# Adding parent into data dict, will be using it while creating sql # Adding parent into data dict, will be using it while creating sql

View File

@ -10,7 +10,7 @@
""" Implements Utility class for Triggers. """ """ Implements Utility class for Triggers. """
from flask import render_template from flask import render_template
from flask_babel import gettext as _ from flask_babel import gettext
from pgadmin.utils.ajax import internal_server_error from pgadmin.utils.ajax import internal_server_error
from pgadmin.utils.exception import ObjectGone, ExecuteError from pgadmin.utils.exception import ObjectGone, ExecuteError
from pgadmin.browser.server_groups.servers.databases.schemas.utils \ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
@ -165,7 +165,7 @@ def get_sql(conn, **kwargs):
if not status: if not status:
raise ExecuteError(res) raise ExecuteError(res)
elif len(res['rows']) == 0: elif len(res['rows']) == 0:
raise ObjectGone(_('Could not find the trigger in the table.')) raise ObjectGone(gettext('Could not find the trigger in the table.'))
old_data = dict(res['rows'][0]) old_data = dict(res['rows'][0])
# If name is not present in data then # If name is not present in data then
@ -202,7 +202,7 @@ def get_sql(conn, **kwargs):
for arg in required_args: for arg in required_args:
if arg not in data: if arg not in data:
return _('-- definition incomplete') return gettext('-- definition incomplete')
# If the request for new object which do not have did # If the request for new object which do not have did
sql = render_template("/".join([template_path, 'create.sql']), sql = render_template("/".join([template_path, 'create.sql']),
@ -279,7 +279,7 @@ def get_reverse_engineered_sql(conn, **kwargs):
raise ExecuteError(res) raise ExecuteError(res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
raise ObjectGone(_('Could not find the trigger in the table.')) raise ObjectGone(gettext('Could not find the trigger in the table.'))
data = dict(res['rows'][0]) data = dict(res['rows'][0])

View File

@ -9,14 +9,13 @@
"""Implements Backup Utility""" """Implements Backup Utility"""
import json import json
import os
import copy import copy
import functools import functools
import operator import operator
from flask import render_template, request, current_app, \ from flask import render_template, request, current_app, \
url_for, Response url_for, Response
from flask_babel import gettext as _ from flask_babel import gettext
from flask_security import login_required, current_user from flask_security import login_required, current_user
from pgadmin.misc.bgprocess.processes import BatchProcess, IProcessDesc from pgadmin.misc.bgprocess.processes import BatchProcess, IProcessDesc
from pgadmin.utils import PgAdminModule, get_storage_directory, html, \ from pgadmin.utils import PgAdminModule, get_storage_directory, html, \
@ -45,7 +44,7 @@ class BackupModule(PgAdminModule):
javascript file. javascript file.
""" """
LABEL = _('Backup') LABEL = gettext('Backup')
def show_system_objects(self): def show_system_objects(self):
""" """
@ -111,7 +110,7 @@ class BackupMessage(IProcessDesc):
s = get_server(self.sid) s = get_server(self.sid)
if s is None: if s is None:
return _("Not available") return gettext("Not available")
from pgadmin.utils.driver import get_driver from pgadmin.utils.driver import get_driver
driver = get_driver(PG_DEFAULT_DRIVER) driver = get_driver(PG_DEFAULT_DRIVER)
@ -125,31 +124,31 @@ class BackupMessage(IProcessDesc):
@property @property
def type_desc(self): def type_desc(self):
if self.backup_type == BACKUP.OBJECT: if self.backup_type == BACKUP.OBJECT:
return _("Backing up an object on the server") return gettext("Backing up an object on the server")
if self.backup_type == BACKUP.GLOBALS: if self.backup_type == BACKUP.GLOBALS:
return _("Backing up the global objects") return gettext("Backing up the global objects")
elif self.backup_type == BACKUP.SERVER: elif self.backup_type == BACKUP.SERVER:
return _("Backing up the server") return gettext("Backing up the server")
else: else:
# It should never reach here. # It should never reach here.
return _("Unknown Backup") return gettext("Unknown Backup")
@property @property
def message(self): def message(self):
server_name = self.get_server_name() server_name = self.get_server_name()
if self.backup_type == BACKUP.OBJECT: if self.backup_type == BACKUP.OBJECT:
return _( return gettext(
"Backing up an object on the server '{0}' " "Backing up an object on the server '{0}' "
"from database '{1}'" "from database '{1}'"
).format(server_name, self.database) ).format(server_name, self.database)
if self.backup_type == BACKUP.GLOBALS: if self.backup_type == BACKUP.GLOBALS:
return _("Backing up the global objects on " return gettext("Backing up the global objects on "
"the server '{0}'").format( "the server '{0}'").format(
server_name server_name
) )
elif self.backup_type == BACKUP.SERVER: elif self.backup_type == BACKUP.SERVER:
return _("Backing up the server '{0}'").format( return gettext("Backing up the server '{0}'").format(
server_name server_name
) )
else: else:
@ -158,13 +157,13 @@ class BackupMessage(IProcessDesc):
def details(self, cmd, args): def details(self, cmd, args):
server_name = self.get_server_name() server_name = self.get_server_name()
backup_type = _("Backup") backup_type = gettext("Backup")
if self.backup_type == BACKUP.OBJECT: if self.backup_type == BACKUP.OBJECT:
backup_type = _("Backup Object") backup_type = gettext("Backup Object")
elif self.backup_type == BACKUP.GLOBALS: elif self.backup_type == BACKUP.GLOBALS:
backup_type = _("Backup Globals") backup_type = gettext("Backup Globals")
elif self.backup_type == BACKUP.SERVER: elif self.backup_type == BACKUP.SERVER:
backup_type = _("Backup Server") backup_type = gettext("Backup Server")
return { return {
"message": self.message, "message": self.message,
@ -178,7 +177,7 @@ class BackupMessage(IProcessDesc):
@blueprint.route("/") @blueprint.route("/")
@login_required @login_required
def index(): def index():
return bad_request(errormsg=_("This URL cannot be called directly.")) return bad_request(errormsg=gettext("This URL cannot be called directly."))
@blueprint.route("/backup.js") @blueprint.route("/backup.js")
@ -415,7 +414,7 @@ def create_backup_objects_job(sid):
if server is None: if server is None:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_("Could not find the specified server.") errormsg=gettext("Could not find the specified server.")
) )
# To fetch MetaData for the server # To fetch MetaData for the server
@ -428,7 +427,7 @@ def create_backup_objects_job(sid):
if not connected: if not connected:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_("Please connect to the server first.") errormsg=gettext("Please connect to the server first.")
) )
utility = manager.utility('backup') if backup_obj_type == 'objects' \ utility = manager.utility('backup') if backup_obj_type == 'objects' \
@ -508,7 +507,7 @@ def check_utility_exists(sid, backup_obj_type):
if server is None: if server is None:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_("Could not find the specified server.") errormsg=gettext("Could not find the specified server.")
) )
from pgadmin.utils.driver import get_driver from pgadmin.utils.driver import get_driver
@ -552,7 +551,7 @@ def objects(sid, did, scid=None):
if server is None: if server is None:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_("Could not find the specified server.") errormsg=gettext("Could not find the specified server.")
) )
from pgadmin.utils.driver import get_driver from pgadmin.utils.driver import get_driver