Пример #1
0
 def test__init__(self):
     blankMessage = Message()
     fullMessage = Message(self.actor, self.verb, self.object,
                            self.result, self.speechAct, self.context,
                            self.timestamp, self.theId)
     self.assertIsInstance(blankMessage, Message)
     self.assertIsInstance(fullMessage, Message)
Пример #2
0
 def sendKCScore(self, kcName, score, relevance):
     if relevance == None:
         relevance = 1.0
     relevance = self.clampToUnitValue(relevance)
     score = self.clampToUnitValue(score)
     msg = Message(self._userId, KC_SCORE_VERB, kcName, score)
     msg.setContextValue(KC_RELEVANCE_KEY, relevance)
     self.sendLoggingMessage(msg)
Пример #3
0
 def _sendMetricMessage(self, verb, value, evidence, stepId, clampToUnit):
     if evidence == None:
         evidence = []
     if clampToUnit:
         value = self.clampToUnitValue(value)
     msg = Message(self._userId, verb, evidence, value)
     msg.setContextValue(STEP_ID_KEY, stepId)
     self.sendLoggingMessage(msg)
 def _dumpLog(self, msg):
     incomingMsg = IncomingMessage(rawMessage=serializeObject(msg))
     allMessages = incomingMsg.find_all()
     attrs = [log.rawMessage for log in allMessages]
     joinedMessage = ""
     #joinedMessage = joinedMessage.join(attrs)
     outMsg = Message("DBLoggingService", "Dump Logs", "To Client", joinedMessage)
     outMsg.setContextValue("sessionId", msg.getContextValue("sessionId", None))
     outMsg.setContextValue("sid", msg.getContextValue("sid", None))
     self.sendMessage(outMsg)
 def receiveMessage(self, msg):
     super(RecommenderMessaging, self).receiveMessage(msg)
     #depending on the content of the message react differently
     logInfo('Entering Recommender.receiveMessage', 5)
     
     if self.recommender.taskASSISTmentsDictionary is None:
         self.recommender.taskASSISTmentsDictionary = self.recommender.populateTaskAssistmentsDictionary() 
     
     if (msg.getSpeechAct() == REQUEST_ACT and
         msg.getVerb() == RECOMMENDED_TASKS_VERB):
         outMsg = Message(None, MASTERY_VERB, msg.getActor(), msg.getObject(), REQUEST_ACT)
         #TODO: Replace with the ability to store context w/ the request in the base recommender class
         outMsg.setContextValue(self.ORIGINAL_MESSAGE_KEY, msg)
         self._makeRequest(outMsg, self.studentModelCallBack)
Пример #6
0
 def setUp(self):
     self.actor = "AnActor"
     self.object = "AnObject"
     self.verb = "AVerb"
     self.result = "Result"
     self.speechAct = CONFIRM_ACT
     self.contextKey = "SimpleContext"
     self.contextVal = 0
     self.context = {self.contextKey : self.contextVal}
     self.timestamp = time()
     self.theId = uuid4()
     self.blankMessage = Message()
     self.message = Message(self.actor, self.verb, self.object,
                            self.result, self.speechAct, self.context,
                            self.timestamp, self.theId)
Пример #7
0
 def sendCompletedStep(self, stepId, isComplete):
     if isComplete == None:
         isComplete = 1.0
     isComplete = self.clampToUnitValue(isComplete)
     msg = Message(self._userId, COMPLETED_STEP_VERB, stepId,
                   1.0 * isComplete)
     self.sendLoggingMessage(msg)
Пример #8
0
 def sendCompletedAllSteps(self, percentComplete):
     if percentComplete == None:
         percentComplete = 1.0
     percentComplete = self.clampToUnitValue(percentComplete)
     msg = Message(self._userId, COMPLETED_ALL_STEPS_VERB, self._taskId,
                   percentComplete * 1.0)
     self.sendLoggingMessage(msg)
Пример #9
0
    def studentModelCallBack(self, msg, oldMsg):
        logInfo("Entering Recommender.studentModelCallback", 5)

        #hack instrumentation
        student = self.recommender.retrieveStudentFromCacheOrDB(
            msg.getObject(), None, True)
        #logInfo("dbStudentRecord = {0}".format(student), 6)
        serializableStudent = student.toSerializable()
        logInfo(
            "student record = {0}".format(
                serializableStudent.saveToSerialized()), 2)

        # Make sure that it is the right student's score for the request
        recMsg = oldMsg.getContextValue(self.ORIGINAL_MESSAGE_KEY, Message())
        if (msg.getVerb() == MASTERY_VERB and msg.getSpeechAct() == INFORM_ACT
                and msg.getObject() == recMsg.getActor()):

            if isinstance(recMsg.getObject(), (int, float)):
                numberOfRecommendations = int(recMsg.getObject())
            else:
                numberOfRecommendations = 3

            recommendedTasks = self.recommender.getRecommendedTasks(
                msg.getObject(), msg.getResult(), numberOfRecommendations)
            self.sendRecommendations(recommendedTasks, recMsg)
Пример #10
0
    def receiveMessage(self, msg):
        super(RecommenderMessaging, self).receiveMessage(msg)
        #depending on the content of the message react differently
        logInfo('Entering Recommender.receiveMessage', 5)

        if self.recommender.taskASSISTmentsDictionary is None:
            self.recommender.taskASSISTmentsDictionary = self.recommender.populateTaskAssistmentsDictionary(
            )

        if (msg.getSpeechAct() == REQUEST_ACT
                and msg.getVerb() == RECOMMENDED_TASKS_VERB):
            outMsg = Message(None, MASTERY_VERB, msg.getActor(),
                             msg.getObject(), REQUEST_ACT)
            #TODO: Replace with the ability to store context w/ the request in the base recommender class
            outMsg.setContextValue(self.ORIGINAL_MESSAGE_KEY, msg)
            self._makeRequest(outMsg, self.studentModelCallBack)
Пример #11
0
 def testIsEquivalent(self):
     # Identity Tests
     self.assertFalse(self.blankMessage.isEquivalent(self.message))
     self.assertFalse(self.message.isEquivalent(self.blankMessage))
     self.assertTrue(self.blankMessage.isEquivalent(self.blankMessage))
     self.assertTrue(self.message.isEquivalent(self.message))
     # Equivalency Tests
     messageClone = self.message.clone(newId=False)
     messageClone._id = uuid4()
     self.assertTrue(self.blankMessage.isEquivalent(Message()))
     self.assertTrue(self.message.isEquivalent(messageClone))
     # Different Id
     messageClone = self.message.clone()
     messageClone._id = uuid4()
     self.assertTrue(self.blankMessage.isEquivalent(Message()))
     self.assertTrue(self.message.isEquivalent(messageClone))
Пример #12
0
 def _sendHelpMessage(self, verb, content, stepId, helpType, contentType):
     if (contentType == None) and content != None:
         contentType = 'text'
         content = str(content)
     if helpType == None:
         helpType = NEUTRAL_HELP_TYPE
     msg = Message(self._taskId, verb, stepId, content)
     msg.setContextValue(STEP_ID_KEY, stepId)
     msg.setContextValue(HELP_TYPE_KEY, helpType)
     msg.setContextValue(RESULT_CONTENT_TYPE_KEY, contentType)
     self.sendLoggingMessage(msg)
Пример #13
0
 def sendTestMessage(self,
                     actor,
                     verb,
                     obj,
                     result,
                     speechAct,
                     context=None):
     if context is None: context = {}
     msg = Message(actor, verb, obj, result, speechAct, context=context)
     that.sendMessage(msg)
Пример #14
0
 def test__ne__(self):
     clone1ActorDiff = self.message.clone(newId=False)
     clone1ActorDiff.setActor("Nobody")
     clone2ContextDiff = self.message.clone(newId=False)
     clone2ContextDiff.setContextValue("ImaginaryKey", 0)
     
     self.assertTrue(self.blankMessage != Message())
     self.assertFalse(self.message != self.message.clone(newId=False))
     self.assertTrue((self.blankMessage) !=(self.message))
     self.assertTrue((self.message) !=(clone1ActorDiff))
     self.assertTrue((self.message)!=(clone2ContextDiff))
Пример #15
0
 def sendRecommendations(self, recommendedTasks, msgTemplate=None):
     if msgTemplate is None: msgTemplate = Message()
     #need to make sure this how we send the reply
     outMsg = self._createRequestReply(msgTemplate)
     outMsg.setSpeechAct(INFORM_ACT)
     outMsg.setVerb(RECOMMENDED_TASKS_VERB)
     outMsg.setResult(recommendedTasks)
     # @TODO: This shouldn't be a problem, yet it seems to be on the JS side when it is stored as a storage token?
     if outMsg.hasContextValue(self.ORIGINAL_MESSAGE_KEY):
         outMsg.delContextValue(self.ORIGINAL_MESSAGE_KEY)
     self.sendMessage(outMsg)
Пример #16
0
 def sendTestMessage(self,
                     callback,
                     actor,
                     verb,
                     obj,
                     result,
                     speechAct,
                     context=None):
     if context is None: context = {}
     msg = Message(actor, verb, obj, result, speechAct, context=context)
     that._makeRequest(msg, callback)
Пример #17
0
 def test__hash__(self):
     self.assertNotEqual(hash(self.blankMessage), hash(Message()))
     self.assertEqual(hash(self.blankMessage), hash(self.blankMessage.clone(newId=False)))
     self.assertEqual(hash(self.message), hash(self.message.clone(newId=False)))
     self.assertNotEqual(hash(self.blankMessage), hash(self.message))
     clone1ActorDiff = self.message.clone(newId=False)
     clone1ActorDiff.setActor("Nobody")
     clone2ContextDiff = self.message.clone(newId=False)
     clone2ContextDiff.setContextValue("ImaginaryKey", 0)
     self.assertNotEqual(hash(self.message), hash(clone1ActorDiff))
     self.assertEqual(hash(self.message), hash(clone2ContextDiff))
Пример #18
0
    def receiveMessage(self, msg):
        #depending on the content of the message react differently
        #logInfo('Entering CSVReader.receiveMessage', 5)

        reply = None
        #Only considering
        if msg.getSpeechAct() == INFORM_ACT:

            if msg.getVerb() == ELECTRONIX_TUTOR_TASK_UPLOAD_VERB:
                logInfo(
                    '{0} is processing a {1},{2} message'.format(
                        CSV_READER_SERVICE_NAME,
                        ELECTRONIX_TUTOR_TASK_UPLOAD_VERB, INFORM_ACT), 4)
                csvString = msg.getResult()
                taskList = self.processCSVFile(csvString)
                print("STORAGE SERVICE NAME: %s" % (STORAGE_SERVICE_NAME))
                reply = Message(STORAGE_SERVICE_NAME, VALUE_VERB, TASKS_OBJECT,
                                taskList)

        if msg.getSpeechAct() == REQUEST_ACT:
            if msg.getVerb() == ELECTRONIX_TUTOR_TASK_UPLOAD_VERB:
                dbtaskList = DBTask.find_all()
                dbassistmentItemsList = DBAssistmentsItem.find_all()

                for dbTask in dbtaskList:
                    if dbTask.assistmentsItemId is not None and dbTask.assistmentsItemId is not '':
                        for dbassistmentsItem in dbassistmentItemsList:
                            if dbassistmentsItem.id == dbTask.assistmentsItemId:
                                dbTask.assistmentsItemCache = dbassistmentsItem
                                break

                taskList = [x.toSerializable() for x in dbtaskList]
                reply = Message(CSV_READER_SERVICE_NAME,
                                ELECTRONIX_TUTOR_TASK_UPLOAD_VERB, None,
                                taskList, INFORM_ACT, msg.getContext())

        if reply is not None:
            logInfo(
                '{0} is broadcasting a {1}, {2} message'.format(
                    CSV_READER_SERVICE_NAME, INFORM_ACT, VALUE_VERB), 4)
            self.sendMessage(reply)
Пример #19
0
 def testGetDataKeys_ByMsg(self):
     self.populate()
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.CONTAINS_VERB,
                   None,
                   None,
                   REQUEST_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     val = self.storage.processStorageRequest(bucket, self.CONTAINS_VERB)
     self.assertItemsEqual(val, self.keys)
Пример #20
0
 def sendPresented(self, elementId, content, stepId, contentType):
     if contentType == None and content != None:
         contentType = 'text'
         content = str(content)
     msg = Message(self._taskId, PRESENTED_VERB, elementId, content)
     msg.setContextValue(STEP_ID_KEY, stepId)
     msg.setContextValue(RESULT_CONTENT_TYPE_KEY, contentType)
     self.sendLoggingMessage(msg)
Пример #21
0
 def _sendInputMessage(self, verb, elementId, content, stepId, contentType):
     if ((contentType == None) and content != None):
         contentType = 'text'
         content = content.toString()
     msg = Message(self._userId, verb, elementId, content)
     msg.setContextValue(STEP_ID_KEY, stepId)
     msg.setContextValue(RESULT_CONTENT_TYPE_KEY, contentType)
     self.sendLoggingMessage(msg)
Пример #22
0
 def testGetData_Missing_ByMsg(self):
     self.populate()
     key = self.keyMissing
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.VALUE_VERB,
                   key,
                   None,
                   REQUEST_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     val = self.storage.processStorageRequest(bucket, self.VALUE_VERB, key)
     self.assertIsNone(val)
Пример #23
0
 def testHasDataKey_False_ByMsg(self):
     self.populate()
     key = self.keyMissing
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.HAS_ELEMENT_VERB,
                   key,
                   None,
                   REQUEST_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     val = self.storage.processStorageRequest(bucket, self.HAS_ELEMENT_VERB,
                                              key)
     self.assertFalse(val)
Пример #24
0
 def testGetDataLink_NonMedia(self):
     self.populate()
     key = self.keyExists
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.ASSIGNED_URI_VERB,
                   key,
                   None,
                   REQUEST_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     val = self.storage.processStorageRequest(bucket,
                                              self.ASSIGNED_URI_VERB, key)
     self.assertIsNone(val)
Пример #25
0
 def testSetData_ByMsg(self):
     self.populate()
     key = self.keyExists
     value = "Ben"
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.VALUE_VERB,
                   key,
                   value,
                   INFORM_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     val = self.storage.processStorageRequest(bucket, self.VALUE_VERB, key)
     self.assertEqual(val, value)
Пример #26
0
 def testGetDataKeys_Tags2_Media(self):
     self.populate()
     context = self.makeMessageContext(tags=[self.tag2], type=DATA_TYPE_DB)
     msg = Message(self.serviceName,
                   self.CONTAINS_VERB,
                   None,
                   None,
                   REQUEST_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     val = self.storage.processStorageRequest(bucket,
                                              self.CONTAINS_VERB,
                                              tags=[self.tag2],
                                              aType=DATA_TYPE_MEDIA)
     self.assertItemsEqual(val, [self.mediaKeyExists])
Пример #27
0
 def testRename(self):
     self.populate()
     key = self.keyExists
     newName = "SomeNewName"
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.HAS_ELEMENT_VERB,
                   key,
                   newName,
                   INFORM_REF_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     valKey, valName = self.storage.processStorageRequest(
         bucket, INFORM_REF_ACT, key)
     self.assertEqual(valName, newName)
Пример #28
0
 def testGetDataName(self):
     self.populate()
     key = self.keyExists
     newName = "SomeNewName"
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   INFORM_REF_ACT,
                   key,
                   None,
                   REQUEST_ACT,
                   context=context)
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     valKey, valName = self.storage.processStorageRequest(
         bucket, INFORM_REF_ACT, key)
     self.assertEqual(valKey, self.keyExists)
     self.assertEqual(valName, self.keyExistsName)
Пример #29
0
 def _dumpLog(self, msg):
     incomingMsg = IncomingMessage(rawMessage=serializeObject(msg))
     allMessages = incomingMsg.find_all()
     attrs = [log.rawMessage for log in allMessages]
     joinedMessage = ""
     #joinedMessage = joinedMessage.join(attrs)
     outMsg = Message("DBLoggingService", "Dump Logs", "To Client",
                      joinedMessage)
     outMsg.setContextValue("sessionId",
                            msg.getContextValue("sessionId", None))
     outMsg.setContextValue("sid", msg.getContextValue("sid", None))
     self.sendMessage(outMsg)
Пример #30
0
 def testDelData_Missing_ByMsg(self):
     self.populate()
     key = self.keyMissing
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.VOID_VERB,
                   key,
                   None,
                   INFORM_ACT,
                   context=context)
     bucket = self.storage.getBucket(self.bucketName)
     self.assertFalse(
         self.storage.processStorageRequest(bucket, self.HAS_ELEMENT_VERB,
                                            key))
     self.storage.receiveMessage(msg)
     self.assertFalse(
         self.storage.processStorageRequest(bucket, self.HAS_ELEMENT_VERB,
                                            key))
Пример #31
0
 def testDelData_Exists_ByMsg(self):
     self.populate()
     key = self.keyExists
     context = self.makeMessageContext()
     msg = Message(self.serviceName,
                   self.VOID_VERB,
                   key,
                   None,
                   INFORM_ACT,
                   context=context)
     bucket = self.storage.getBucket(self.bucketName)
     print bucket.to_json()
     oldBucket = self.storage.getBucket(self.bucketName)
     self.assertTrue(
         self.storage.processStorageRequest(bucket, self.HAS_ELEMENT_VERB,
                                            key))
     self.storage.receiveMessage(msg)
     bucket = self.storage.getBucket(self.bucketName)
     self.assertFalse(bucket.delValue(key))
     self.assertFalse(
         self.storage.processStorageRequest(bucket, self.HAS_ELEMENT_VERB,
                                            key))
Пример #32
0
    def receiveMessage(self, msg):
        reply = None
        if msg.getSpeechAct() == INFORM_ACT:
            """
            message format for loading calendars: 
            actor = className or student name
            verb = electronixTutorUploadCalendarVerb
            object = ownerType
            result = iCal data
            context contains access permissions
            """
            if msg.getVerb() == ELECTRONIX_TUTOR_UPLOAD_CALENDAR_VERB:
                logInfo(
                    '{0} is processing a {1},{2} message'.format(
                        ICAL_READER_SERVICE_NAME,
                        ELECTRONIX_TUTOR_UPLOAD_CALENDAR_VERB, INFORM_ACT), 4)
                calendarData = SerializableCalendarData()
                calendarData.ownerId = msg.getActor()
                calendarData.ownerType = msg.getObject()
                #default to public access if none are given
                calendarData.accessPermissions = msg.getContextValue(
                    CALENDAR_ACCESS_PERMISSIONS_KEY, PUBLIC_PERMISSION)
                calendarInput = msg.getResult()
                #Calendar library needs to have an encoding
                #calendarData.calendarData = calendarInput.encode('UTF-8')
                calendarData.calendarData = calendarInput
                self.createCalendarData(calendarData.ownerId,
                                        calendarData.ownerType,
                                        calendarData.accessPermissions,
                                        calendarInput)
                reply = Message(STORAGE_SERVICE_NAME,
                                VALUE_VERB,
                                calendarData.getId(),
                                calendarData,
                                INFORM_ACT,
                                context=msg.getContext())

        if msg.getSpeechAct() == REQUEST_ACT:
            """
            message format for adding a task or topic to a calendar:
            actor = ICAL_READER_SERVICE_NAME
            verb = addTaskToCalendar
            object = ownerId
            result = task or topic data
            context = startTime (required), endTime(optional), duration(optional)
            """
            if msg.getVerb() == ADD_EVENT_TO_CALENDAR_VERB:
                logInfo(
                    '{0} is processing a {1},{2} message'.format(
                        ICAL_READER_SERVICE_NAME, ADD_EVENT_TO_CALENDAR_VERB,
                        REQUEST_ACT), 4)
                startTime = msg.getContextValue(CALENDAR_EVENT_START_TIME_KEY,
                                                None)
                calendarData = self.DB_BRIDGE.getCalendarFromOwnerId(
                    msg.getObject())
                endTime = msg.getContextValue(CALENDAR_EVENT_END_TIME_KEY,
                                              None)
                duration = msg.getContextValue(CALENDAR_EVENT_DURATION_KEY,
                                               None)
                if isinstance(msg.getResult(), LearningTask):
                    self.addTaskToCalendar(msg.getResult(), calendarData,
                                           startTime, endTime, duration)
                    calendarData.saveToDB()
                elif isinstance(msg.getResult(), SerializableTopic):
                    self.addTopicToCalendar(msg.getResult(), calendarData,
                                            startTime, endTime, duration)
                    calendarData.saveToDB()
                else:
                    logInfo("no task or topic given, cannot create event", 2)
            """
            message format for lookup up information from a calendar
            actor = ICAL_READER_SERVICE_NAME
            verb = calendarLookup
            object = ownerId
            result = 'taskId' or 'topicId' defaults to taskID
            context = startTime (optional), endTime(optional), duration(optional)
            """
            if msg.getVerb() == CALENDAR_LOOKUP_VERB:
                logInfo(
                    '{0} is processing a {1},{2} message'.format(
                        ICAL_READER_SERVICE_NAME, CALENDAR_LOOKUP_VERB,
                        REQUEST_ACT), 4)
                startTime = msg.getContextValue(CALENDAR_LOOKUP_START_TIME_KEY,
                                                None)
                endTime = msg.getContextValue(CALENDAR_LOOKUP_END_TIME_KEY,
                                              None)
                duration = msg.getContextValue(
                    CALENDAR_LOOKUP_RELATIVE_TIME_KEY, None)
                eventType = msg.getContextValue(CALENDAR_LOOKUP_EVENT_TYPE_KEY,
                                                TASK_ID)
                calendarData = self.DB_BRIDGE.getCalendarFromOwnerId(
                    msg.getObject())
                taskOrTopicList = self.lookupEventInformation(
                    calendarData, eventType, startTime, endTime, duration)
                reply = Message(actor=ICAL_READER_SERVICE_NAME,
                                verb=CALENDAR_LOOKUP_VERB,
                                object=eventType,
                                result=taskOrTopicList,
                                context=msg.getContext())
            """
            message format for requesting information from a calendar
            actor = ICAL_READER_SERVICE_NAME
            verb = requestCalendar
            object = ownerId
            """
            if msg.getVerb() == REQUEST_CALENDAR_VERB:
                logInfo(
                    '{0} is processing a {1},{2} message'.format(
                        ICAL_READER_SERVICE_NAME, REQUEST_CALENDAR_VERB,
                        REQUEST_ACT), 4)
                calendarData = self.DB_BRIDGE.getCalendarFromOwnerId(
                    msg.getObject())
                iCalData = calendarData.calendarData
                #iCalDataAsBytes = calendarData.calendarData
                #iCalDataAsString = iCalDataAsBytes.decode('UTF-8')
                reply = Message(actor=ICAL_READER_SERVICE_NAME,
                                verb=REQUEST_CALENDAR_VERB,
                                obj=msg.getObject(),
                                result=iCalData,
                                context=msg.getContext())
            """
            message format for requesting the table of contents
            actor = ICAL_READER_SERVICE_NAME
            verb = tableOfContents
            object = ownerId
            context = startTime (optional), endTime(optional), duration(optional)
            """
            if msg.getVerb() == TABLE_OF_CONTENTS_VERB:
                logInfo(
                    '{0} is processing a {1},{2} message'.format(
                        ICAL_READER_SERVICE_NAME, TABLE_OF_CONTENTS_VERB,
                        REQUEST_ACT), 4)
                calendarData = self.DB_BRIDGE.getCalendarFromOwnerId(
                    msg.getObject())
                startTime = msg.getContextValue(CALENDAR_LOOKUP_START_TIME_KEY,
                                                None)
                endTime = msg.getContextValue(CALENDAR_LOOKUP_END_TIME_KEY,
                                              None)
                duration = msg.getContextValue(
                    CALENDAR_LOOKUP_RELATIVE_TIME_KEY, None)
                topicList = self.lookupEventInformation(
                    calendarData, TOPIC_ID, startTime, endTime, duration)
                taskList = self.lookupEventInformation(calendarData, TASK_ID,
                                                       startTime, endTime,
                                                       duration)

                topicTaskDictionary = self.buildTableOfContents(
                    topicList, taskList)
                reply = Message(actor=ICAL_READER_SERVICE_NAME,
                                verb=TABLE_OF_CONTENTS_VERB,
                                object=msg.getObject(),
                                result=topicTaskDictionary,
                                context=msg.getContext())

        if reply is not None:
            logInfo(
                '{0} is broadcasting a {1}, {2} message'.format(
                    ICAL_READER_SERVICE_NAME, INFORM_ACT, VALUE_VERB), 4)
            self.sendMessage(reply)
 def testSerialize(self):
     token = self.message.saveToToken()
     newMessage = Message()
     newMessage.initializeFromToken(token)
     self.assertEqual(self.message, newMessage)
