style(python): ignore PLW1501,E721,S413,PLE0704,RUF025,PLR0916,PERF403,PLW0604,PLR1733,S410,PLW3201,PLW0108,S403,S405,PLW1641

Bug #31771
This commit is contained in:
Florian Best 2024-02-18 12:55:56 +01:00
parent cae922406e
commit eb2acd7b59
57 changed files with 63 additions and 63 deletions

View File

@ -34,7 +34,7 @@
import math
import os
import subprocess
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET # noqa: S405
STEPS = 48

View File

@ -757,7 +757,7 @@ class _ConfigRegistry(dict):
for key, val in sorted(self.items())
)
def __unicode__(self):
def __unicode__(self): # noqa: PLW3201
data = self.__str__()
if isinstance(data, bytes):
data = data.decode('UTF-8')

View File

@ -42,7 +42,7 @@ from __future__ import print_function
import errno
import os
import pickle
import pickle # noqa: S403
import random
import re
import subprocess

View File

@ -99,7 +99,7 @@ else:
__LD = dict
class LocalizedDictionary(__LD):
class LocalizedDictionary(__LD): # noqa: PLW1641
"""Localized descriptions."""
_LOCALE_REGEX = re.compile(r'(?P<key>[a-zA-Z]*)\[(?P<lang>[a-z]*)\]$')

View File

@ -33,10 +33,10 @@ def test_ro(ucrf):
@pytest.mark.parametrize("autoload,before,after", [
pytest.param(lambda: UCR.ConfigRegistry(), None, None, id="Manual"),
pytest.param(lambda: UCR.ConfigRegistry(), None, None, id="Manual"), # noqa: PLW0108
pytest.param(lambda: UCR.ucr, "BEFORE", "BEFORE", id="Once"),
pytest.param(lambda: UCR.ucr_live, "BEFORE", "AFTER", id="Always"),
pytest.param(lambda: UCR.ucr_live.__enter__(), "BEFORE", "BEFORE", id="View"),
pytest.param(lambda: UCR.ucr_live.__enter__(), "BEFORE", "BEFORE", id="View"), # noqa: PLW0108
])
def test_autoload(autoload, before, after, ucr0):
reload(UCR)

View File

@ -140,7 +140,7 @@ _handler_syslog = None
_do_flush = False
_enable_function = False
_enable_syslog = False
_logger_level = {key: DEFAULT for key in _map_id_old2new.values()}
_logger_level = {key: DEFAULT for key in _map_id_old2new.values()} # noqa: RUF025
def init(logfile, force_flush=0, enable_function=0, enable_syslog=0):

View File

@ -98,7 +98,7 @@ class SkipPhase(Exception):
pass
class Phase:
class Phase: # noqa: PLW1641
"""Base-class for all phases."""
priority = 0

View File

@ -455,7 +455,7 @@ class Device(object):
vals: Dict[str, str | None] = {key: None for key in ucr if pattern.match(key)}
for key, val in self._leftover:
vals[key] = val
vals[key] = val # noqa: PERF403
if self.start is not None:
vals['interfaces/%s/start' % (name)] = str(bool(self.start)).lower()

View File

@ -344,7 +344,7 @@ def written_profile(values: Dict[str, str]) -> Iterator[None]:
os.remove(PATH_PROFILE)
class ProgressState(object):
class ProgressState(object): # noqa: PLW1641
def __init__(self) -> None:
self.reset()

View File

@ -45,7 +45,7 @@ except ImportError:
from six.moves.urllib_parse import quote, urlsplit
class UcsRepoUrl(object):
class UcsRepoUrl(object): # noqa: PLW1641
"""UCS repository server base URL."""
DEFAULT = 'https://updates.software-univention.de/'

View File

@ -126,7 +126,7 @@ def verify_script(script, signature):
return stdout if ret != 0 else None
class _UCSRepo(UCS_Version):
class _UCSRepo(UCS_Version): # noqa: PLW1641
"""Super class to build URLs for APT repositories."""
ARCHS = {'all', 'amd64'}
@ -423,7 +423,7 @@ class UCSRepoPoolNoArch(_UCSRepo):
return "clean %s%s" % (server, super(UCSRepoPoolNoArch, self)._format(fmt))
class _UCSServer(object):
class _UCSServer(object): # noqa: PLW1641
"""Abstrace base class to access UCS compatible update server."""
@classmethod

