[Pkg-mpd-commits] [python-mpd] 149/262: mpd.py refactor timeout settings

Simon McVittie smcv at debian.org
Sun May 22 18:16:40 UTC 2016


This is an automated email from the git hooks/post-receive script.

smcv pushed a commit to branch upstream
in repository python-mpd.

commit 17d524decb21a58998c22934541b59c8db41f96e
Author: Jörg Thalheim <joerg at higgsboson.tk>
Date:   Sun Nov 18 09:50:52 2012 +0100

    mpd.py refactor timeout settings
    
    - replace timeout argument in connect() with timeout property.
    - timeout for fetch_idle() is handled seperately,
      to be conform with the specification: http://www.musicpd.org/doc/protocol/ch03.html
---
 README.md |  8 +++++---
 mpd.py    | 36 +++++++++++++++++++++++++++++-------
 test.py   | 56 +++++++++++++++++++++++++++++++++-----------------------
 3 files changed, 67 insertions(+), 33 deletions(-)

diff --git a/README.md b/README.md
index 184303e..d36587a 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ python-mpd2 is a fork of the python-mpd.
 It is backward compatible to python-mpd, so it could act as drop-in replacement
 (tested with [sonata](http://sonata.berlios.de/)).
 
-Current features list:
+The following features was added:
 
  - python3 support (python2.6 is minimum python version required)
  - support for the upcoming client-to-client protocol
@@ -19,6 +19,7 @@ Current features list:
  - add unit tests
  - documented API to add new commands (see Future Compatible)
  - use unicode strings in all commands (optionally in python2, default in python3 - see Unicode Handling)
+ - configureable timeout
 
 If you like this module, you could try contact the original author <jat at spatialrift.net> or
 join the discussion on the [issue tracker](http://jatreuman.indefero.net/p/python-mpd/issues/7/)
@@ -94,8 +95,9 @@ The client library can be used as follows:
 
 ```python
 client = mpd.MPDClient()           # create client object
-client.connect("localhost", 6600,  # connect to localhost:6600
-                timeout=10)        # optional timeout in seconds (floats allowed), default: None
+client.timeout = 10                # network timeout in seconds (floats allowed), default: None
+client.idletimeout = None          # timeout for fetching the result of the idle command is handled seperat, default: None
+client.connect("localhost", 6600)  # connect to localhost:6600
 print(client.mpd_version)          # print the mpd version
 print(client.find("any", "house")) # print result of the command "find any house"
 client.close()                     # send the close command
diff --git a/mpd.py b/mpd.py
index b61c385..9f1f50c 100644
--- a/mpd.py
+++ b/mpd.py
@@ -17,6 +17,7 @@
 
 import sys
 import socket
+import warnings
 from collections import Callable
 
 HELLO_PREFIX = "OK MPD "
@@ -65,7 +66,7 @@ _commands = {
     # Status Commands
     "clearerror":         "_fetch_nothing",
     "currentsong":        "_fetch_object",
-    "idle":               "_fetch_list",
+    "idle":               "_fetch_idle",
     "noidle":             None,
     "status":             "_fetch_object",
     "stats":              "_fetch_object",
@@ -342,6 +343,12 @@ class MPDClient(object):
     def _fetch_changes(self):
         return self._fetch_objects(["cpos"])
 
+    def _fetch_idle(self):
+        self._sock.settimeout(self.idletimeout)
+        ret = self._fetch_list()
+        self._sock.settimeout(self._timeout)
+        return ret
+
     def _fetch_songs(self):
         return self._fetch_objects(["file"])
 
@@ -382,16 +389,16 @@ class MPDClient(object):
         self._rfile = _NotConnected()
         self._wfile = _NotConnected()
 
-    def _connect_unix(self, path, timeout):
+    def _connect_unix(self, path):
         if not hasattr(socket, "AF_UNIX"):
             raise ConnectionError("Unix domain sockets not supported "
                                   "on this platform")
         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-        sock.settimeout(timeout)
+        sock.settimeout(self.timeout)
         sock.connect(path)
         return sock
 
-    def _connect_tcp(self, host, port, timeout):
+    def _connect_tcp(self, host, port):
         try:
             flags = socket.AI_ADDRCONFIG
         except AttributeError:
@@ -405,7 +412,7 @@ class MPDClient(object):
             try:
                 sock = socket.socket(af, socktype, proto)
                 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
-                sock.settimeout(timeout)
+                sock.settimeout(self.timeout)
                 sock.connect(sa)
                 return sock
             except socket.error as e:
@@ -417,13 +424,28 @@ class MPDClient(object):
         else:
             raise ConnectionError("getaddrinfo returns an empty list")
 
+    def _settimeout(self, timeout):
+        self._timeout = timeout
+        if self._sock != None:
+            self._sock.settimeout(timeout)
+    def _gettimeout(self):
+        return self._timeout
+    timeout = property(_gettimeout, _settimeout)
+    _timeout = None
+    idletimeout = None
+
     def connect(self, host, port, timeout=None):
         if self._sock is not None:
             raise ConnectionError("Already connected")
+        if timeout != None:
+            warnings.warn("The timeout parameter in connect() is deprecated! "
+                          "Use MPDClient.timeout = yourtimeout instead.",
+                          DeprecationWarning)
+            self.timeout = timeout
         if host.startswith("/"):
-            self._sock = self._connect_unix(host, timeout)
+            self._sock = self._connect_unix(host)
         else:
-            self._sock = self._connect_tcp(host, port, timeout)
+            self._sock = self._connect_tcp(host, port)
         self._rfile = self._sock.makefile("r")
         self._wfile = self._sock.makefile("w")
         try:
diff --git a/test.py b/test.py
index fdcf3b1..13e3275 100755
--- a/test.py
+++ b/test.py
@@ -6,6 +6,7 @@ import types
 import sys
 from socket import error as SocketError
 import mpd
+import warnings
 
 try:
     # is required for python2.6
@@ -20,6 +21,9 @@ except ImportError:
         print("Please install unittest2 from pypi to run tests!")
         sys.exit(1)
 
+# show deprecation warnings
+warnings.simplefilter('default')
+
 def setup_environment():
     # Alternate this to your setup
     # Make sure you have at least one song on your playlist
@@ -37,6 +41,20 @@ def setup_environment():
 
 setup_environment()
 
+def createMpdClient():
+    global TEST_MPD_HOST, TEST_MPD_PORT, TEST_MPD_PASSWORD
+    client = mpd.MPDClient()
+    try:
+        client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
+        commands = client.commands()
+    except SocketError as e:
+        raise Exception("Can't connect mpd! Start it or check the configuration: %s" % e)
+    if TEST_MPD_PASSWORD != None:
+        try:
+            client.password(TEST_MPD_PASSWORD)
+        except mpd.CommandError as e:
+            raise Exception("Fail to authenticate to mpd.")
+    return client
 
 class TestMPDClient(unittest.TestCase):
 
@@ -44,25 +62,10 @@ class TestMPDClient(unittest.TestCase):
 
     @classmethod
     def setUpClass(self):
-        global TEST_MPD_HOST, TEST_MPD_PORT, TEST_MPD_PASSWORD
-        self.client = mpd.MPDClient()
-        self.idleclient = mpd.MPDClient()
-        try:
-            self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
-            self.idleclient.connect(TEST_MPD_HOST, TEST_MPD_PORT)
-            self.commands = self.client.commands()
-        except SocketError as e:
-            raise Exception("Can't connect mpd! Start it or check the configuration: %s" % e)
-        if TEST_MPD_PASSWORD != None:
-            try:
-                self.client.password(TEST_MPD_PASSWORD)
-                self.idleclient.password(TEST_MPD_PASSWORD)
-            except mpd.CommandError as e:
-                raise Exception("Fail to authenticate to mpd.")
+        self.client = createMpdClient()
     @classmethod
     def tearDownClass(self):
         self.client.disconnect()
-        self.idleclient.disconnect()
     def test_metaclass_commands(self):
         # just some random functions
         self.assertTrue(hasattr(self.client, "commands"))
@@ -108,13 +111,13 @@ class TestMPDClient(unittest.TestCase):
                 self.assertIsInstance(song, dict)
         self.client.iterate = False
     def test_idle(self):
+        idleclient = createMpdClient()
         # clean event mask
-        self.idleclient.idle()
-
-        self.idleclient.send_idle()
+        idleclient.idle()
+        idleclient.send_idle()
         # new event
         self.client.update()
-        event = self.idleclient.fetch_idle()
+        event = idleclient.fetch_idle()
         self.assertEqual(event, ['update'])
     def test_add_and_remove_command(self):
         self.client.add_command("awesome command", mpd.MPDClient._fetch_nothing)
@@ -197,15 +200,22 @@ class TestMPDClient(unittest.TestCase):
     def test_numbers_as_command_args(self):
         res = self.client.find("file", 1)
 
-    def test_empty_callbacks(self):
+    def test_commands_without_callbacks(self):
         self.client.close()
         self.client._reset()
         self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
 
     def test_timeout(self):
         self.client.disconnect()
-        self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT, timeout=5)
-        self.assertEqual(self.client._sock.gettimeout(), 5)
+        self.client.timeout = 1
+        self.assertEqual(self.client.timeout, 1)
+        with warnings.catch_warnings(record=True) as w:
+            self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT, timeout=5)
+            self.assertEqual(self.client._sock.gettimeout(), 5)
+            self.assertEqual(len(w), 1)
+
+        self.client.timeout = None
+        self.assertEqual(self.client._sock.gettimeout(), None)
 
     def test_connection_lost(self):
         client = mpd.MPDClient()

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-mpd/python-mpd.git



More information about the Pkg-mpd-commits mailing list