class MessageTest(unittest.TestCase):

    def setUp(self):
        self.actor = "AnActor"
        self.object = "AnObject"
        self.verb = "AVerb"
        self.result = "Result"
        self.speechAct = CONFIRM_ACT
        self.contextKey = "SimpleContext"
        self.contextVal = 0
        self.context = {self.contextKey : self.contextVal}
        self.timestamp = time()
        self.theId = uuid4()
        self.blankMessage = Message()
        self.message = Message(self.actor, self.verb, self.object,
                               self.result, self.speechAct, self.context,
                               self.timestamp, self.theId)

    def test__init__(self):
        blankMessage = Message()
        fullMessage = Message(self.actor, self.verb, self.object,
                               self.result, self.speechAct, self.context,
                               self.timestamp, self.theId)
        self.assertIsInstance(blankMessage, Message)
        self.assertIsInstance(fullMessage, Message)

    def testGetActor(self):
        self.assertIsNone(self.blankMessage.getActor())
        self.assertEqual(self.message.getActor(), self.actor)

    def testSetActor(self):
        newValue = "NewValue"
        self.assertEqual(self.message.getActor(), self.actor)
        self.message.setActor(newValue)
        self.assertEqual(self.message.getActor(), newValue)

    def testGetVerb(self):
        self.assertIsNone(self.blankMessage.getVerb())
        self.assertEqual(self.message.getVerb(), self.verb)

    def testSetVerb(self):
        newValue = "NewValue"
        self.assertEqual(self.message.getVerb(), self.verb)
        self.message.setVerb(newValue)
        self.assertEqual(self.message.getVerb(), newValue)

    def testGetObject(self):
        self.assertIsNone(self.blankMessage.getObject())
        self.assertEqual(self.message.getObject(), self.object)

    def testSetObject(self):
        newValue = "NewValue"
        self.assertEqual(self.message.getObject(), self.object)
        self.message.setObject(newValue)
        self.assertEqual(self.message.getObject(), newValue)

    def testGetResult(self):
        self.assertIsNone(self.blankMessage.getResult())
        self.assertEqual(self.message.getResult(), self.result)

    def testSetResult(self):
        newValue = "NewValue"
        self.assertEqual(self.message.getResult(), self.result)
        self.message.setResult(newValue)
        self.assertEqual(self.message.getResult(), newValue)

    def testGetSpeechAct(self):
        self.assertEqual(self.blankMessage.getSpeechAct(), INFORM_ACT)
        self.assertEqual(self.message.getSpeechAct(), self.speechAct)

    def testSetSpeechAct(self):
        newValue = INFORM_ACT
        self.assertEqual(self.message.getSpeechAct(), self.speechAct)
        self.message.setSpeechAct(newValue)
        self.assertEqual(self.message.getSpeechAct(), newValue)

    def testGetTimestamp(self):
        self.assertIsNone(self.blankMessage.getTimestamp())
        self.assertEqual(self.message.getTimestamp(), self.timestamp)

    def testSetTimestamp(self):
        newValue = "NewValue"
        self.assertEqual(self.message.getTimestamp(), self.timestamp)
        self.message.setTimestamp(newValue)
        self.assertEqual(self.message.getTimestamp(), newValue)

    def testUpdateTimestamp(self):
        self.assertEqual(self.message.getTimestamp(), self.timestamp)
        sleep(0.001)
        self.message.updateTimestamp()
        #Now a str in isoformat format
        self.assertIsInstance(self.message.getTimestamp(), str)
        self.assertTrue(self.message.getTimestamp() > self.timestamp)

    def testHasContextValue(self):
        self.assertFalse(self.blankMessage.hasContextValue(self.contextKey))
        self.assertTrue(self.message.hasContextValue(self.contextKey))
        self.assertFalse(self.message.hasContextValue("NonexistentKey"))

    def testGetContextValue(self):
        self.assertIsNone(self.blankMessage.getContextValue(self.contextKey))
        self.assertEqual(self.message.getContextValue(self.contextKey), self.contextVal)
        self.assertIsNone(self.message.getContextValue("NonexistentKey"))

    def testGetContextKeys(self):
        self.assertEqual(list(self.blankMessage.getContextKeys()), [])
        self.assertEqual(list(self.message.getContextKeys()), [self.contextKey])

    def testSetContextValue_NoKey(self):
        newKey = "NewKey"
        newValue = "NewValue"
        self.assertFalse(self.blankMessage.hasContextValue(newKey))
        self.blankMessage.setContextValue(newKey, newValue)
        self.assertTrue(self.blankMessage.hasContextValue(newKey))
        self.assertEqual(self.blankMessage.getContextValue(newKey), newValue)

    def testSetContextValue_KeyExists(self):
        newValue = "NewValue"
        self.assertEqual(self.message.getContextValue(self.contextKey), self.contextVal)
        self.message.setContextValue(self.contextKey, newValue)
        self.assertEqual(self.message.getContextValue(self.contextKey), newValue)

    def testDelContextValue(self):
        self.assertTrue(self.message.hasContextValue(self.contextKey))
        self.message.delContextValue(self.contextKey)
        self.assertFalse(self.message.hasContextValue(self.contextKey))

    def test__hash__(self):
        self.assertNotEqual(hash(self.blankMessage), hash(Message()))
        self.assertEqual(hash(self.blankMessage), hash(self.blankMessage.clone(newId=False)))
        self.assertEqual(hash(self.message), hash(self.message.clone(newId=False)))
        self.assertNotEqual(hash(self.blankMessage), hash(self.message))
        clone1ActorDiff = self.message.clone(newId=False)
        clone1ActorDiff.setActor("Nobody")
        clone2ContextDiff = self.message.clone(newId=False)
        clone2ContextDiff.setContextValue("ImaginaryKey", 0)
        self.assertNotEqual(hash(self.message), hash(clone1ActorDiff))
        self.assertEqual(hash(self.message), hash(clone2ContextDiff))

    def test__eq__(self):
        clone1ActorDiff = self.message.clone(newId=False)
        clone1ActorDiff.setActor("Nobody")
        clone2ContextDiff = self.message.clone(newId=False)
        clone2ContextDiff.setContextValue("ImaginaryKey", 0)
        
        self.assertFalse(self.blankMessage == Message())
        self.assertTrue(self.message == self.message.clone(newId=False))
        self.assertFalse((self.blankMessage) == (self.message))
        self.assertFalse((self.message) == (clone1ActorDiff))
        self.assertFalse((self.message) == (clone2ContextDiff))

    def test__ne__(self):
        clone1ActorDiff = self.message.clone(newId=False)
        clone1ActorDiff.setActor("Nobody")
        clone2ContextDiff = self.message.clone(newId=False)
        clone2ContextDiff.setContextValue("ImaginaryKey", 0)
        
        self.assertTrue(self.blankMessage != Message())
        self.assertFalse(self.message != self.message.clone(newId=False))
        self.assertTrue((self.blankMessage) !=(self.message))
        self.assertTrue((self.message) !=(clone1ActorDiff))
        self.assertTrue((self.message)!=(clone2ContextDiff))

    def testIsEquivalent(self):
        # Identity Tests
        self.assertFalse(self.blankMessage.isEquivalent(self.message))
        self.assertFalse(self.message.isEquivalent(self.blankMessage))
        self.assertTrue(self.blankMessage.isEquivalent(self.blankMessage))
        self.assertTrue(self.message.isEquivalent(self.message))
        # Equivalency Tests
        messageClone = self.message.clone(newId=False)
        messageClone._id = uuid4()
        self.assertTrue(self.blankMessage.isEquivalent(Message()))
        self.assertTrue(self.message.isEquivalent(messageClone))
        # Different Id
        messageClone = self.message.clone()
        messageClone._id = uuid4()
        self.assertTrue(self.blankMessage.isEquivalent(Message()))
        self.assertTrue(self.message.isEquivalent(messageClone))

    def testSerialize(self):
        token = self.message.saveToToken()
        newMessage = Message()
        newMessage.initializeFromToken(token)
        self.assertEqual(self.message, newMessage)

    def testClone(self):
        x = self.message.clone(newId=False)
        self.assertEqual(self.message, x)

    def testAuthContext(self):
        self.message.setContextValue(Message.AUTHORIZATION_KEY, "role1,role2")
        self.message.setContextValue(Message.AUTHENTICATION_KEY, "userid")
        
        self.testClone()
        
        #silly but thorough
        self.assertEquals("role1,role2", self.message.getContextValue(Message.AUTHORIZATION_KEY))
        self.assertEquals("userid", self.message.getContextValue(Message.AUTHENTICATION_KEY))

    def testMakeFIPAMessage(self):
        self.assertRaises(NotImplementedError, self.blankMessage.makeFIPAMessage)

    def testMakeTinCanMessage(self):
        self.assertRaises(NotImplementedError, self.blankMessage.makeTinCanMessage)