View File

@ -27,7 +27,7 @@ def test_parse_args_rejects_invalid_update_to_bug49061(mocker):
with pytest.raises(SystemExit) as pytest_wrapped_e:
mocker.patch('sys.argv', ['/usr/sbin/univention-upgrade', '--updateto=4.0.0'])
parse_args()
assert pytest_wrapped_e.type == SystemExit
assert pytest_wrapped_e.type == SystemExit # noqa: E721
assert pytest_wrapped_e.value.code == 1

View File

@ -69,7 +69,7 @@ glocal_acl_pattern1 = re.compile(r'(?P<folder>[^ ]+) "(?P<id>.+)" (?P<acl>\w+)')
glocal_acl_pattern2 = re.compile(r'(?P<folder>[^ ]+) (?P<id>.+) (?P<acl>\w+)')
class DovecotFolderAclEntry(object):
class DovecotFolderAclEntry(object): # noqa: PLW1641
def __init__(self, folder_name, identifier, acl): # type: (str, str, str) -> None
self.folder_name = folder_name
self.identifier = identifier

View File

@ -73,7 +73,7 @@ class _Link(object):
port = ''
return '%s://%s%s%s' % (self.protocol, self.host, port, self.path)
def __nonzero__(self):
def __nonzero__(self): # noqa: PLW3201
return str(self) != ''
__bool__ = __nonzero__

View File

@ -485,7 +485,7 @@ class AppMetaClass(UniventionMetaClass):
return new_cls
class App(with_metaclass(AppMetaClass, object)):
class App(with_metaclass(AppMetaClass, object)): # noqa: PLW1641
"""
This is the main App class. It represents *one version* of the App in
the Univention App Center. It is mainly a container for a parsed ini

View File

@ -61,7 +61,7 @@ def ucr_save(values):
_UCR.load()
for k, v in values.items():
if _UCR.get(k) != v:
changed_values[k] = v
changed_values[k] = v # noqa: PERF403
if changed_values:
ucr_update(_UCR, changed_values)
return changed_values

View File

@ -65,7 +65,7 @@ def mocked_ucr_appcenter(mock_ucr, mocker):
changed_values = {}
for k, v in values.items():
if mock_ucr.get(k) != v:
changed_values[k] = v
changed_values[k] = v # noqa: PERF403
if changed_values:
mock_ucr.items.update(changed_values)
return changed_values

View File

@ -543,7 +543,7 @@ if six.PY2: # deprecated, use layout.Tab instead
if six.PY2: # deprecated, use layout.Group instead
class field:
class field: # noqa: PLW1641
"""
>>> field('bar') < field('foo')
True

View File

@ -101,7 +101,7 @@ class conjunction(object):
return ''
return '(%s%s)' % (self.type, ''.join(map(six.text_type, self.expressions)))
def __unicode__(self):
def __unicode__(self): # noqa: PLW3201
# type: () -> str
return self.__str__()
@ -198,7 +198,7 @@ class expression(object):
self.__dict__.update(con.__dict__)
self.__class__ = type(con) # type: ignore
def __unicode__(self):
def __unicode__(self): # noqa: PLW3201
# type: () -> str
return self.__str__()

View File

@ -392,7 +392,7 @@ class object(univention.admin.handlers.simpleLdap):
# modlist for new items
for lang, txt in oldlist.items():
if txt != newlist[lang]:
ml.append(('univentionUDMPropertyTranslation%s;entry-%s' % (transKey, lang), oldlist[lang], newlist[lang]))
ml.append(('univentionUDMPropertyTranslation%s;entry-%s' % (transKey, lang), oldlist[lang], newlist[lang])) # noqa: PLR1733
return ml

View File

