1+ import atexit
2+ import logging
13import os
24import socket
5+ import subprocess
36import sys
47import time
5- import subprocess
6- import logging
7- import atexit
88from logging .handlers import SysLogHandler
99from shutil import which
1010from urllib .parse import quote_plus
4747
4848
4949def _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
9693class 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 (
0 commit comments