MPDClient: add __enter__/__exit__ to connect/disconnect
authorWonko <wonko@hanstool.org>
Fri, 17 Dec 2021 11:35:01 +0000 (12:35 +0100)
committerWonko <wonko@hanstool.org>
Fri, 17 Dec 2021 11:42:40 +0000 (12:42 +0100)
musicpd.py
test.py

index d96e76a..5824056 100644 (file)
@@ -726,6 +726,13 @@ class MPDClient:
             self._sock.close()
         self._reset()
 
+    def __enter__(self):
+        self.connect()
+        return self
+
+    def __exit__(self, exception_type, exception_value, exception_traceback):
+        self.disconnect()
+
     def fileno(self):
         """Return the socket’s file descriptor (a small integer).
         This is useful with :py:obj:`select.select`.
diff --git a/test.py b/test.py
index 2c5094d..c911a57 100755 (executable)
--- a/test.py
+++ b/test.py
@@ -593,6 +593,18 @@ class testException(unittest.TestCase):
             with self.assertRaises(musicpd.CommandError):
                 cli.find('(album == "foo\nbar")')
 
+class testContextManager(unittest.TestCase):
+
+    def test_enter_exit(self):
+        os.environ['MPD_HOST'] = '@abstract'
+        with mock.patch('musicpd.socket') as socket_mock:
+            sock = mock.MagicMock(name='socket')
+            socket_mock.socket.return_value = sock
+            cli = musicpd.MPDClient()
+            with cli as c:
+                sock.connect.assert_called_with('\0abstract')
+                sock.close.assert_not_called()
+            sock.close.assert_called()
 
 if __name__ == '__main__':
     unittest.main()