Skip to content

Commit

Permalink
pubsub: improve error reporting if caller forgets to subscribe
Browse files Browse the repository at this point in the history
This is an easy mistake to make -- at least, I keep making it. It
formerly resulted in a confusing crash, "AttributeError: 'NoneType'
object has no attribute 'can_read'", from parse_response(). I have had
to dig into the redis-py source code more than once to figure out what
went wrong.

With this patch, it still crashes, but with a clearer error that
clarifies what the calling code forgot to do.

Fixes issue redis#716.
  • Loading branch information
gward committed Jun 12, 2016
1 parent 3bdf81a commit 86ec8d0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
4 changes: 4 additions & 0 deletions redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2226,6 +2226,10 @@ def _execute(self, connection, command, *args):
def parse_response(self, block=True, timeout=0):
"Parse the response from a publish/subscribe command"
connection = self.connection
if connection is None:
raise RuntimeError(
'pubsub connection not set: '
'did you forget to call subscribe() or psubscribe()?')
if not block and not connection.can_read(timeout=timeout):
return None
return self._execute(connection, connection.read_response)
Expand Down
8 changes: 8 additions & 0 deletions tests/test_pubsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,14 @@ def test_unicode_pattern_message_handler(self, r):
assert self.message == make_message('pmessage', channel,
'test message', pattern=pattern)

def test_get_message_without_subscribe(self, r):
p = r.pubsub()
with pytest.raises(RuntimeError) as info:
p.get_message()
expect = ('connection not set: '
'did you forget to call subscribe() or psubscribe()?')
assert expect in info.exconly()


class TestPubSubAutoDecoding(object):
"These tests only validate that we get unicode values back"
Expand Down

0 comments on commit 86ec8d0

Please sign in to comment.