Commit 443d3b35 authored by Alexander Lercher's avatar Alexander Lercher

Trace Retrieval: unit tests for message handling

parent fca98b09
**/__pycache__
**/.vscode
*.log
\ No newline at end of file
......@@ -13,11 +13,13 @@ LOGGER = logging.getLogger(__name__)
#############################
import connexion
from db.MongoRepository import MongoRepository
from messaging.MessageHandler import MessageHandler
from messaging.ReconnectingMessageManager import ReconnectingMessageManager
# init message handler
message_handler = MessageHandler()
message_handler = MessageHandler(MongoRepository(), ReconnectingMessageManager.getInstance())
def message_received_callback(channel, method, properties, body):
message_handler.handle_generic(body)
......
from db.MongoRepository import MongoRepository
from messaging.ReconnectingMessageManager import ReconnectingMessageManager
import json
import logging
LOGGER = logging.getLogger(__name__)
class MessageHandler:
MSG_NOT_JSON = "Message is not in JSON format and is ignored"
MSG_NO_TYPE = "Message has no type field and is ignored"
MSG_NOT_PROCESSED = "Message Type could not be processed"
MSG_TRACE_PROCESSED = "Message handled as blockchain-transaction"
_mongo_repo = None
_message_sender = None
def __init__(self):
self._mongo_repo = MongoRepository()
self._init_message_sender()
def _init_message_sender(self):
self._message_sender = ReconnectingMessageManager.getInstance()
def __init__(self, mongo_repo, message_sender):
self._mongo_repo = mongo_repo
self._message_sender = message_sender
self._message_sender.create_message_destination('datahub', 'direct')
def handle_generic(self, body):
LOGGER.info(f"Received message: {body}")
result = None
message = None
try:
message = json.loads(body)
except ValueError:
LOGGER.warning("Message is not in JSON format and is ignored")
return
except (ValueError, TypeError):
result = self.MSG_NOT_JSON
LOGGER.warning(result)
return result
if not 'type' in message:
LOGGER.warning("Message has no type field and is ignored")
return
result = self.MSG_NO_TYPE
LOGGER.warning(result)
return result
if message['type'] == 'blockchain-transaction':
self.handle_blockchain_transaction(message['content'])
result = self.MSG_TRACE_PROCESSED
else:
LOGGER.info("Message Type could not be processed")
result = self.MSG_NOT_PROCESSED
LOGGER.info(result)
return result
def handle_blockchain_transaction(self, transaction):
self._mongo_repo.insert_trace(transaction)
......
# add modules folder to interpreter path
import sys
import os
modules_paths = ['../app/', '../../../modules/']
for path in modules_paths:
if os.path.exists(path):
sys.path.insert(1, path)
print(f"added {path}")
import unittest
import manage_sys_paths
import json
from messaging.MessageHandler import MessageHandler
class DummyMongoRepo:
'''Dummy class to be used for testing the MessageHandler'''
last_trace = None
def insert_trace(self, trace):
self.last_trace = trace
class DummyMessageSender:
'''Dummy class to be used for testing the MessageHandler'''
last_message = {}
def create_message_destination(self, exch, exch_type):
pass
def send_message(self, exch, key, mess):
self.last_message = {'ex': exch, 'key': key, 'msg': mess}
class Test_MessageHandler(unittest.TestCase):
handler = None
repo = None
msg_sender = None
def setUp(self):
self.repo = DummyMongoRepo()
self.msg_sender = DummyMessageSender()
self.handler = MessageHandler(self.repo, self.msg_sender)
def test_handleGeneric_emptyMessage_NotJsonError(self):
res = self.handler.handle_generic('')
self.assertEqual(self.handler.MSG_NOT_JSON, res)
def test_handleGeneric_noneMessage_NotJsonError(self):
res = self.handler.handle_generic(None)
self.assertEqual(self.handler.MSG_NOT_JSON, res)
def test_handleGeneric_emptyJson1_NoTypeFieldError(self):
message = json.dumps({})
res = self.handler.handle_generic(message)
self.assertEqual(self.handler.MSG_NO_TYPE, res)
def test_handleGeneric_emptyJson2_NoTypeFieldError(self):
message = json.dumps('')
res = self.handler.handle_generic(message)
self.assertEqual(self.handler.MSG_NO_TYPE, res)
def test_handleGeneric_missingTypeJson_NoTypeFieldError(self):
message = json.dumps({'test': 'content'})
res = self.handler.handle_generic(message)
self.assertEqual(self.handler.MSG_NO_TYPE, res)
def test_handleGeneric_randomType1_NotProcessed(self):
message = json.dumps({'type': ''})
res = self.handler.handle_generic(message)
self.assertEqual(self.handler.MSG_NOT_PROCESSED, res)
def test_handleGeneric_randomType2_NotProcessed(self):
message = json.dumps({'type': 'test'})
res = self.handler.handle_generic(message)
self.assertEqual(self.handler.MSG_NOT_PROCESSED, res)
def test_handleGeneric_randomTypeWithOtherField_NotProcessed(self):
message = json.dumps({'type': 'test', 'other': 'content'})
res = self.handler.handle_generic(message)
self.assertEqual(self.handler.MSG_NOT_PROCESSED, res)
def _get_valid_message(self) -> str:
message_values = \
{ 'type': 'blockchain-transaction',
'content':
{
"ApplicationType": "string",
"Metadata": {},
"ResourceIds": "string",
"ResourceMd5": "string",
"ResourceState": "string",
"Timestamp": "2019-08-27T14:00:48.587Z",
"TransactionFrom": "string",
"TransactionFromLatLng": "string",
"TransactionId": "string",
"TransactionTo": "string",
"TransactionToLatLng": "string",
"TransferredAsset": "string"
}
}
return json.dumps(message_values)
def test_handleGeneric_correctTraceContent_ProcessedResult(self):
res = self.handler.handle_generic(self._get_valid_message())
self.assertEqual(self.handler.MSG_TRACE_PROCESSED, res)
def test_handleGeneric_correctTraceContent_AddedToRepo(self):
msg = self._get_valid_message()
res = self.handler.handle_generic(msg)
trace = json.loads(msg)['content']
self.assertEqual(trace, self.repo.last_trace)
def test_handleGeneric_correctTraceContent_NotificationSentCorrectly(self):
msg = self._get_valid_message()
res = self.handler.handle_generic(msg)
self.assertEqual('datahub', self.msg_sender.last_message['ex'])
self.assertEqual('semantic-linking', self.msg_sender.last_message['key'])
self.assertEqual(json.dumps({'type': 'new-traces-available'}), self.msg_sender.last_message['msg'])
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment