Skip to content

Commit 4f2eb18

Browse files
committed
chore: format the code with ruff
1 parent f3aea4b commit 4f2eb18

File tree

5 files changed

+84
-66
lines changed

5 files changed

+84
-66
lines changed

.pre-commit-config.yaml

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
repos:
3+
- repo: https://github.com/astral-sh/ruff-pre-commit
4+
rev: 'v0.11.2'
5+
hooks:
6+
- id: ruff
7+
args: [--fix, --exit-non-zero-on-fix]
8+
- id: ruff-format
9+

doc/conf.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
#!/usr/bin/env python3
22

3-
import toml
4-
import mock
53
import os
64
import sys
5+
from unittest import mock
6+
7+
import toml
78

89
sys.path.insert(0, os.path.abspath(".."))
910
sys.path.insert(0, os.path.abspath("../slapd"))
@@ -41,7 +42,7 @@ def __getattr__(cls, name):
4142
author = "python-ldap"
4243

4344
release = config["tool"]["poetry"]["version"]
44-
version = "%s.%s" % tuple(map(int, release.split(".")[:2]))
45+
version = ".".join(tuple(map(int, release.split(".")[:2])))
4546
language = None
4647
exclude_patterns = []
4748
pygments_style = "sphinx"

pyproject.toml

+30
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,36 @@ omit = [
5858
".tox/*",
5959
]
6060

61+
[tool.ruff.lint]
62+
select = [
63+
"D", # pydocstyle
64+
"B", # flake8-bugbear
65+
"E", # pycodestyle
66+
"F", # pyflakes
67+
"I", # isort
68+
"UP", # pyupgrade
69+
]
70+
ignore = [
71+
"E501", # line-too-long
72+
"E722", # bare-except
73+
"D100", # public module
74+
"D101", # public class
75+
"D102", # public method
76+
"D103", # public function
77+
"D104", # public package
78+
"D105", # magic method
79+
"D106", # nested class
80+
"D107", # public init
81+
"D203", # no-blank-line-before-class
82+
"D213", # multi-line-summary-second-line
83+
]
84+
85+
[tool.ruff.lint.isort]
86+
force-single-line = true
87+
88+
[tool.ruff.format]
89+
docstring-code-format = true
90+
6191
[tool.pytest.ini_options]
6292
addopts = "--durations=10 --color=yes --showlocals --full-trace --doctest-modules --doctest-glob='*.rst'"
6393
norecursedirs = ".tox tests/perf .eggs .git build doc"

slapd/__init__.py

+39-62
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1+
import atexit
2+
import logging
13
import os
24
import socket
5+
import subprocess
36
import sys
47
import time
5-
import subprocess
6-
import logging
7-
import atexit
88
from logging.handlers import SysLogHandler
99
from shutil import which
1010
from urllib.parse import quote_plus
@@ -47,7 +47,7 @@
4747

4848

