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):
if isinstance(value, bytes):
value = value.decode('utf-8')
value = value.decode("utf-8")
return value
# result_list is for example :

View file

@ -95,10 +95,7 @@ class Translator(object):
failed_to_format = False
if key in self._translations.get(self.locale, {}):
try:
return (
self._translations[self.locale][key]
.format(*args, **kwargs)
)
return self._translations[self.locale][key].format(*args, **kwargs)
except KeyError as e:
unformatted_string = self._translations[self.locale][key]
error_message = (
@ -120,14 +117,11 @@ class Translator(object):
logger.info("untranslated key '%s' for locale '%s'", key, self.locale)
try:
return (
self._translations[self.default_locale][key]
.format(*args, **kwargs)
return self._translations[self.default_locale][key].format(
*args, **kwargs
)
except KeyError as e:
unformatted_string = self._translations[self.default_locale][
key
]
unformatted_string = self._translations[self.default_locale][key]
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)"
% (key, unformatted_string, args, kwargs, e.__class__.__name__, e)
@ -169,7 +163,7 @@ class Translator(object):
return True
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)
except IOError:
return False

View file

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

View file

@ -158,11 +158,9 @@ def write_to_file(file_path, data, file_mode="w"):
assert not os.path.isdir(file_path), (
"Error: file_path '%s' point to a dir, it should be a file" % file_path
)
assert os.path.isdir(
os.path.dirname(file_path)
), "Error: the path ('%s') base dir ('%s') is not a dir" % (
file_path,
os.path.dirname(file_path),
assert os.path.isdir(os.path.dirname(file_path)), (
"Error: the path ('%s') base dir ('%s') is not a dir"
% (file_path, os.path.dirname(file_path),)
)
# 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"
% (file_path, type(file_path))
)
assert isinstance(data, dict) or isinstance(
data, list
), "Error: data '%s' should be a dict or a list but is of type '%s' instead" % (
data,
type(data),
assert isinstance(data, dict) or isinstance(data, list), (
"Error: data '%s' should be a dict or a list but is of type '%s' instead"
% (data, type(data),)
)
assert not os.path.isdir(file_path), (
"Error: file_path '%s' point to a dir, it should be a file" % file_path
)
assert os.path.isdir(
os.path.dirname(file_path)
), "Error: the path ('%s') base dir ('%s') is not a dir" % (
file_path,
os.path.dirname(file_path),
assert os.path.isdir(os.path.dirname(file_path)), (
"Error: the path ('%s') base dir ('%s') is not a dir"
% (file_path, os.path.dirname(file_path),)
)
# 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.
"""
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 ----------------------------------------------
@ -66,7 +70,7 @@ def call_async_output(args, callback, **kwargs):
kwargs["pass_fds"] = [stdinfo.fdWrite]
if "env" not in kwargs:
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:
kwargs["stdout"].close()

View file

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

View file

@ -11,7 +11,10 @@ HERE = os.path.abspath(os.path.dirname(__file__))
class LDAPServer:
def __init__(self):
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()
self.server_default.slapd_conf_template = SLAPD_CONF_TEMPLATE
self.server_default.suffix = "dc=yunohost,dc=org"
@ -33,7 +36,9 @@ class LDAPServer:
self.server = self.server_default
self.server.start()
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()
self.server.ldapadd(ldif)
self.tools_ldapinit()

View file

@ -199,8 +199,7 @@ def combined_logger(
fmt=" ".join((log_name, sys_log_format))
)
my_syslog_handler = logging.handlers.SysLogHandler(
address="/dev/log",
facility=SysLogHandler.LOG_DAEMON,
address="/dev/log", facility=SysLogHandler.LOG_DAEMON,
)
my_syslog_handler.setFormatter(my_syslog_formatter)
new_logger.addHandler(my_syslog_handler)
@ -372,8 +371,7 @@ class SlapdObject(object):
"""
include_directives = "\n".join(
'include "{schema_prefix}/{schema_file}"'.format(
schema_prefix=self._schema_prefix,
schema_file=schema_file,
schema_prefix=self._schema_prefix, schema_file=schema_file,
)
for schema_file in self.openldap_schema_files
)
@ -563,13 +561,7 @@ class SlapdObject(object):
if ldap_uri is None:
ldap_uri = self.default_ldap_uri
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))
proc = subprocess.Popen(

View file

@ -58,11 +58,9 @@ class TestLDAP:
def test_authenticate_sasl_non_interactive_bind(self, ldap_server):
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
self.ldap_conf["parameters"][
"user_rdn"
] = "gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth" % (
os.getgid(),
os.getuid(),
self.ldap_conf["parameters"]["user_rdn"] = (
"gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
% (os.getgid(), os.getuid(),)
)
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):
assert isinstance(a, int)
assert isinstance(b, str)
#assert isinstance(c, str)
# assert isinstance(c, str)
return True
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):
assert isinstance(a, int)
assert isinstance(b, str)
#assert isinstance(c, str)
# assert isinstance(c, str)
return False
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):
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")