1
+ import atexit
2
+ import logging
1
3
import os
2
4
import socket
5
+ import subprocess
3
6
import sys
4
7
import time
5
- import subprocess
6
- import logging
7
- import atexit
8
8
from logging .handlers import SysLogHandler
9
9
from shutil import which
10
10
from urllib .parse import quote_plus
47
47
48
48
49
49
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. """
51
51
directories = path .split (os .pathsep )
52
52
if sys .platform != "win32" :
53
53
for sbin in "/usr/local/sbin" , "/sbin" , "/usr/sbin" :
@@ -62,10 +62,7 @@ def combinedlogger(
62
62
syslogger_format = "%(levelname)s %(message)s" ,
63
63
consolelogger_format = "%(asctime)s %(levelname)s %(message)s" ,
64
64
):
65
- """
66
- Returns a combined SysLogHandler/StreamHandler logging instance
67
- with formatters
68
- """
65
+ """Return a combined SysLogHandler/StreamHandler logging instance with formatters."""
69
66
if "LOGLEVEL" in os .environ :
70
67
log_level = os .environ ["LOGLEVEL" ]
71
68
try :
@@ -94,8 +91,7 @@ def combinedlogger(
94
91
95
92
96
93
class Slapd :
97
- """
98
- Controller class for a slapd instance, OpenLDAP's server.
94
+ """Controller class for a slapd instance, OpenLDAP's server.
99
95
100
96
This class creates a temporary data store for slapd, runs it
101
97
listening on a private Unix domain socket and TCP port,
@@ -177,17 +173,17 @@ def __init__(
177
173
self .port = port or self ._avail_tcpport ()
178
174
self .server_id = self .port % 4096
179
175
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 } "
181
177
)
182
178
self ._slapd_conf = os .path .join (self .testrundir , "slapd.d" )
183
179
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 } /"
185
181
self .configuration_template = configuration_template or SLAPD_CONF_TEMPLATE
186
182
self .debug = debug
187
183
have_ldapi = hasattr (socket , "AF_UNIX" )
188
184
if have_ldapi :
189
185
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 )} "
191
187
self .default_ldap_uri = self .ldapi_uri
192
188
# use SASL/EXTERNAL via LDAPI when invoking OpenLDAP CLI tools
193
189
self .cli_sasl_external = True
@@ -217,7 +213,7 @@ def __exit__(self, exc_type, exc_value, traceback):
217
213
218
214
@property
219
215
def root_dn (self ):
220
- return "cn={self.root_cn},{self.suffix}" . format ( self = self )
216
+ return f "cn={ self .root_cn } ,{ self .suffix } "
221
217
222
218
def _find_commands (self ):
223
219
self .PATH_LDAPADD = self ._find_command ("ldapadd" )
@@ -242,14 +238,13 @@ def _find_command(self, cmd, in_sbin=False):
242
238
command = which (cmd , path = path )
243
239
if command is None :
244
240
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."
247
243
)
248
244
return command
249
245
250
246
def _setup_rundir (self ):
251
- """
252
- creates rundir structure
247
+ """Create rundir structure.
253
248
254
249
for setting up a custom directory structure you have to override
255
250
this method
@@ -261,9 +256,7 @@ def _setup_rundir(self):
261
256
os .mkdir (dir_name )
262
257
263
258
def _cleanup_rundir (self ):
264
- """
265
- Recursively delete whole directory specified by `path'
266
- """
259
+ """Recursively delete whole directory specified by `path'."""
267
260
if not os .path .exists (self .testrundir ):
268
261
return
269
262
@@ -279,9 +272,7 @@ def _cleanup_rundir(self):
279
272
self .logger .info ("cleaned-up %s" , self .testrundir )
280
273
281
274
def _avail_tcpport (self ):
282
- """
283
- find an available port for TCP connection
284
- """
275
+ """Find an available port for TCP connection."""
285
276
sock = socket .socket ()
286
277
try :
287
278
sock .bind ((self .host , 0 ))
@@ -293,8 +284,7 @@ def _avail_tcpport(self):
293
284
return port
294
285
295
286
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.
298
288
299
289
for generating specific static configuration files you have to
300
290
override this method
@@ -315,7 +305,7 @@ def _gen_config(self):
315
305
return self .configuration_template % config_dict
316
306
317
307
def _write_config (self ):
318
- """Loads the slapd.d configuration."""
308
+ """Load the slapd.d configuration."""
319
309
self .logger .debug ("importing configuration: %s" , self ._slapd_conf )
320
310
321
311
self .slapadd (self ._gen_config (), ["-n0" ])
@@ -347,9 +337,7 @@ def _test_config(self):
347
337
self .logger .info ("config ok: %s" , self ._slapd_conf )
348
338
349
339
def _start_slapd (self ):
350
- """
351
- Spawns/forks the slapd process
352
- """
340
+ """Spawns/forks the slapd process."""
353
341
urls = [self .ldap_uri ]
354
342
if self .ldapi_uri :
355
343
urls .append (self .ldapi_uri )
@@ -386,10 +374,7 @@ def _start_slapd(self):
386
374
raise RuntimeError ("slapd did not start properly" ) # pragma: no cover
387
375
388
376
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."""
393
378
if self ._proc is not None :
394
379
return
395
380
@@ -407,9 +392,7 @@ def start(self):
407
392
)
408
393
409
394
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."""
413
396
if self ._proc is not None :
414
397
self .logger .debug ("stopping slapd with pid %d" , self ._proc .pid )
415
398
self ._proc .terminate ()
@@ -418,21 +401,19 @@ def stop(self):
418
401
atexit .unregister (self .stop )
419
402
420
403
def restart (self ):
421
- """
422
- Restarts the slapd server with same data
423
- """
404
+ """Restarts the slapd server with same data."""
424
405
self ._proc .terminate ()
425
406
self .wait ()
426
407
self ._start_slapd ()
427
408
428
409
def wait (self ):
429
- """Waits for the slapd process to terminate by itself."""
410
+ """Wait for the slapd process to terminate by itself."""
430
411
if self ._proc :
431
412
self ._proc .wait ()
432
413
self ._stopped ()
433
414
434
415
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. """
436
417
if self ._proc is not None :
437
418
self .logger .info ("slapd[%d] terminated" , self ._proc .pid )
438
419
self ._proc = None
@@ -479,14 +460,19 @@ def _cli_popen(
479
460
self .logger .debug ("Run command: %r" , " " .join (args ))
480
461
proc = subprocess .run (args , input = stdin_data , capture_output = True )
481
462
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 ,
483
465
)
484
466
485
467
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
+ )
487
471
488
472
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
+ )
490
476
491
477
if proc .returncode not in expected :
492
478
raise RuntimeError (
@@ -497,8 +483,7 @@ def _cli_popen(
497
483
return proc
498
484
499
485
def ldapwhoami (self , extra_args = None , expected = 0 ):
500
- """
501
- Runs ldapwhoami on this slapd instance
486
+ """Run ldapwhoami on this slapd instance.
502
487
503
488
:param extra_args: Extra argument to pass to *ldapwhoami*.
504
489
:param expected: Expected return code. Defaults to `0`.
@@ -511,8 +496,7 @@ def ldapwhoami(self, extra_args=None, expected=0):
511
496
)
512
497
513
498
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.
516
500
517
501
:param ldif: The ldif content to pass to the *ldapadd* standard input.
518
502
:param extra_args: Extra argument to pass to *ldapadd*.
@@ -529,8 +513,7 @@ def ldapadd(self, ldif, extra_args=None, expected=0):
529
513
)
530
514
531
515
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.
534
517
535
518
:param ldif: The ldif content to pass to the *ldapmodify* standard input.
536
519
:param extra_args: Extra argument to pass to *ldapmodify*.
@@ -547,8 +530,7 @@ def ldapmodify(self, ldif, extra_args=None, expected=0):
547
530
)
548
531
549
532
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'.
552
534
553
535
:param dn: The distinguished name of the element to delete.
554
536
: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):
568
550
)
569
551
570
552
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.
573
554
574
555
:param filter: The search filter.
575
556
:param base: The starting point for the search.
@@ -589,8 +570,7 @@ def ldapsearch(self, filter, searchbase=None, extra_args=None, expected=0):
589
570
)
590
571
591
572
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.
594
574
595
575
:param ldif: The ldif content to pass to the *slapadd* standard input.
596
576
:param extra_args: Extra argument to pass to *slapadd*.
@@ -607,8 +587,7 @@ def slapadd(self, ldif, extra_args=None, expected=0):
607
587
)
608
588
609
589
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.
612
591
613
592
:param extra_args: Extra argument to pass to *slapcat*.
614
593
:param expected: Expected return code. Defaults to `0`.
@@ -623,9 +602,7 @@ def slapcat(self, extra_args=None, expected=0):
623
602
)
624
603
625
604
def init_tree (self ):
626
- """
627
- Creates the organization and applicationProcess object.
628
- """
605
+ """Create the organization and applicationProcess object."""
629
606
suffix_dc = self .suffix .split ("," )[0 ][3 :]
630
607
return self .ldapadd (
631
608
"\n " .join (
0 commit comments