Browse Source

Merge pull request #63 from kalliope-project/tests

Tests
Nicolas Marcq 8 years ago
parent
commit
8fb09da0be
2 changed files with 242 additions and 154 deletions
  1. 87 51
      core/OrderAnalyser.py
  2. 155 103
      core/Tests/test_order_analyser.py

+ 87 - 51
core/OrderAnalyser.py

@@ -31,64 +31,100 @@ class OrderAnalyser:
         logger.debug("OrderAnalyser, Received order: %s" % self.order)
 
     def start(self):
-        # TODO : refactor this method !!
         """
         This method matches the incoming messages to the signals/order sentences provided in the Brain
         """
-        synapses_found = False
-        problem_in_neuron_found = False
-        # create a dict of synapses that have benn launched
-        launched_synapses = list()
-        for synapse in self.brain.synapses:
+
+        # create a dict of synapses that have been launched
+        launched_synapses = self._get_matching_synapse_list(self.brain.synapses, self.order)
+
+        if not launched_synapses:
+            Utils.print_info("No synapse match the captured order: %s" % self.order)
+        else:
+            for synapse in launched_synapses:
+                params = self._get_synapse_params(synapse, self.order)
+                for neuron in synapse.neurons:
+                    self._start_neuron(neuron, params)
+
+        # return the list of launched synapse
+        return launched_synapses
+
+    @classmethod
+    def _get_matching_synapse_list(cls, all_synapses_list, order_to_match):
+        """
+        Class method to return all the matching synapses with the order from the complete of synapses.
+
+        :param all_synapses_list: the complete list of all synapses
+        :param order_to_match: the order to match
+        :type order_to_match: str
+        :return: the list of matching synapses
+        """
+        matching_synapses_list = list()
+        for synapse in all_synapses_list:
             for signal in synapse.signals:
                 if type(signal) == Order:
-                    if self._spelt_order_match_brain_order_via_table(signal.sentence, self.order):
-                        launched_synapses.append(synapse)
-                        synapses_found = True
+                    if cls._spelt_order_match_brain_order_via_table(signal.sentence, order_to_match):
+                        matching_synapses_list.append(synapse)
                         logger.debug("Order found! Run neurons: %s" % synapse.neurons)
                         Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
-                        # if the order contains bracket, we get parameters said by the user
-                        params = None
-                        if self._is_containing_bracket(signal.sentence):
-                            params = self._associate_order_params_to_values(self.order, signal.sentence)
-                            logger.debug("Parameters for order: %s" % params)
-
-                        for neuron in synapse.neurons:
-                            if isinstance(neuron.parameters, dict):
-                                # print neuron.parameters
-                                if "args" in neuron.parameters:
-                                    logger.debug("The neuron wait for parameter")
-                                    # check that the user added parameters to his order
-                                    if params is None:
-                                        # we don't raise an error and break the program but we don't run the neuron
-                                        problem_in_neuron_found = True
-                                        Utils.print_danger("Error: The neuron %s is waiting for argument. "
-                                                           "Argument found in bracket in the given order" % neuron.name)
-                                    else:
-                                        # we add wanted arguments the existing neuron parameter dict
-                                        for arg in neuron.parameters["args"]:
-                                            if arg in params:
-                                                logger.debug("Parameter %s added to the current parameter "
-                                                             "of the neuron: %s" % (arg, neuron.name))
-                                                neuron.parameters[arg] = params[arg]
-                                            else:
-                                                # we don't raise an error and break the program but
-                                                # we don't run the neuron
-                                                problem_in_neuron_found = True
-                                                Utils.print_danger("Error: Argument \"%s\" not found in the"
-                                                                   " order" % arg)
-
-                            # if no error detected, we run the neuron
-                            if not problem_in_neuron_found:
-                                NeuroneLauncher.start_neurone(neuron)
-                            else:
-                                Utils.print_danger("A problem has been found in the Synapse.")
-
-        if not synapses_found:
-            Utils.print_info("No synapse match the captured order: %s" % self.order)
+        return matching_synapses_list
 
