From: Wonko Date: Fri, 17 Dec 2021 11:35:01 +0000 (+0100) Subject: MPDClient: add __enter__/__exit__ to connect/disconnect X-Git-Tag: v0.8.0~9 X-Git-Url: http://git.kaliko.me/?p=python-musicpd.git;a=commitdiff_plain;h=08f23715d963ccdb712133fdceb9e35f62b76561 MPDClient: add __enter__/__exit__ to connect/disconnect --- diff --git a/musicpd.py b/musicpd.py index d96e76a..5824056 100644 --- a/musicpd.py +++ b/musicpd.py @@ -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 --- 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()