Skip to content

Commit 55c96b9

Browse files
committed
Make SlapdObject a context manager
Allows for automatic cleanup of resources using the with statement. For example: with slapdtest.SlapdObject() as server: server.ldapadd(...) ... When using SlapdObject in a function, it is more convenient and concise than using try/finally pattern.
1 parent adc40d0 commit 55c96b9

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

Lib/slapdtest/_slapdtest.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,10 @@ class SlapdObject(object):
164164
165165
When a reference to an instance of this class is lost, the slapd
166166
server is shut down.
167+
168+
An instance can be used as a context manager. When exiting the context
169+
manager, the slapd server is shut down and the temporary data store is
170+
removed.
167171
"""
168172
slapd_conf_template = SLAPD_CONF_TEMPLATE
169173
database = 'mdb'
@@ -553,6 +557,13 @@ def ldapdelete(self, dn, recursive=False, extra_args=None):
553557
extra_args.append(dn)
554558
self._cli_popen(self.PATH_LDAPDELETE, extra_args=extra_args)
555559

560+
def __enter__(self):
561+
self.start()
562+
return self
563+
564+
def __exit__(self, exc_type, exc_value, traceback):
565+
self.stop()
566+
556567

557568
class SlapdTestCase(unittest.TestCase):
558569
"""

Tests/t_slapdobject.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import unittest
2+
3+
import slapdtest
4+
5+
6+
class TestSlapdObject(unittest.TestCase):
7+
def test_context_manager(self):
8+
with slapdtest.SlapdObject() as server:
9+
self.assertIsNotNone(server._proc)
10+
self.assertIsNone(server._proc)
11+
12+
def test_context_manager_after_start(self):
13+
server = slapdtest.SlapdObject()
14+
server.start()
15+
self.assertIsNotNone(server._proc)
16+
with server:
17+
self.assertIsNotNone(server._proc)
18+
self.assertIsNone(server._proc)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy