Skip to content

Commit

Permalink
Make SlapdObject a context manager
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Jon Dufresne committed Apr 1, 2018
1 parent adc40d0 commit 55c96b9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Lib/slapdtest/_slapdtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,10 @@ class SlapdObject(object):
When a reference to an instance of this class is lost, the slapd
server is shut down.
An instance can be used as a context manager. When exiting the context
manager, the slapd server is shut down and the temporary data store is
removed.
"""
slapd_conf_template = SLAPD_CONF_TEMPLATE
database = 'mdb'
Expand Down Expand Up @@ -553,6 +557,13 @@ def ldapdelete(self, dn, recursive=False, extra_args=None):
extra_args.append(dn)
self._cli_popen(self.PATH_LDAPDELETE, extra_args=extra_args)

def __enter__(self):
self.start()
return self

def __exit__(self, exc_type, exc_value, traceback):
self.stop()


class SlapdTestCase(unittest.TestCase):
"""
Expand Down
18 changes: 18 additions & 0 deletions Tests/t_slapdobject.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import unittest

import slapdtest


class TestSlapdObject(unittest.TestCase):
def test_context_manager(self):
with slapdtest.SlapdObject() as server:
self.assertIsNotNone(server._proc)
self.assertIsNone(server._proc)

def test_context_manager_after_start(self):
server = slapdtest.SlapdObject()
server.start()
self.assertIsNotNone(server._proc)
with server:
self.assertIsNotNone(server._proc)
self.assertIsNone(server._proc)

0 comments on commit 55c96b9

Please sign in to comment.