-        # return the list of launched synapse
-        return launched_synapses
+    @classmethod
+    def _get_synapse_params(cls, synapse, order_to_check):
+        """
+        Class method to get all params coming from a synapse. Returns a dict of key/value.
+
+        :param synapse: the synapse to check
+        :param order_to_check: the order to match
+        :type order_to_check: str
+        :return: the dict key/value
+        """
+        params = dict()
+        for signal in synapse.signals:
+            if cls._is_containing_bracket(signal.sentence):
+                params = cls._associate_order_params_to_values(order_to_check, signal.sentence)
+                logger.debug("Parameters for order: %s" % params)
+        return params
+
+    @classmethod
+    def _start_neuron(cls, neuron, params):
+        """
+        Associate params and Starts a neuron.
+
+        :param neuron: the neuron to start
+        :param params: the params to check and associate to the neuron args.
+        """
+
+        problem_in_neuron_found = False
+        if isinstance(neuron.parameters, dict):
+            # print neuron.parameters
+            if "args" in neuron.parameters:
+                logger.debug("The neuron waits for parameter")
+                # check that the user added parameters to his order
+                if params is None:
+                    # we don't raise an error and break the program but we don't run the neuron
+                    problem_in_neuron_found = True
+                    Utils.print_danger("Error: The neuron %s is waiting for argument. "
+                                       "Argument found in bracket in the given order" % neuron.name)
+                else:
+                    # we add wanted arguments the existing neuron parameter dict
+                    for arg in neuron.parameters["args"]:
+                        if arg in params:
+                            logger.debug("Parameter %s added to the current parameter "
+                                         "of the neuron: %s" % (arg, neuron.name))
+                            neuron.parameters[arg] = params[arg]
+                        else:
+                            # we don't raise an error and break the program but
+                            # we don't run the neuron
+                            problem_in_neuron_found = True
+                            Utils.print_danger("Error: Argument \"%s\" not found in the"
+                                               " order" % arg)
+
+        # if no error detected, we run the neuron
+        if not problem_in_neuron_found:
+            NeuroneLauncher.start_neurone(neuron)
+        else:
+            Utils.print_danger("A problem has been found in the Synapse.")
 
     @classmethod
     def _associate_order_params_to_values(cls, order, order_to_check):
@@ -113,7 +149,7 @@ class OrderAnalyser:
         truncate_list_word_said = truncate_user_sentence.split()
 
         # make dict var:value
-        dict_var = {}
+        dict_var = dict()
         for idx, ow in enumerate(list_word_in_order):
             if cls._is_containing_bracket(ow):
                 # remove bracket and grab the next value / stop value

+ 155 - 103
core/Tests/test_order_analyser.py

@@ -1,8 +1,10 @@
 import unittest
-from mock import patch, Mock, MagicMock
 
 
 from core.OrderAnalyser import OrderAnalyser
+from core.Models.Neuron import Neuron
+from core.Models.Synapse import Synapse
+from core.Models.Order import Order
 
 
 class TestOrderAnalyser(unittest.TestCase):
@@ -30,17 +32,17 @@ class TestOrderAnalyser(unittest.TestCase):
         #  Failure
         order_to_test = "This test does not contain bracket"
         self.assertFalse(OrderAnalyser._is_containing_bracket(order_to_test),
-                        "Fail returning False when order has no brackets")
+                         "Fail returning False when order has no brackets")
 
         #  Behaviour
         order_to_test = ""
         self.assertFalse(OrderAnalyser._is_containing_bracket(order_to_test),
-                        "Fail returning False when no order")
+                         "Fail returning False when no order")
 
     def test_get_next_value_list(self):
         # Success
         list_to_test = {1, 2, 3}
-        self.assertEqual(OrderAnalyser._get_next_value_list(list_to_test),2,
+        self.assertEqual(OrderAnalyser._get_next_value_list(list_to_test), 2,
                          "Fail to match the expected next value from the list")
 
         # Failure
@@ -71,7 +73,7 @@ class TestOrderAnalyser(unittest.TestCase):
         # Success
         order_to_test = "this is the order"
         expected_result = ["this", "is", "the", "order"]
-        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test),expected_result,
+        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "No brackets Fails to return the expected list")
 
         order_to_test = "this is the {{ order }}"
