Permalink
Browse files

started adding some real tests and had a bit of a tidy up

  • Loading branch information...
1 parent be5896b commit bf5d6760bd0ca87a2dffdebbe83ab67bce21bee5 Jonthan Moss committed Jun 28, 2011
View
@@ -3,3 +3,4 @@
*.pyc
docs/build/*
amity.egg-info
+scripts/consume2.py
View
@@ -5,19 +5,13 @@
import uuid
#Get my IP for events I am sending
-SOCK = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-SOCK.connect(('google.com', 0))
-IP = SOCK.getsockname()[0]
-
+IP_ADDRESS = socket.gethostbyname(socket.gethostname())
class Event(object):
"""
Base event object
"""
- _data = {
- 'values': {},
- 'headers': {}
- }
+ _data = None
def __init__(self, values=None, headers=None):
"""
@@ -29,13 +23,17 @@ def __init__(self, values=None, headers=None):
headers
A dictionary of headers
"""
- self.set_header('from', IP)
+ self._data = {
+ 'values': {},
+ 'headers': {}
+ }
+ self.set_header('from', IP_ADDRESS)
if headers:
for header, value in headers.items():
self.set_header(header, value)
if values:
for key, value in values.items():
- self.set_value(key, value)
+ self.set(key, value)
def set_header(self, header, value):
"""
@@ -52,11 +50,11 @@ def set_header(self, header, value):
self._data['headers'][header] = value
return self
- def get_header(self, header):
+ def get_header(self, header, default=None):
"""
Gets the value of the specified header
"""
- value = None
+ value = default
if header in self._data['headers']:
value = self._data['headers'][header]
return value
@@ -67,7 +65,7 @@ def get_headers(self):
"""
return self._data['headers']
- def set_value(self, key, value):
+ def set(self, key, value):
"""
Sets a value within the event
@@ -82,11 +80,11 @@ def set_value(self, key, value):
self._data['values'][key] = value
return self
- def get_value(self, key):
+ def get(self, key, default=None):
"""
Gets the value of the specified key
"""
- value = None
+ value = default
if key in self._data['values']:
value = self._data['values'][key]
return value
@@ -120,28 +118,12 @@ def __init__(self, connection):
connection
The instance of kombu.connection.BrokerConnection to use
"""
- self._set_connection(connection)
- self.exchange = Exchange('event', 'topic')
-
- def _set_connection(self, connection):
- """
- Arguments:
-
- connection
- The instance of kombu.connection.BrokerConnection to use
- """
- if isinstance(connection, BrokerConnection):
- self.connection = connection
- return self
- else:
- raise Exception("not a kombu.connection.BrokerConnection")
+ self.connection = connection
- def get_connection(self):
- """
- Returns:
- kombu.connection.BrokerConnection
- """
- return self.connection
+ def _get_exchange(self):
+ if self.exchange is None:
+ self.exchange = Exchange('event', 'topic')
+ return self.exchange
def _get_producer(self):
"""
@@ -150,7 +132,7 @@ def _get_producer(self):
if self.producer is None:
channel = self.connection.channel()
self.producer = Producer(channel,
- exchange=self.exchange,
+ exchange=self._get_exchange(),
serializer="json")
return self.producer
@@ -213,7 +195,7 @@ def marshalled_func(body, message):
"""
event = Event()
for key, value in body['values'].items():
- event.set_value(key, value)
+ event.set(key, value)
for header, value in body['headers'].items():
event.set_header(header, value)
func(event)
@@ -286,7 +268,7 @@ def marshalled_func(body, message):
"""
event = Event()
for key, value in body['values'].items():
- event.set_value(key, value)
+ event.set(key, value)
for header, value in body['headers'].items():
event.set_header(header, value)
self._emitter.emit(event.get_header('reply-to'), func(event))
File renamed without changes.
View
@@ -0,0 +1,35 @@
+from mock import Mock
+
+def get_channel():
+ return Mock()
+
+def get_connection():
+ conn = Mock()
+ conn.channel = Mock(return_value=get_channel())
+ return conn
+
+def get_exchange():
+ return Mock()
+
+def get_producer():
+ producer = Mock()
+ producer.publish = Mock()
+ return producer
+
+def on_default(type):
+ raise Exception("%s is not a defined mock type" % type)
+
+TYPES = {
+ "channel": get_channel,
+ "connection": get_connection,
+ "exchange": get_exchange,
+ "producer": get_producer
+}
+
+
+def get_mock(type):
+ func = TYPES.get(type)
+ if func is None:
+ on_default(type)
+ else:
+ return func()
@@ -0,0 +1,58 @@
+import unittest
+from amity.messaging import Emitter, Event
+from amity.tests.mocks import get_mock
+
+
+class EventTests(unittest.TestCase):
+
+ def test_from_header_is_set(self):
+ event = Event()
+ assert event.get_header('from') is not None
+
+ def test_setting_value(self):
+ event = Event()
+ event.set("key", "value")
+ assert event.get("key") == "value"
+ assert event.get("unset_key", "default") == "default"
+
+ def test_setting_header(self):
+ event = Event()
+ event.set_header("key", "value")
+ assert event.get_header("key") == "value"
+ assert event.get_header("unset_key", "default") == "default"
+
+ def test_get_values(self):
+ event = Event()
+ values = event.get_values()
+ assert len(values) == 0
+ event.set("key", "value")
+ values = event.get_values()
+ assert len(values) == 1
+
+ def test_get_headers(self):
+ event = Event()
+ headers = event.get_headers()
+ assert len(headers) == 1
+ event.set_header("key", "value")
+ headers = event.get_headers()
+ assert len(headers) == 2
+
+ def test_data(self):
+ event = Event()
+ data = event.data
+ assert "values" in data
+ assert "headers" in data
+ assert "from" in data["headers"]
+
+
+class EmitterTests(unittest.TestCase):
+
+ def test_emits(self):
+ emitter = Emitter(None)
+ emitter.producer = get_mock("producer")
+ event = Event()
+ emitter.emit('event.test', event)
+ assert emitter.producer.publish.call_count == 1
+
+if __name__ == "__main__":
+ unittest.main()
@@ -45,7 +45,7 @@ And a simple listener::
connection = BrokerConnection('localhost', 'guest', 'guest', '/')
def on_message(event):
- print "%s says: %s" % (event.get_header("from"), event.get_value("msg"))
+ print "%s says: %s" % (event.get_header("from"), event.get("msg"))
listener = Listener(connection)
listener.add_callback("event.something", on_message)
@@ -54,7 +54,7 @@ Emitting a signal is pretty simple::
from amity.messaging import Event, Emitter
from amity.helpers import get_django_connection
- emitter = Emitter(get_djano_connection())
+ emitter = Emitter(get_django_connection())
emitter.emit("event.name", Event())
Ok, so that is still pretty un-interesting but it can get a little more
@@ -65,7 +65,7 @@ on you ecommerce site::
from amity.messaging import Event, Emitter
from amity.helpers import get_django_connection
- emitter = Emitter(get_djano_connection())
+ emitter = Emitter(get_django_connection())
event = Event({"order_name": order.order_number})
emitter.emit("event.name", event)
@@ -77,7 +77,7 @@ better still you could just hook it up to the order classes post_save signal.::
from amity.messaging import Event, Emitter
from amity.helpers import get_django_connection
- EMITTER = Emitter(get_djano_connection())
+ EMITTER = Emitter(get_django_connection())
def emit_order(sender, instance, created, **kwarg):
if created:
View
@@ -1,3 +1,4 @@
amqplib==0.6.1
anyjson==0.3.1
-kombu==1.1.6
+kombu==1.1.6
+mock=0.7.2
View
@@ -4,18 +4,14 @@
@author: mossj
'''
-import os
-import sys
-ROOT_PATH = os.path.dirname(os.path.realpath(__file__ + "/../"))
-sys.path.append(ROOT_PATH)
from amity.messaging import Listener
from kombu.connection import BrokerConnection
connection = BrokerConnection('localhost', 'guest', 'guest', '/')
def lineItemLogger(event):
- print "Message: '%s' FROM %s" % (event.get_value("msg"),
+ print "Message: '%s' FROM %s" % (event.get("msg"),
event.get_header('from'))
c = Listener(connection)
View
@@ -4,12 +4,7 @@
@author: mossj
'''
-import os
-import sys
-ROOT_PATH = os.path.dirname(os.path.realpath(__file__ + "/../"))
-sys.path.append(ROOT_PATH)
-from amity.entity import Event
-from amity.messaging import Emitter
+from amity.messaging import Emitter, Event
from kombu.connection import BrokerConnection
connection = BrokerConnection('localhost', 'guest', 'guest', '/')
@@ -4,12 +4,7 @@
@author: mossj
'''
-import os
-import sys
-ROOT_PATH = os.path.dirname(os.path.realpath(__file__ + "/../"))
-sys.path.append(ROOT_PATH)
-from amity.entity import Event
-from amity.messaging import Requester
+from amity.messaging import Requester, Event
from kombu.connection import BrokerConnection
#import uuid
@@ -19,4 +14,4 @@
r = Requester(connection)
response = r.call('event.reverse', Event({'msg': 'jonathan'}))
-print "Message: %s" % response.get_value("msg")
+print "Message: %s" % response.get("msg")
View
@@ -4,20 +4,15 @@
@author: mossj
'''
-import os
-import sys
-ROOT_PATH = os.path.dirname(os.path.realpath(__file__ + "/../"))
-sys.path.append(ROOT_PATH)
-from amity.entity import Event
-from amity.messaging import Responder
+from amity.messaging import Responder, Event
from kombu.connection import BrokerConnection
connection = BrokerConnection('localhost', 'guest', 'guest', '/')
def responser(event):
- print "replying to %s on %s" % (event.get_value('msg'),
+ print "replying to %s on %s" % (event.get('msg'),
event.get_header("reply-to"))
- response = event.get_value('msg')[::-1]
+ response = event.get('msg')[::-1]
return Event({"msg": response})
c = Responder(connection)
View
@@ -1,12 +0,0 @@
-'''
-Created on Jun 22, 2011
-
-@author: mossj
-'''
-from kombu.connection import BrokerConnection
-
-
-def test_can_connect():
- b = BrokerConnection('localhost', 'guest', 'guest', '/')
- b.connect()
- assert True

0 comments on commit bf5d676

Please sign in to comment.