@ -197,7 +197,7 @@ class object(univention.admin.handlers.simpleLdap):
# modlist for new items
for lang, txt in oldlist.items():
if txt != newlist[lang]:
ml.append(('univentionUDMOptionTranslation%s;entry-%s' % (transKey, lang), oldlist[lang], newlist[lang]))
ml.append(('univentionUDMOptionTranslation%s;entry-%s' % (transKey, lang), oldlist[lang], newlist[lang])) # noqa: PLR1733
return ml

View File

@ -5520,7 +5520,7 @@ class SambaLogonHours(MultiSelect):
from univention.admin.handlers.users.user import logonHoursUnmap
value = logonHoursUnmap([value.encode('ASCII')])
else:
value = list(map(lambda x: int(x), shlex.split(value)))
value = list(map(lambda x: int(x), shlex.split(value))) # noqa: PLW0108
return super(SambaLogonHours, self).parse(value)

View File

@ -69,7 +69,7 @@ class DN(object):
def __str__(self):
return ldap.dn.dn2str(self._dn)
def __unicode__(self):
def __unicode__(self): # noqa: PLW3201
return unicode(str(self)) # noqa: F821
def __repr__(self):

View File

@ -797,7 +797,7 @@ class CLI(object):
object.policy_reference(*policy_reference)
object.policy_dereference(*policy_dereference)
if object.hasChanged(input.keys()) or object.hasChanged(append.keys()) or object.hasChanged(remove.keys()) or parsed_append_options or parsed_remove_options or parsed_options or object.policiesChanged():
if object.hasChanged(input.keys()) or object.hasChanged(append.keys()) or object.hasChanged(remove.keys()) or parsed_append_options or parsed_remove_options or parsed_options or object.policiesChanged(): # noqa: PLR0916
try:
dn = object.modify()
object_modified += 1

View File

@ -35,7 +35,7 @@
import json
import re
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET # noqa: S405
import defusedxml.minidom
from genshi import XML

View File

@ -46,7 +46,7 @@ import os
import re
import traceback
import uuid
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET # noqa: S405
import zlib
from http.client import responses
from typing import Dict, List, Optional
@ -2687,7 +2687,7 @@ class PolicyResultBase(Resource):
infos = copy.copy(policy_obj.polinfo_more)
for key, _value in infos.items():
if key in policy_obj.polinfo:
if isinstance(infos[key], (tuple, list)):
if isinstance(infos[key], (tuple, list)): # noqa: PLR1733
continue
_value['value'] = policy_obj.polinfo[key]
if policy_dn:

View File