@@ -79,12 +81,12 @@ class TestOrderAnalyser(unittest.TestCase):
         self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "With spaced brackets Fails to return the expected list")
 
-        order_to_test = "this is the {{order }}" # left bracket without space
+        order_to_test = "this is the {{order }}"    # left bracket without space
         expected_result = ["this", "is", "the"]
         self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "Left brackets Fails to return the expected list")
 
-        order_to_test = "this is the {{ order}}" # right bracket without space
+        order_to_test = "this is the {{ order}}"    # right bracket without space
         expected_result = ["this", "is", "the"]
         self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "Right brackets Fails to return the expected list")
@@ -95,101 +97,151 @@ class TestOrderAnalyser(unittest.TestCase):
                          "No space brackets Fails to return the expected list")
 
     def test_associate_order_params_to_values(self):
-       ##
-       # Testing the brackets position behaviour
-       ##
-
-       # Success
-       order_brain = "This is the {{ variable }}"
-       order_user = "This is the value"
-       expected_result = {'variable': 'value'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user,order_brain), expected_result,
-                        "Fail to match the order_brain {{ variable }} to the 'value'")
-
-       # Success
-       order_brain = "This is the {{variable }}"
-       order_user = "This is the value"
-       expected_result = {'variable': 'value'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                        "Fail to match the order_brain {{variable }} to the 'value'")
-
-       # Success
-       order_brain = "This is the {{ variable}}"
-       order_user = "This is the value"
-       expected_result = {'variable': 'value'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                        "Fail to match the order_brain {{ variable}} to the 'value'")
-
-       # Success
-       order_brain = "This is the {{variable}}"
-       order_user = "This is the value"
-       expected_result = {'variable': 'value'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                        "Fail to match the order_brain {{variable}} to the 'value'")
-
-       # Fail
-       order_brain = "This is the {variable}"
-       order_user = "This is the value"
-       expected_result = {'variable': 'value'}
-       self.assertNotEquals(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                        "Should not match the order_brain {variable} to the 'value'")
-
-       # Fail
-       order_brain = "This is the { variable}}"
-       order_user = "This is the value"
-       expected_result = {'variable': 'value'}
-       self.assertNotEquals(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                        "Should not match the order_brain { variable}} to the 'value'")
-
-       ##
-       # Testing the brackets position in the sentence
-       ##
-
-       # Success
-       order_brain = "{{ variable }} This is the"
-       order_user = "value This is the"
-       expected_result = {'variable': 'value'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                         "Fail to match the order_brain {{ variable }} in first position ins the sentence to the 'value'")
-
-       # Success
-       order_brain = "This is {{ variable }} the"
-       order_user = " This is value the"
-       expected_result = {'variable': 'value'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                         "Fail to match the order_brain {{ variable }} in middle position ins the sentence to the 'value'")
-
-
-       ##
-       # Testing multi variables
-       ##
-
-       # Success
-       order_brain = "This is {{ variable }} the {{ variable2 }}"
-       order_user = "This is value the value2"
-       expected_result = {'variable': 'value',
-                          'variable2': 'value2'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
-                        "Fail to match the order_brain multi variable to the multi values")
-
-       ##
-       # Testing multi words in variable
-       ##
-
-       # Success
-       order_brain = "This is the {{ variable }}"
-       order_user = "This is the value with multiple words"
-       expected_result = {'variable': 'value with multiple words'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user,order_brain), expected_result,
-                        "Fail to match the order_brain {{ variable }} to the 'value with multiple words'")
-
-       # Success
-       order_brain = "This is the {{ variable }} and  {{ variable2 }}"
-       order_user = "This is the value with multiple words and second value multiple"
-       expected_result = {'variable': 'value with multiple words',
-                          'variable2': 'second value multiple'}
-       self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user,order_brain), expected_result,
-                        "Fail to match the order_brain multiple variables with multiple words as values'")
+        ##
+        # Testing the brackets position behaviour
+        ##
+
+        # Success
+        order_brain = "This is the {{ variable }}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain {{ variable }} to the 'value'")
+
+        # Success
+        order_brain = "This is the {{variable }}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain {{variable }} to the 'value'")
+
+        # Success
+        order_brain = "This is the {{ variable}}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain {{ variable}} to the 'value'")
+
+        # Success
+        order_brain = "This is the {{variable}}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain {{variable}} to the 'value'")
+
+        # Fail
+        order_brain = "This is the {variable}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertNotEquals(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                             "Should not match the order_brain {variable} to the 'value'")
+
+        # Fail
+        order_brain = "This is the { variable}}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertNotEquals(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                             "Should not match the order_brain { variable}} to the 'value'")
+
+        ##
+        # Testing the brackets position in the sentence
+        ##
+
+        # Success
+        order_brain = "{{ variable }} This is the"
+        order_user = "value This is the"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain {{ variable }} in first position "
+                         "ins the sentence to the 'value'")
+
+        # Success
+        order_brain = "This is {{ variable }} the"
+        order_user = " This is value the"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain {{ variable }} in middle position ins "
+                         "the sentence to the 'value'")
+
+        ##
+        # Testing multi variables
+        ##
+
+        # Success
+        order_brain = "This is {{ variable }} the {{ variable2 }}"
+        order_user = "This is value the value2"
+        expected_result = {'variable': 'value',
+                           'variable2': 'value2'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain multi variable to the multi values")
+
+        ##
+        # Testing multi words in variable
+        ##
+
+        # Success
+        order_brain = "This is the {{ variable }}"
+        order_user = "This is the value with multiple words"
+        expected_result = {'variable': 'value with multiple words'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain {{ variable }} to the 'value with multiple words'")
+
+        # Success
+        order_brain = "This is the {{ variable }} and  {{ variable2 }}"
+        order_user = "This is the value with multiple words and second value multiple"
+        expected_result = {'variable': 'value with multiple words',
+                           'variable2': 'second value multiple'}
+        self.assertEqual(OrderAnalyser._associate_order_params_to_values(order_user, order_brain), expected_result,
+                         "Fail to match the order_brain multiple variables with multiple words as values'")
+
+    def test_get_matching_synapse_list(self):
+        # Init
+        neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
+        neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2'})
+        neuron3 = Neuron(name='neurone3', parameters={'var3': 'val3'})
+        neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4'})
+
+        signal1 = Order(sentence="this is the sentence")
+        signal2 = Order(sentence="this is the second sentence")
+        signal3 = Order(sentence="this is the third sentence")
+
+        synapse1 = Synapse(name="Synapse1", neurons={neuron1, neuron2}, signals={signal1})
+        synapse2 = Synapse(name="Synapse2", neurons={neuron3, neuron4}, signals={signal2})
+        synapse3 = Synapse(name="Synapse3", neurons={neuron2, neuron4}, signals={signal3})
+
+        order_to_match = "this is the sentence"
+        all_synapse_list = [synapse1,
+                            synapse2,
+                            synapse3]
+
+        expected_result = [synapse1]
+
+        # Success
+        self.assertEquals(OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
+                                                                   order_to_match=order_to_match),
+                          expected_result,
+                          "Fail matching the expected synapse from the complete synapse list and the order")
+
+        # TODO : to be continued
+
+    def test_get_synapse_params(self):
+        # Init
+        neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
+        neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2'})
+
+        signal1 = Order(sentence="this is the {{ sentence }}")
+
+        synapse1 = Synapse(name="Synapse1", neurons={neuron1, neuron2}, signals={signal1})
+
+        order_to_check = "this is the value"
+        expected_result = {'sentence': 'value'}
+
+        self.assertEquals(OrderAnalyser._get_synapse_params(synapse=synapse1, order_to_check=order_to_check),
+                          expected_result,
+                          "Fail to retrieve the params of the synapse from the order")
+
+        # TODO : to be continued
+
 
 if __name__ == '__main__':
-    unittest.main()
+    unittest.main()