4949
def _add_sbin(path):
50-
"""Add /sbin and related directories to a command search path"""
50+
"""Add /sbin and related directories to a command search path."""
5151
directories = path.split(os.pathsep)
5252
if sys.platform != "win32":
5353
for sbin in "/usr/local/sbin", "/sbin", "/usr/sbin":
@@ -62,10 +62,7 @@ def combinedlogger(
6262
syslogger_format="%(levelname)s %(message)s",
6363
consolelogger_format="%(asctime)s %(levelname)s %(message)s",
6464
):
65-
"""
66-
Returns a combined SysLogHandler/StreamHandler logging instance
67-
with formatters
68-
"""
65+
"""Return a combined SysLogHandler/StreamHandler logging instance with formatters."""
6966
if "LOGLEVEL" in os.environ:
7067
log_level = os.environ["LOGLEVEL"]
7168
try:
@@ -94,8 +91,7 @@ def combinedlogger(
9491

9592

9693
class Slapd:
97-
"""
98-
Controller class for a slapd instance, OpenLDAP's server.
94+
"""Controller class for a slapd instance, OpenLDAP's server.
9995
10096
This class creates a temporary data store for slapd, runs it
10197
listening on a private Unix domain socket and TCP port,
@@ -177,17 +173,17 @@ def __init__(
177173
self.port = port or self._avail_tcpport()
178174
self.server_id = self.port % 4096
179175
self.testrundir = os.path.join(
180-
self.TMPDIR, "%s-%d" % (datadir_prefix or "python-ldap-test", self.port)
176+
self.TMPDIR, f"{datadir_prefix or 'python-ldap-test'}-{self.port}"
181177
)
182178
self._slapd_conf = os.path.join(self.testrundir, "slapd.d")
183179
self._db_directory = os.path.join(self.testrundir, "openldap-data")
184-
self.ldap_uri = "ldap://%s:%d/" % (self.host, self.port)
180+
self.ldap_uri = f"ldap://{self.host}:{self.port}/"
185181
self.configuration_template = configuration_template or SLAPD_CONF_TEMPLATE
186182
self.debug = debug
187183
have_ldapi = hasattr(socket, "AF_UNIX")
188184
if have_ldapi:
189185
ldapi_path = os.path.join(self.testrundir, "ldapi")
190-
self.ldapi_uri = "ldapi://%s" % quote_plus(ldapi_path)
186+
self.ldapi_uri = f"ldapi://{quote_plus(ldapi_path)}"
191187
self.default_ldap_uri = self.ldapi_uri
192188
# use SASL/EXTERNAL via LDAPI when invoking OpenLDAP CLI tools
193189
self.cli_sasl_external = True
@@ -217,7 +213,7 @@ def __exit__(self, exc_type, exc_value, traceback):
217213

218214
@property
219215
def root_dn(self):
220-
return "cn={self.root_cn},{self.suffix}".format(self=self)
216+
return f"cn={self.root_cn},{self.suffix}"
221217

222218
def _find_commands(self):
223219
self.PATH_LDAPADD = self._find_command("ldapadd")
@@ -242,14 +238,13 @@ def _find_command(self, cmd, in_sbin=False):
242238
command = which(cmd, path=path)
243239
if command is None:
244240
raise ValueError(
245-
"Command '{}' not found. Set the {} environment variable to "
246-
"override slapd's search path.".format(cmd, var_name)
241+
f"Command '{cmd}' not found. Set the {var_name} environment variable to "
242+
"override slapd's search path."
247243
)
248244
return command
249245

250246
def _setup_rundir(self):
251-
"""
252-
creates rundir structure
247+
"""Create rundir structure.
253248
254249
for setting up a custom directory structure you have to override
255250
this method
@@ -261,9 +256,7 @@ def _setup_rundir(self):
261256
os.mkdir(dir_name)
262257

263258
def _cleanup_rundir(self):
264-
"""
265-
Recursively delete whole directory specified by `path'
266-
"""
259+
"""Recursively delete whole directory specified by `path'."""
267260
if not os.path.exists(self.testrundir):
268261
return
269262

@@ -279,9 +272,7 @@ def _cleanup_rundir(self):
279272
self.logger.info("cleaned-up %s", self.testrundir)
280273

281274
def _avail_tcpport(self):
282-
"""
283-
find an available port for TCP connection
284-
"""
275+
"""Find an available port for TCP connection."""
285276
sock = socket.socket()
286277
try:
287278
sock.bind((self.host, 0))
@@ -293,8 +284,7 @@ def _avail_tcpport(self):
293284
return port
294285

295286
def _gen_config(self):
296-
"""
297-
generates a slapd.conf and returns it as one string
287+
"""Generate a slapd.conf and returns it as one string.
298288
299289
for generating specific static configuration files you have to
300290
override this method
@@ -315,7 +305,7 @@ def _gen_config(self):
315305
return self.configuration_template % config_dict
316306

317307
def _write_config(self):
318-
"""Loads the slapd.d configuration."""
308+
"""Load the slapd.d configuration."""
319309
self.logger.debug("importing configuration: %s", self._slapd_conf)
320310

321311
self.slapadd(self._gen_config(), ["-n0"])
@@ -347,9 +337,7 @@ def _test_config(self):
347337
self.logger.info("config ok: %s", self._slapd_conf)
348338

349339
def _start_slapd(self):
350-
"""
351-
Spawns/forks the slapd process
352-
"""
340+
"""Spawns/forks the slapd process."""
353341
urls = [self.ldap_uri]
354342
if self.ldapi_uri:
355343
urls.append(self.ldapi_uri)
@@ -386,10 +374,7 @@ def _start_slapd(self):
386374
raise RuntimeError("slapd did not start properly") # pragma: no cover
387375

388376
def start(self):
389-
"""
390-
Starts the slapd server process running, and waits for it to come up.
391-
"""
392-
377+
"""Start the slapd server process running, and waits for it to come up."""
393378
if self._proc is not None:
394379
return
395380

@@ -407,9 +392,7 @@ def start(self):
407392
)
408393

409394
def stop(self):
410-
"""
411-
Stops the slapd server, and waits for it to terminate and cleans up
412-
"""
395+
"""Stop the slapd server, and waits for it to terminate and cleans up."""
413396
if self._proc is not None:
414397
self.logger.debug("stopping slapd with pid %d", self._proc.pid)
415398
self._proc.terminate()
@@ -418,21 +401,19 @@ def stop(self):
418401
atexit.unregister(self.stop)
419402

420403
def restart(self):
421-
"""
422-
Restarts the slapd server with same data
423-
"""
404+
"""Restarts the slapd server with same data."""
424405
self._proc.terminate()
425406
self.wait()
426407
self._start_slapd()
427408

428409
def wait(self):
429-
"""Waits for the slapd process to terminate by itself."""
410+
"""Wait for the slapd process to terminate by itself."""
430411
if self._proc:
431412
self._proc.wait()
432413
self._stopped()
433414

434415
def _stopped(self):
435-
"""Called when the slapd server is known to have terminated"""
416+
"""Is called when the slapd server is known to have terminated."""
436417
if self._proc is not None:
437418
self.logger.info("slapd[%d] terminated", self._proc.pid)
438419
self._proc = None
@@ -479,14 +460,19 @@ def _cli_popen(
479460
self.logger.debug("Run command: %r", " ".join(args))
480461
proc = subprocess.run(args, input=stdin_data, capture_output=True)
481462
self.logger.debug(
482-
"stdin_data=%s", stdin_data.decode("utf-8", errors="replace") if stdin_data else stdin_data
463+
"stdin_data=%s",
464+
stdin_data.decode("utf-8", errors="replace") if stdin_data else stdin_data,
483465
)
484466

485467
if proc.stdout is not None:
486-
self.logger.debug("stdout=%s", proc.stdout.decode("utf-8", errors="replace"))
468+
self.logger.debug(
469+
"stdout=%s", proc.stdout.decode("utf-8", errors="replace")
470+
)
487471

488472
if proc.stderr is not None:
489-
self.logger.debug("stderr=%s", proc.stderr.decode("utf-8", errors="replace"))
473+
self.logger.debug(
474+
"stderr=%s", proc.stderr.decode("utf-8", errors="replace")
475+
)
490476

491477
if proc.returncode not in expected:
492478
raise RuntimeError(
@@ -497,8 +483,7 @@ def _cli_popen(
497483
return proc
498484

499485
def ldapwhoami(self, extra_args=None, expected=0):
500-
"""
501-
Runs ldapwhoami on this slapd instance
486+
"""Run ldapwhoami on this slapd instance.
502487
503488
:param extra_args: Extra argument to pass to *ldapwhoami*.
504489
:param expected: Expected return code. Defaults to `0`.
@@ -511,8 +496,7 @@ def ldapwhoami(self, extra_args=None, expected=0):
511496
)
512497

513498
def ldapadd(self, ldif, extra_args=None, expected=0):
514-
"""
515-
Runs ldapadd on this slapd instance, passing it the ldif content
499+
"""Run ldapadd on this slapd instance, passing it the ldif content.
516500
517501
:param ldif: The ldif content to pass to the *ldapadd* standard input.
518502
:param extra_args: Extra argument to pass to *ldapadd*.
@@ -529,8 +513,7 @@ def ldapadd(self, ldif, extra_args=None, expected=0):
529513
)
530514

531515
def ldapmodify(self, ldif, extra_args=None, expected=0):
532-
"""
533-
Runs ldapadd on this slapd instance, passing it the ldif content
516+
"""Run ldapadd on this slapd instance, passing it the ldif content.
534517
535518
:param ldif: The ldif content to pass to the *ldapmodify* standard input.
536519
:param extra_args: Extra argument to pass to *ldapmodify*.
@@ -547,8 +530,7 @@ def ldapmodify(self, ldif, extra_args=None, expected=0):
547530
)
548531

549532
def ldapdelete(self, dn, recursive=False, extra_args=None, expected=0):
550-
"""
551-
Runs ldapdelete on this slapd instance, deleting 'dn'
533+
"""Run ldapdelete on this slapd instance, deleting 'dn'.
552534
553535
:param dn: The distinguished name of the element to delete.
554536
:param recursive: Whether to delete sub-elements. Defaults to `False`.
@@ -568,8 +550,7 @@ def ldapdelete(self, dn, recursive=False, extra_args=None, expected=0):
568550
)
569551

