This commit is contained in:
Alexandre Aubin 2021-01-20 05:46:05 +01:00
parent 570e53234a
commit 677efcf6d6
10 changed files with 43 additions and 60 deletions

View file

@ -152,7 +152,7 @@ class Authenticator(BaseAuthenticator):
def decode(value): def decode(value):
if isinstance(value, bytes): if isinstance(value, bytes):
value = value.decode('utf-8') value = value.decode("utf-8")
return value return value
# result_list is for example : # result_list is for example :

View file

@ -95,10 +95,7 @@ class Translator(object):
failed_to_format = False failed_to_format = False
if key in self._translations.get(self.locale, {}): if key in self._translations.get(self.locale, {}):
try: try:
return ( return self._translations[self.locale][key].format(*args, **kwargs)
self._translations[self.locale][key]
.format(*args, **kwargs)
)
except KeyError as e: except KeyError as e:
unformatted_string = self._translations[self.locale][key] unformatted_string = self._translations[self.locale][key]
error_message = ( error_message = (
@ -120,14 +117,11 @@ class Translator(object):
logger.info("untranslated key '%s' for locale '%s'", key, self.locale) logger.info("untranslated key '%s' for locale '%s'", key, self.locale)
try: try:
return ( return self._translations[self.default_locale][key].format(
self._translations[self.default_locale][key] *args, **kwargs
.format(*args, **kwargs)
) )
except KeyError as e: except KeyError as e:
unformatted_string = self._translations[self.default_locale][ unformatted_string = self._translations[self.default_locale][key]
key
]
error_message = ( error_message = (
"Failed to format translatable string '%s': '%s' with arguments '%s' and '%s', raising error: %s(%s) (don't panic this is just a warning)" "Failed to format translatable string '%s': '%s' with arguments '%s' and '%s', raising error: %s(%s) (don't panic this is just a warning)"
% (key, unformatted_string, args, kwargs, e.__class__.__name__, e) % (key, unformatted_string, args, kwargs, e.__class__.__name__, e)
@ -169,7 +163,7 @@ class Translator(object):
return True return True
try: try:
with open("%s/%s.json" % (self.locale_dir, locale), "r", encoding='utf-8') as f: with open(f"{self.locale_dir}/{locale}.json", "r", encoding="utf-8") as f:
j = json.load(f) j = json.load(f)
except IOError: except IOError:
return False return False

View file

@ -288,10 +288,7 @@ class _ActionsMapPlugin(object):
# Append messages route # Append messages route
app.route( app.route(
"/messages", "/messages", name="messages", callback=self.messages, skip=["actionsmap"],
name="messages",
callback=self.messages,
skip=["actionsmap"],
) )
# Append routes from the actions map # Append routes from the actions map
@ -818,9 +815,7 @@ class Interface(BaseInterface):
""" """
logger.debug( logger.debug(
"starting the server instance in %s:%d", "starting the server instance in %s:%d", host, port,
host,
port,
) )
try: try:

View file

@ -158,11 +158,9 @@ def write_to_file(file_path, data, file_mode="w"):
assert not os.path.isdir(file_path), ( assert not os.path.isdir(file_path), (
"Error: file_path '%s' point to a dir, it should be a file" % file_path "Error: file_path '%s' point to a dir, it should be a file" % file_path
) )
assert os.path.isdir( assert os.path.isdir(os.path.dirname(file_path)), (
os.path.dirname(file_path) "Error: the path ('%s') base dir ('%s') is not a dir"
), "Error: the path ('%s') base dir ('%s') is not a dir" % ( % (file_path, os.path.dirname(file_path),)
file_path,
os.path.dirname(file_path),
) )
# If data is a list, check elements are strings and build a single string # If data is a list, check elements are strings and build a single string
@ -209,20 +207,16 @@ def write_to_json(file_path, data, sort_keys=False, indent=None):
"Error: file_path '%s' should be a string but is of type '%s' instead" "Error: file_path '%s' should be a string but is of type '%s' instead"
% (file_path, type(file_path)) % (file_path, type(file_path))
) )
assert isinstance(data, dict) or isinstance( assert isinstance(data, dict) or isinstance(data, list), (
data, list "Error: data '%s' should be a dict or a list but is of type '%s' instead"
), "Error: data '%s' should be a dict or a list but is of type '%s' instead" % ( % (data, type(data),)
data,
type(data),
) )
assert not os.path.isdir(file_path), ( assert not os.path.isdir(file_path), (
"Error: file_path '%s' point to a dir, it should be a file" % file_path "Error: file_path '%s' point to a dir, it should be a file" % file_path
) )
assert os.path.isdir( assert os.path.isdir(os.path.dirname(file_path)), (
os.path.dirname(file_path) "Error: the path ('%s') base dir ('%s') is not a dir"
), "Error: the path ('%s') base dir ('%s') is not a dir" % ( % (file_path, os.path.dirname(file_path),)
file_path,
os.path.dirname(file_path),
) )
# Write dict to file # Write dict to file

View file

@ -28,7 +28,11 @@ def check_output(args, stderr=subprocess.STDOUT, shell=True, **kwargs):
and use shell by default before calling subprocess.check_output. and use shell by default before calling subprocess.check_output.
""" """
return subprocess.check_output(args, stderr=stderr, shell=shell, **kwargs).decode('utf-8').strip() return (
subprocess.check_output(args, stderr=stderr, shell=shell, **kwargs)
.decode("utf-8")
.strip()
)
# Call with stream access ---------------------------------------------- # Call with stream access ----------------------------------------------
@ -66,7 +70,7 @@ def call_async_output(args, callback, **kwargs):
kwargs["pass_fds"] = [stdinfo.fdWrite] kwargs["pass_fds"] = [stdinfo.fdWrite]
if "env" not in kwargs: if "env" not in kwargs:
kwargs["env"] = os.environ kwargs["env"] = os.environ
kwargs["env"]['YNH_STDINFO'] = str(stdinfo.fdWrite) kwargs["env"]["YNH_STDINFO"] = str(stdinfo.fdWrite)
with subprocess.Popen(args, **kwargs) as p: with subprocess.Popen(args, **kwargs) as p:
kwargs["stdout"].close() kwargs["stdout"].close()

View file

@ -5,7 +5,6 @@ import threading
class LogPipe(threading.Thread): class LogPipe(threading.Thread):
def __init__(self, log_callback): def __init__(self, log_callback):
"""Setup the object with a logger and a loglevel """Setup the object with a logger and a loglevel
and start the thread and start the thread
@ -27,8 +26,8 @@ class LogPipe(threading.Thread):
def run(self): def run(self):
"""Run the thread, logging everything. """Run the thread, logging everything.
""" """
for line in iter(self.pipeReader.readline, ''): for line in iter(self.pipeReader.readline, ""):
self.log_callback(line.strip('\n')) self.log_callback(line.strip("\n"))
self.pipeReader.close() self.pipeReader.close()

View file

@ -11,7 +11,10 @@ HERE = os.path.abspath(os.path.dirname(__file__))
class LDAPServer: class LDAPServer:
def __init__(self): def __init__(self):
self.server_default = slapdtest.SlapdObject() self.server_default = slapdtest.SlapdObject()
with open(os.path.join(HERE, "..", "ldap_files", "slapd.conf.template"), encoding="utf-8") as f: with open(
os.path.join(HERE, "..", "ldap_files", "slapd.conf.template"),
encoding="utf-8",
) as f:
SLAPD_CONF_TEMPLATE = f.read() SLAPD_CONF_TEMPLATE = f.read()
self.server_default.slapd_conf_template = SLAPD_CONF_TEMPLATE self.server_default.slapd_conf_template = SLAPD_CONF_TEMPLATE
self.server_default.suffix = "dc=yunohost,dc=org" self.server_default.suffix = "dc=yunohost,dc=org"
@ -33,7 +36,9 @@ class LDAPServer:
self.server = self.server_default self.server = self.server_default
self.server.start() self.server.start()
self.uri = self.server.ldapi_uri self.uri = self.server.ldapi_uri
with open(os.path.join(HERE, "..", "ldap_files", "tests.ldif"), encoding="utf-8") as fp: with open(
os.path.join(HERE, "..", "ldap_files", "tests.ldif"), encoding="utf-8"
) as fp:
ldif = fp.read() ldif = fp.read()
self.server.ldapadd(ldif) self.server.ldapadd(ldif)
self.tools_ldapinit() self.tools_ldapinit()

View file

@ -199,8 +199,7 @@ def combined_logger(
fmt=" ".join((log_name, sys_log_format)) fmt=" ".join((log_name, sys_log_format))
) )
my_syslog_handler = logging.handlers.SysLogHandler( my_syslog_handler = logging.handlers.SysLogHandler(
address="/dev/log", address="/dev/log", facility=SysLogHandler.LOG_DAEMON,
facility=SysLogHandler.LOG_DAEMON,
) )
my_syslog_handler.setFormatter(my_syslog_formatter) my_syslog_handler.setFormatter(my_syslog_formatter)
new_logger.addHandler(my_syslog_handler) new_logger.addHandler(my_syslog_handler)
@ -372,8 +371,7 @@ class SlapdObject(object):
""" """
include_directives = "\n".join( include_directives = "\n".join(
'include "{schema_prefix}/{schema_file}"'.format( 'include "{schema_prefix}/{schema_file}"'.format(
schema_prefix=self._schema_prefix, schema_prefix=self._schema_prefix, schema_file=schema_file,
schema_file=schema_file,
) )
for schema_file in self.openldap_schema_files for schema_file in self.openldap_schema_files
) )
@ -563,13 +561,7 @@ class SlapdObject(object):
if ldap_uri is None: if ldap_uri is None:
ldap_uri = self.default_ldap_uri ldap_uri = self.default_ldap_uri
args = ( args = (
[ [ldapcommand, "-H", ldap_uri,] + self._cli_auth_args() + (extra_args or [])
ldapcommand,
"-H",
ldap_uri,
]
+ self._cli_auth_args()
+ (extra_args or [])
) )
self._log.debug("Run command: %r", " ".join(args)) self._log.debug("Run command: %r", " ".join(args))
proc = subprocess.Popen( proc = subprocess.Popen(

View file

@ -58,11 +58,9 @@ class TestLDAP:
def test_authenticate_sasl_non_interactive_bind(self, ldap_server): def test_authenticate_sasl_non_interactive_bind(self, ldap_server):
self.ldap_conf["parameters"]["uri"] = ldap_server.uri self.ldap_conf["parameters"]["uri"] = ldap_server.uri
self.ldap_conf["parameters"][ self.ldap_conf["parameters"]["user_rdn"] = (
"user_rdn" "gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
] = "gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth" % ( % (os.getgid(), os.getuid(),)
os.getgid(),
os.getuid(),
) )
ldap_interface = m_ldap.Authenticator(**self.ldap_conf) ldap_interface = m_ldap.Authenticator(**self.ldap_conf)

View file

@ -23,7 +23,7 @@ def test_run_shell_bad_cmd_with_callback():
def callback(a, b, c): def callback(a, b, c):
assert isinstance(a, int) assert isinstance(a, int)
assert isinstance(b, str) assert isinstance(b, str)
#assert isinstance(c, str) # assert isinstance(c, str)
return True return True
assert run_commands(["yolo swag", "yolo swag", "yolo swag"], callback=callback) == 3 assert run_commands(["yolo swag", "yolo swag", "yolo swag"], callback=callback) == 3
@ -31,7 +31,7 @@ def test_run_shell_bad_cmd_with_callback():
def callback(a, b, c): def callback(a, b, c):
assert isinstance(a, int) assert isinstance(a, int)
assert isinstance(b, str) assert isinstance(b, str)
#assert isinstance(c, str) # assert isinstance(c, str)
return False return False
assert run_commands(["yolo swag", "yolo swag"], callback=callback) == 1 assert run_commands(["yolo swag", "yolo swag"], callback=callback) == 1
@ -115,6 +115,8 @@ def test_call_async_output_kwargs(test_file, mocker):
def test_check_output(test_file): def test_check_output(test_file):
assert check_output(["cat", str(test_file)], shell=False) == "foo\nbar".encode("utf-8") assert check_output(["cat", str(test_file)], shell=False) == "foo\nbar".encode(
"utf-8"
)
assert check_output("cat %s" % str(test_file)) == "foo\nbar".encode("utf-8") assert check_output("cat %s" % str(test_file)) == "foo\nbar".encode("utf-8")