@ -221,7 +221,7 @@ ucr_vars = [
for i in ucr_vars:
for key, value in get_ucr_entry(*i):
data[key] = value
data[key] = value # noqa: PERF403
print(json.dumps(data, indent=2, sort_keys=True))
@!@

View File

@ -38,7 +38,7 @@ from __future__ import print_function
import json
import os
import pickle
import pickle # noqa: S403
import sys
from argparse import ArgumentParser

View File

@ -71,7 +71,7 @@ import itertools
import json
import operator
import os
import pickle
import pickle # noqa: S403
import traceback
from fnmatch import fnmatch
@ -89,7 +89,7 @@ from .config import ucr
from .log import ACL
class Rule(dict):
class Rule(dict): # noqa: PLW1641
"""
A simple class representing one ACL rule in a form that can be
simply serialized.

View File

@ -70,7 +70,7 @@ must be given in curly braces {VARIABLE}.
import os
import sys
import xml.etree.cElementTree as ET
import xml.etree.cElementTree as ET # noqa: S405
import xml.parsers.expat
from .log import RESOURCES

View File

@ -124,7 +124,7 @@ import copy
import os
import re
import sys
import xml.etree.cElementTree as ET
import xml.etree.cElementTree as ET # noqa: S405
import xml.parsers.expat
from .config import ucr

View File

@ -110,7 +110,7 @@ class Resource(RequestHandler):
def get_current_user(self):
session = Session.get_or_create(self.get_session_id()) # FIXME: this creates a Session instance even if the session does not exists
session._ = lambda *args: self._(*args) # hack to prevent circular use, when "_" is not yet set but only in prepare()
session._ = lambda *args: self._(*args) # hack to prevent circular use, when "_" is not yet set but only in prepare() # noqa: PLW0108
if not session.user.ip:
session.user.ip = self.get_ip_address()
return session

View File

@ -35,7 +35,7 @@
import getopt
import os
import pickle
import pickle # noqa: S403
import subprocess
import sys

View File

@ -39,7 +39,7 @@ from __future__ import absolute_import
import os
import polib
from lxml import etree
from lxml import etree # noqa: S410
from . import message_catalogs, umc

View File

@ -64,7 +64,7 @@ import re
import subprocess
import sys
import warnings
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET # noqa: S405
from email.utils import formatdate
import polib

View File

@ -38,7 +38,7 @@ from __future__ import absolute_import, annotations
import glob
import os
import os.path
import xml.etree.ElementTree
import xml.etree.ElementTree # noqa: S405
from subprocess import PIPE, Popen
from tempfile import NamedTemporaryFile
from typing import Dict, List, Tuple

View File

@ -1615,7 +1615,7 @@ class ad(univention.connector.ucs):
ud.debug(ud.LDAP, ud.INFO, "group_members_sync_to_ucs: members to add: %s" % add_members)
ud.debug(ud.LDAP, ud.INFO, "group_members_sync_to_ucs: members to del: %s" % del_members)
if add_members['user'] or add_members['group'] or del_members['user'] or del_members['group'] or add_members['unknown'] or add_members['windowscomputer'] or del_members['windowscomputer']:
if add_members['user'] or add_members['group'] or del_members['user'] or del_members['group'] or add_members['unknown'] or add_members['windowscomputer'] or del_members['windowscomputer']: # noqa: PLR0916
ucs_admin_object = univention.admin.objects.get(self.modules[object_key], co='', lo=self.lo, position='', dn=object['dn'])
ucs_admin_object.open()

View File

@ -45,7 +45,7 @@ import Crypto
import heimdal
import ldap
import samba.dcerpc.samr
from Crypto.Cipher import ARC4, DES
from Crypto.Cipher import ARC4, DES # noqa: S413
from samba import NTSTATUSError
from samba.dcerpc import drsblobs, drsuapi, lsa, misc, security
from samba.ndr import ndr_unpack

View File

@ -72,7 +72,7 @@ class RsyslogTransport(object):
# message
payload = Regex(".*")
payload.setParseAction(lambda t: "".join(t)) # json parsing happens in Event class
payload.setParseAction(lambda t: "".join(t)) # json parsing happens in Event class # noqa: PLW0108
self._pattern = timestamp("source_datetime") + hostname("source_hostname") + syslogtag + payload("serialized_event_dict")

View File

@ -62,7 +62,7 @@ class AppListener(ListenerModuleHandler):
if old_dn:
self.run_update = True
self.logger.info('config update triggered (move)')
elif (b'univentionRadiusClient' in old.get('objectClass', []) or b'univentionRadiusClient' in new.get('objectClass', [])) and (
elif (b'univentionRadiusClient' in old.get('objectClass', []) or b'univentionRadiusClient' in new.get('objectClass', [])) and ( # noqa: PLR0916
set(old.get('univentionRadiusClientSharedSecret', [])) != set(new.get('univentionRadiusClientSharedSecret', []))
or set(old.get('univentionRadiusClientType', [])) != set(new.get('univentionRadiusClientType', []))
or set(old.get('univentionRadiusClientVirtualServer', [])) != set(new.get('univentionRadiusClientVirtualServer', []))

View File

@ -44,7 +44,7 @@ from os.path import exists, extsep, join, split, splitext
from sys import exit, stderr
import libvirt
from lxml import etree
from lxml import etree # noqa: S410
from lxml.builder import E
from urlparse import urlparse

View File

@ -5,7 +5,7 @@
## - univention-base-files
## exposure: dangerous
import pickle
import pickle # noqa: S403
import sys
import univention.config_registry.handler as ucrh

View File

@ -1,5 +1,5 @@
import os
import pickle
import pickle # noqa: S403
import time
from univention.testing import utils

View File

@ -48,13 +48,13 @@ class Configuring:
def __exit__(self, exc_type, exc_val, exc_tb):
if self.revert == 'configure':
config = {key: None for key in self.settings}
config = {key: None for key in self.settings} # noqa: RUF025
configure = get_action('configure')
configure.call(app=self.app, set_vars=config, run_script='no')
for setting in self.settings:
assert ucr_get(setting) is None
elif self.revert == 'ucr':
config = {key: None for key in self.settings}
config = {key: None for key in self.settings} # noqa: RUF025
ucr_save(config)

View File

@ -70,7 +70,7 @@ def test_ini_data(umc_data, lang):
'description': 'Test App [%s]' % lang,
}
for ikey, ival in expected_data.items():
expected_val = expected_data[ikey]
expected_val = expected_data[ikey] # noqa: PLR1733
assert umc_data[ikey] == ival, f'Entry {ikey}={ival} does not match expected value {expected_val}!'
print('SUCCESS')

View File

@ -14,7 +14,7 @@ from univention.appcenter.actions import get_action
def mock_ucr_get(var):
if var == 'version/version':
return '4.4'
raise
raise # noqa: PLE0704
# new app cache

View File

@ -68,7 +68,7 @@ def check_webinterface(app):
def _check_url(url):
print(' Checking', url)
import lxml
import lxml # noqa: S410
import requests
requests_timeout = 30
r = requests.get(url, timeout=requests_timeout, verify=False) # noqa: S501

View File

@ -88,6 +88,6 @@ def main():
if __name__ == '__main__':
global timeout
global timeout # noqa: PLW0604
timeout = 1
main()

View File

@ -140,6 +140,6 @@ def main():
if __name__ == '__main__':
global timeout
global timeout # noqa: PLW0604
timeout = 1
main()

View File

@ -85,6 +85,6 @@ def main() -> None:
if __name__ == '__main__':
global timeout
global timeout # noqa: PLW0604
timeout = 1
main()

View File

@ -135,6 +135,6 @@ def main():
if __name__ == '__main__':
global timeout
global timeout # noqa: PLW0604
timeout = 1
main()

View File

@ -108,7 +108,7 @@ class SimpleCurl:
time.sleep(1)
else:
print('Requested page could not be fetched')
raise
raise # noqa: PLE0704
page = buf.getvalue()
# print page[1:400]
buf.close()

View File

@ -8,7 +8,7 @@
## - domaincontroller_master
## - domaincontroller_slave
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET # noqa: S405
from os import path
from re import search
from subprocess import PIPE, Popen

View File

@ -10,7 +10,7 @@ from html import unescape
import requests
from bs4 import BeautifulSoup
from lxml import etree
from lxml import etree # noqa: S410
from requests_kerberos import OPTIONAL, HTTPKerberosAuth
import univention.config_registry as configRegistry

View File

@ -180,7 +180,7 @@ class Interactions:
from univention.testing.browser.appcenter import AppCenter, wait_for_final_query
app_center = AppCenter(self.tester)
with self.page.expect_response(lambda request: wait_for_final_query(request), timeout=2 * MIN):
with self.page.expect_response(lambda request: wait_for_final_query(request), timeout=2 * MIN): # noqa: PLW0108
app_center.handle_first_open_dialog()
def fill_combobox(self, name: str, option: str):

View File

@ -128,7 +128,7 @@ def get_tests(sections: Iterable[str]) -> Dict[str, List[str]]:
return result
class UCSVersion: # pylint: disable-msg=R0903
class UCSVersion: # pylint: disable-msg=R0903 # noqa: PLW1641
"""
UCS version.

View File

@ -30,7 +30,7 @@ MAPPED_UDM_PROPERTIES = [
def setup_kelvin_traeger():
with open('/var/lib/ucs-school-import/configs/kelvin.json', 'r+w') as fp:
with open('/var/lib/ucs-school-import/configs/kelvin.json', 'r+w') as fp: # noqa: PLW1501
config = json.load(fp)
config['configuration_checks'] = ['defaults', 'class_overwrites', 'mapped_udm_properties']
config['mapped_udm_properties'] = MAPPED_UDM_PROPERTIES