[tor-commits] [stem/master] Adding a ControlMessage.from_str() function

atagar at torproject.org atagar at torproject.org
Sat Feb 9 20:38:48 UTC 2013


commit 5f8b7b4231bcda7f69296821aa6417fd3e2ce5f3
Author: Damian Johnson <atagar at torproject.org>
Date:   Sat Feb 9 12:35:11 2013 -0800

    Adding a ControlMessage.from_str() function
    
    In discussions with Mike about using stem for txtorcon a major use has been
    response parsing. Using stem for this is dead easy, but requires a hack. Adding
    a function to negate the need for hackery.
---
 stem/response/__init__.py |   14 ++++++++++++++
 test/mocking.py           |    6 ++----
 2 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/stem/response/__init__.py b/stem/response/__init__.py
index 11eed0a..f4c9694 100644
--- a/stem/response/__init__.py
+++ b/stem/response/__init__.py
@@ -37,6 +37,7 @@ __all__ = [
 ]
 
 import re
+import StringIO
 import threading
 
 import stem.socket
@@ -124,6 +125,19 @@ class ControlMessage(object):
   never empty.
   """
 
+  def from_str(content):
+    """
+    Provides a ControlMessage for the given content.
+
+    :param str content: message to construct the message from
+
+    :returns: stem.response.ControlMessage instance
+    """
+
+    return stem.socket.recv_message(StringIO.StringIO(content))
+
+  from_str = staticmethod(from_str)
+
   def __init__(self, parsed_content, raw_content):
     if not parsed_content:
       raise ValueError("ControlMessages can't be empty")
diff --git a/test/mocking.py b/test/mocking.py
index 6472659..f1e863d 100644
--- a/test/mocking.py
+++ b/test/mocking.py
@@ -24,7 +24,7 @@ calling :func:`test.mocking.revert_mocking`.
     raise_exception - raises an exception when called
 
   Instance Constructors
-    get_message                     - stem.socket.ControlMessage
+    get_message                     - stem.response.ControlMessage
     get_protocolinfo_response       - stem.response.protocolinfo.ProtocolInfoResponse
 
     stem.descriptor.server_descriptor
@@ -51,7 +51,6 @@ import base64
 import hashlib
 import inspect
 import itertools
-import StringIO
 
 import stem.descriptor.extrainfo_descriptor
 import stem.descriptor.networkstatus
@@ -59,7 +58,6 @@ import stem.descriptor.router_status_entry
 import stem.descriptor.server_descriptor
 import stem.prereq
 import stem.response
-import stem.socket
 
 # Once we've mocked a function we can't rely on its __module__ or __name__
 # attributes, so instead we associate a unique 'mock_id' attribute that maps
@@ -530,7 +528,7 @@ def get_message(content, reformat = True):
 
     content = content.replace("\n", "\r\n")
 
-  return stem.socket.recv_message(StringIO.StringIO(content))
+  return stem.response.ControlMessage.from_str(content)
 
 
 def get_protocolinfo_response(**attributes):



More information about the tor-commits mailing list