570552
def ldapsearch(self, filter, searchbase=None, extra_args=None, expected=0):
571-
"""
572-
Runs search on this slapd instance
553+
"""Run search on this slapd instance.
573554
574555
:param filter: The search filter.
575556
:param base: The starting point for the search.
@@ -589,8 +570,7 @@ def ldapsearch(self, filter, searchbase=None, extra_args=None, expected=0):
589570
)
590571

591572
def slapadd(self, ldif, extra_args=None, expected=0):
592-
"""
593-
Runs slapadd on this slapd instance, passing it the ldif content
573+
"""Run slapadd on this slapd instance, passing it the ldif content.
594574
595575
:param ldif: The ldif content to pass to the *slapadd* standard input.
596576
:param extra_args: Extra argument to pass to *slapadd*.
@@ -607,8 +587,7 @@ def slapadd(self, ldif, extra_args=None, expected=0):
607587
)
608588

609589
def slapcat(self, extra_args=None, expected=0):
610-
"""
611-
Runs slapadd on this slapd instance, passing it the ldif content
590+
"""Run slapadd on this slapd instance, passing it the ldif content.
612591
613592
:param extra_args: Extra argument to pass to *slapcat*.
614593
:param expected: Expected return code. Defaults to `0`.
@@ -623,9 +602,7 @@ def slapcat(self, extra_args=None, expected=0):
623602
)
624603

625604
def init_tree(self):
626-
"""
627-
Creates the organization and applicationProcess object.
628-
"""
605+
"""Create the organization and applicationProcess object."""
629606
suffix_dc = self.suffix.split(",")[0][3:]
630607
return self.ldapadd(
631608
"\n".join(

tests/test_slapdobject.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import slapd
21
import pytest
32

3+
import slapd
4+
45

56
def test_nominal_case():
67
server = slapd.Slapd()

0 commit comments

Comments
 (0)