]> kaliko git repositories - python-musicpd.git/commitdiff
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 d96e76a54387fcfb7d6ac8db9be83540252edf83..5824056aac4c364c71943e08a06cc2d5c84334ad 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 2c5094d9106296911223a1d3220c4213380d0f25..c911a57319e6a24081a05a8e16558a67c3ad71fe 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()