Skip to content

Commit

Permalink
Test de zmq_server
Browse files Browse the repository at this point in the history
  • Loading branch information
Bruno Geninatti committed Mar 2, 2018
1 parent 6cabd07 commit 2324737
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 52 deletions.
2 changes: 1 addition & 1 deletion Cardenal/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def check_for_notifications(self, bot, job):
msg = self._zmq_server.msgs_queue.get()
user = users.where((User.id == msg['user_id']) | (User.username == msg['username'])).get()
try:
self.logger("Enviando mensaje a {0}.".format(user.username))
self.logger.info("Enviando mensaje a {0}.".format(user.username))
bot.sendMessage(
user.id,
text=msg['msg']
Expand Down
73 changes: 40 additions & 33 deletions Cardenal/zmq_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ def __init__(self,
self.msgs_queue = Queue()
self._context = zmq.Context()
self._command_socket = self._context.socket(zmq.REP)
self._command_socket.bind("tcp://*:{0}".format(self._command_port))
self._command_poller = zmq.Poller()
self._command_poller.register(self._command_socket)
self._command_poller_timeout = command_poller_timeout
self._msgs_thread = Thread(target=self.check_msgs)
self._msgs_thread = Thread(target=self._keep_checking)

def start(self):
self._command_socket.bind("tcp://*:{0}".format(self._command_port))
self._command_poller.register(self._command_socket)
self._msgs_thread.start()

def stop(self):
Expand All @@ -45,36 +45,43 @@ def check_msgs(self):
Se debe especificar user_id o username. Si ambos están presentes se
usa username
'''
while not self._stop:
socks = self._command_poller.poll(self._command_poller_timeout)
for socket, _ in socks:
try:
msg = socket.recv_json()
if type(msg) is not dict:
raise TypeError
except (json.decoder.JSONDecodeError, TypeError) as e:
socket.send_string(json.dumps({
'status': 500,
'msg': "Error en formato del comando."}))
self.logger.error("ERROR 500: Error en formato del comando.")
continue
if 'msg' not in msg.keys():
socket.send_string(json.dumps({
'status': 501,
'msg': "No se especifico un mensaje para la notificación."
}))
self.logger.error("ERROR 501: No se especifico un mensaje para la notificación.")
continue
msgs = []
socks = self._command_poller.poll(self._command_poller_timeout)
for socket, _ in socks:
try:
msg = socket.recv_json()
if type(msg) is not dict:
raise TypeError
except (json.decoder.JSONDecodeError, TypeError) as e:
socket.send_string(json.dumps({
'status': 500,
'msg': "Error en formato del comando."}))
self.logger.error("ERROR 500: Error en formato del comando.")
continue
if 'msg' not in msg.keys():
socket.send_string(json.dumps({
'status': 501,
'msg': "No se especifico un mensaje para la notificación."
}))
self.logger.error("ERROR 501: No se especifico un mensaje para la notificación.")
continue

if all((k not in ('username', 'usernames', 'user_id', 'users_ids') for k in msg.keys())):
socket.send_string(json.dumps({
'status': 502,
'msg': 'No se especifico ningún destinatario para el ' +
'mensaje.'}))
self.logger.error("ERROR 502: No se especifico ningún destinatario para el mensaje.")
continue
if all((k not in ('username', 'usernames', 'user_id', 'users_ids') for k in msg.keys())):
socket.send_string(json.dumps({
'status': 200,
'msg': "Notificacion creada correctamente"}))
'status': 502,
'msg': 'No se especifico ningún destinatario para el ' +
'mensaje.'}))
self.logger.error("ERROR 502: No se especifico ningún destinatario para el mensaje.")
continue
socket.send_string(json.dumps({
'status': 200,
'msg': "Notificacion creada correctamente"}))
msgs.append(msg)
return msgs

def _keep_checking(self):
while not self._stop:
msgs = self.check_msgs()
for m in msgs:
self.logger.info("Notificacion creada correctamente.")
self.msgs_queue.put(msg)
self.msgs_queue.put(m)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified docs/_misc/ex_01.gif
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/_misc/ex_02.gif
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ For more information please go to section `Clients`
Here we have an example of how to send messages using the client `cardenal-python-client`_::


>> from CardenalClient.client import CardenalCliet
>> from CardenalClient.client import CardenalClient
>> cli = CardenalClient('localhost') # This is because we are running the server localy
>> user_id = 12345 # My telegram ID. Cardenal send you this when you log to the server (go to step 3)
>> username = 'myUsername' # Telegram Username
Expand All @@ -125,7 +125,7 @@ Voila!


.. _ZMQ: http://zeromq.org/
.. _cardenal-python-client: http://github.com
.. _cardenal-python-client: https://github.com/Bgeninatti/cardenal-python-client
.. _BotFather: https://core.telegram.org/bots#6-botfather
.. _`ZMQ lenguage Bindings`: http://zeromq.org/bindings:_start
.. _peewee: http://docs.peewee-orm.com/en/latest/
Expand Down
28 changes: 12 additions & 16 deletions tests/test_zmq.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import unittest
import zmq
from zmq_server import CardenalZmqServer
from Cardenal.zmq_server import CardenalZmqServer


class MockClient(object):
Expand All @@ -18,38 +18,34 @@ def stop(self):

def send_msg(self, msg, user_id=None, username=None):
if user_id is not None:
msg = json.dumps({'msg': msg, 'user_id': user_id})
msg = {'msg': msg, 'user_id': user_id}
elif username is not None:
msg = json.dumps({'msg': msg, 'username': username})
msg = {'msg': msg, 'username': username}
else:
raise ValueError("Se debe especificar username o user_id como" +
"parámetros")

self.socket.send_string(msg)
socks = self.poller.poll(10)
self.socket.send_json(msg)


class ZMQServerTest(unittest.TestCase):

def setUp(self):
self.server = CardenalZmqServer()
self.client = MockClient()

def tearDown(self):
self.server.stop()
self.client.stop()

def test_empty(self):
msgs = self.server.check_msgs()
self.assertEqual(len(msgs), 0)
@classmethod
def setUpClass(cls):
cls.server = CardenalZmqServer()

def test_500_not_json(self):
self.client.socket.send_string("asd")
msgs = self.server.check_msgs()
rta = self.client.socket.recv_json()
self.assertEqual(rta['status'], 500)
@classmethod
def tearDownClass(cls):
cls.server._command_socket.close()
cls.server._context.term()

def test_500_not_dict(self):
def test_500(self):
self.client.socket.send_json("asd")
msgs = self.server.check_msgs()
rta = self.client.socket.recv_json()
Expand Down

0 comments on commit 2324737

Please sign in to comment.