瀏覽代碼

Merge pull request #242 from kalliope-project/oa_refactor

Order Analyser refactor
Nicolas Marcq 8 年之前
父節點
當前提交
ba0e85c145

+ 0 - 1
Tests/__init__.py

@@ -2,7 +2,6 @@ from test_brain_loader import TestBrainLoader
 from test_configuration_checker import TestConfigurationChecker
 from test_dynamic_loading import TestDynamicLoading
 from test_file_manager import TestFileManager
-from test_order_analyser import TestOrderAnalyser
 from test_rest_api import TestRestAPI
 from test_settings_loader import TestSettingLoader
 from test_singleton import TestSingleton

+ 587 - 0
Tests/backup_test_order_analyser.py

@@ -0,0 +1,587 @@
+import unittest
+import mock
+
+from kalliope.core.OrderAnalyser import OrderAnalyser
+from kalliope.core.Models.Neuron import Neuron
+from kalliope.core.Models.Synapse import Synapse
+from kalliope.core.Models.Brain import Brain
+from kalliope.core.Models.Settings import Settings
+from kalliope.core.Models.Order import Order
+
+
+class TestOrderAnalyser(unittest.TestCase):
+
+    """Test case for the OrderAnalyser Class"""
+
+    def setUp(self):
+        pass
+
+    def test_start(self):
+        """
+        Testing if the matches from the incoming messages and the signals/order sentences.
+        Scenarii :
+            - Order matchs a synapse and the synapse has been launched.
+            - Order does not match but have a default synapse.
+            - Order does not match and does not have default synapse.
+            - Provide synapse without any external orders
+            - Provide synapse with any external orders
+        """
+        # 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="that is part of 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])
+
+        all_synapse_list = [synapse1,
+                            synapse2,
+                            synapse3]
+
+        br = Brain(synapses=all_synapse_list)
+
+        with mock.patch("kalliope.core.OrderAnalyser._start_neuron") as mock_start_neuron_method:
+            # assert synapses have been launched
+            order_to_match = "this is the sentence"
+            oa = OrderAnalyser(order=order_to_match,
+                               brain=br)
+            expected_result = [synapse1]
+
+            self.assertEquals(oa.start(),
+                              expected_result,
+                              "Fail to run the expected Synapse matching the order")
+
+            calls = [mock.call(neuron1, {}), mock.call(neuron2, {})]
+            mock_start_neuron_method.assert_has_calls(calls=calls)
+            mock_start_neuron_method.reset_mock()
+
+            # No order matching Default Synapse to run
+            order_to_match = "random sentence"
+            oa = OrderAnalyser(order=order_to_match,
+                               brain=br)
+            oa.settings = mock.MagicMock(default_synapse="Synapse3")
+            expected_result = [synapse3]
+            self.assertEquals(oa.start(),
+                              expected_result,
+                              "Fail to run the default Synapse because no other synapses match the order")
+
+            # No order matching no Default Synapse
+            order_to_match = "random sentence"
+            oa = OrderAnalyser(order=order_to_match,
+                               brain=br)
+            oa.settings = mock.MagicMock()
+            expected_result = []
+            self.assertEquals(oa.start(),
+                              expected_result,
+                              "Fail to no synapse because no synapse matchs and no default defined")
+
+            # Provide synapse to run
+            order_to_match = "this is the sentence"
+            oa = OrderAnalyser(order=order_to_match,
+                               brain=br)
+            expected_result = [synapse1]
+            synapses_to_run = [synapse1]
+
+            self.assertEquals(oa.start(synapses_to_run=synapses_to_run),
+                              expected_result,
+                              "Fail to run the provided synapse to run")
+            calls = [mock.call(neuron1, {}), mock.call(neuron2, {})]
+            mock_start_neuron_method.assert_has_calls(calls=calls)
+            mock_start_neuron_method.reset_mock()
+
+            # Provide synapse and external orders
+            order_to_match = "this is an external sentence"
+            oa = OrderAnalyser(order=order_to_match,
+                               brain=br)
+            external_orders = "this is an external {{ order }}"
+            synapses_to_run = [synapse2]
+            expected_result = [synapse2]
+
+            self.assertEquals(oa.start(synapses_to_run=synapses_to_run, external_order=external_orders),
+                              expected_result,
+                              "Fail to run a provided synapse with external order")
+            calls = [mock.call(neuron3, {"order":u"sentence"}), mock.call(neuron4, {"order":u"sentence"})]
+            mock_start_neuron_method.assert_has_calls(calls=calls)
+            mock_start_neuron_method.reset_mock()
+
+    def test_start_neuron(self):
+        """
+        Testing params association and starting a Neuron
+        """
+
+        neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4'})
+
+        with mock.patch("kalliope.core.NeuronLauncher.NeuronLauncher.start_neuron") as mock_start_neuron_method:
+            # Assert to the neuron is launched
+            neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
+            params = {
+                'param1':'parval1'
+            }
+            OrderAnalyser._start_neuron(neuron=neuron1,params=params)
+            mock_start_neuron_method.assert_called_with(neuron1)
+            mock_start_neuron_method.reset_mock()
+
+            # Assert the params are well passed to the neuron
+            neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2', 'args': ['arg1', 'arg2']})
+            params = {
+                'arg1':'argval1',
+                'arg2':'argval2'
+            }
+            OrderAnalyser._start_neuron(neuron=neuron2, params=params)
+            neuron2_params = Neuron(name='neurone2',
+                                    parameters={'var2': 'val2',
+                                                'args': ['arg1', 'arg2'],
+                                                'arg1':'argval1',
+                                                'arg2':'argval2'}
+                                    )
+            mock_start_neuron_method.assert_called_with(neuron2_params)
+            mock_start_neuron_method.reset_mock()
+
+            # Assert the Neuron is not started when missing args
+            neuron3 = Neuron(name='neurone3', parameters={'var3': 'val3', 'args': ['arg3', 'arg4']})
+            params = {
+                'arg1': 'argval1',
+                'arg2': 'argval2'
+            }
+            OrderAnalyser._start_neuron(neuron=neuron3, params=params)
+            mock_start_neuron_method.assert_not_called()
+            mock_start_neuron_method.reset_mock()
+
+            # Assert no neuron is launched when waiting for args and none are given
+            neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4', 'args': ['arg5', 'arg6']})
+            params = {}
+            OrderAnalyser._start_neuron(neuron=neuron4, params=params)
+            mock_start_neuron_method.assert_not_called()
+            mock_start_neuron_method.reset_mock()
+
+    def test_spelt_order_match_brain_order_via_table(self):
+        order_to_test = "this is the order"
+        sentence_to_test = "this is the order"
+
+        # Success
+        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test),
+                        "Fail matching order with the expected sentence")
+
+        # Failure
+        sentence_to_test = "unexpected sentence"
+        self.assertFalse(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test),
+                         "Fail to ensure the expected sentence is not matching the order")
+
+        # Upper/lower cases
+        sentence_to_test = "THIS is THE order"
+        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test),
+                        "Fail matching Upper/lower cases")
+
+    def test_format_sentences_to_analyse(self):
+        # First capital in sentence
+        order_to_test = "this is the order"
+        sentence_to_test = "This is the order"
+        expected_result = "this is the order", "this is the order"
+        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
+                                                                    user_said=sentence_to_test),
+                         expected_result,
+                         "Fails formatting the sentences with first capital in sentence")
+
+        # random uppercase in sentence
+        order_to_test = "this is the order"
+        sentence_to_test = "This IS the ordeR"
+        expected_result = "this is the order", "this is the order"
+        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
+                                                                    user_said=sentence_to_test),
+                         expected_result,
+                         "Fails formatting the sentences with random in sentence")
+
+        # random uppercase in order
+        order_to_test = "thiS is THE orDer"
+        sentence_to_test = "this is the order"
+        expected_result = "this is the order", "this is the order"
+        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
+                                                                    user_said=sentence_to_test),
+                         expected_result,
+                         "Fails formatting the sentences with random in order")
+
+        # random uppercase in both order and sentence
+        order_to_test = "thiS is THE orDer"
+        sentence_to_test = "THIS is the Order"
+        expected_result = "this is the order", "this is the order"
+        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
+                                                                    user_said=sentence_to_test),
+                         expected_result,
+                         "Fails formatting the sentences with random in both order and sentence")
+
+    def test_get_split_order_without_bracket(self):
+        # 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,
+                         "No brackets Fails to return the expected list")
+
+        order_to_test = "this is the {{ order }}"
+        expected_result = ["this", "is", "the"]
+        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
+        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
+        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")
+
+        order_to_test = "this is the {{order}}"  # bracket without space
+        expected_result = ["this", "is", "the"]
+        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
+                         "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'")
+
+        ##
+        #  Specific Behaviour
+        ##
+
+        # Upper/Lower case
+        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 when using Upper/Lower cases")
+
+    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="that is part of 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]
+
+
+
+        # Success
+        expected_result = synapse1
+        oa_tuple_list = OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
+                                                                   order_to_match=order_to_match)
+        self.assertEquals(oa_tuple_list[0].synapse,
+                          expected_result,
+                          "Fail matching 'the expected synapse' from the complete synapse list and the order")
+
+        # Multiple Matching synapses
+        signal2 = Order(sentence="this is the sentence")
+
+        synapse2 = Synapse(name="Synapse2", neurons=[neuron3, neuron4], signals=[signal2])
+        order_to_match = "this is the sentence"
+
+        all_synapse_list = [synapse1,
+                            synapse2,
+                            synapse3]
+
+        expected_result = [synapse1,
+                           synapse2]
+        oa_tuple_list = OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
+                                                                 order_to_match=order_to_match)
+        self.assertEquals(oa_tuple_list[0].synapse,
+                          expected_result[0],
+                          "Fail 'Multiple Matching synapses' from the complete synapse list and the order (first element)")
+        self.assertEquals(oa_tuple_list[1].synapse,
+                          expected_result[1],
+                          "Fail 'Multiple Matching synapses' from the complete synapse list and the order (second element)")
+
+        # matching no synapses
+        order_to_match = "this is not the correct word"
+
+        all_synapse_list = [synapse1,
+                            synapse2,
+                            synapse3]
+
+        expected_result = []
+
+        self.assertEquals(OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
+                                                                   order_to_match=order_to_match),
+                          expected_result,
+                          "Fail matching 'no synapses' from the complete synapse list and the order")
+
+        # matching synapse with all key worlds
+        # /!\ Some words in the order are matching all words in synapses signals !
+        order_to_match = "this is not the correct sentence"
+        all_synapse_list = [synapse1,
+                            synapse2,
+                            synapse3]
+
+        expected_result = [synapse1,
+                           synapse2]
+
+        oa_tuple_list = OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
+                                                                 order_to_match=order_to_match)
+
+        self.assertEquals(oa_tuple_list[0].synapse,
+                          expected_result[0],
+                          "Fail matching 'synapse with all key worlds' from the complete synapse list and the order (first element)")
+        self.assertEquals(oa_tuple_list[1].synapse,
+                          expected_result[1],
+                          "Fail matching 'synapse with all key worlds' from the complete synapse list and the order (second element)")
+
+    def test_get_params_from_order(self):
+
+        string_order = "this is the {{ sentence }}"
+        order_to_check = "this is the value"
+        expected_result = {'sentence': 'value'}
+
+        self.assertEquals(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
+                          expected_result,
+                          "Fail to retrieve 'the params' of the string_order from the order")
+
+        # Multiple match
+        string_order = "this is the {{ sentence }}"
+
+        order_to_check = "this is the value with multiple words"
+        expected_result = {'sentence': 'value with multiple words'}
+
+        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
+                         expected_result,
+                         "Fail to retrieve the 'multiple words params' of the string_order from the order")
+
+        # Multiple params
+        string_order = "this is the {{ sentence }} with multiple {{ params }}"
+
+        order_to_check = "this is the value with multiple words"
+        expected_result = {'sentence': 'value',
+                            'params':'words'}
+
+        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
+                         expected_result,
+                         "Fail to retrieve the 'multiple params' of the string_order from the order")
+
+        # Multiple params with multiple words
+        string_order = "this is the {{ sentence }} with multiple {{ params }}"
+
+        order_to_check = "this is the multiple values with multiple values as words"
+        expected_result = {'sentence': 'multiple values',
+                           'params': 'values as words'}
+
+        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
+                         expected_result,
+                         "Fail to retrieve the 'multiple params with multiple words' of the string_order from the order")
+
+        # params at the begining of the sentence
+        string_order = "{{ sentence }} this is the sentence"
+
+        order_to_check = "hello world this is the multiple values with multiple values as words"
+        expected_result = {'sentence': 'hello world'}
+
+        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
+                         expected_result,
+                         "Fail to retrieve the 'params at the begining of the sentence' of the string_order from the order")
+
+        # all of the sentence is a variable
+        string_order = "{{ sentence }}"
+
+        order_to_check = "this is the all sentence is a variable"
+        expected_result = {'sentence': 'this is the all sentence is a variable'}
+
+        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
+                         expected_result,
+                         "Fail to retrieve the 'all of the sentence is a variable' of the string_order from the order")
+
+    def test_get_default_synapse_from_sysnapses_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="that is part of 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])
+
+        default_synapse_name = "Synapse2"
+        all_synapse_list = [synapse1,
+                            synapse2,
+                            synapse3]
+        expected_result = synapse2
+
+        # Assert equals
+        self.assertEquals(OrderAnalyser._get_default_synapse_from_sysnapses_list(all_synapses_list=all_synapse_list,
+                                                                                 default_synapse_name=default_synapse_name),
+                          expected_result,
+                          "Fail to match the expected default Synapse")
+
+    def test_find_synapse_to_run(self):
+        """
+        Test to find the good synapse to run
+        Scenarii:
+            - 1/ Find the synapse
+            - 2/ No synpase found, no default synapse
+            - 3/ No synapse found, run the default synapse
+        """
+        # 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="that is part of 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])
+
+        all_synapse_list = [synapse1,
+                            synapse2,
+                            synapse3]
+
+        br = Brain(synapses=all_synapse_list)
+        st = Settings()
+        # 1/ Find synapse
+        order = "this is the sentence"
+        expected_result = synapse1
+        oa_tuple_list = OrderAnalyser._find_synapse_to_run(brain=br,settings=st, order=order)
+        self.assertEquals(oa_tuple_list[0].synapse,
+                          expected_result,
+                          "Fail to run the proper synapse matching the order")
+
+        expected_result = signal1.sentence
+        self.assertEquals(oa_tuple_list[0].order,
+                          expected_result,
+                          "Fail to run the proper synapse matching the order")
+
+        # 2/ No Default synapse
+        order = "No default synapse"
+        expected_result = []
+        self.assertEquals(OrderAnalyser._find_synapse_to_run(brain=br,settings=st, order=order),
+                          expected_result,
+                          "Fail to run no synapse, when no default is defined")
+
+        # 3/ Default synapse
+        st = Settings(default_synapse="Synapse2")
+        order = "default synapse"
+        expected_result = synapse2
+        oa_tuple_list = OrderAnalyser._find_synapse_to_run(brain=br, settings=st, order=order)
+        self.assertEquals(oa_tuple_list[0].synapse,
+                          expected_result,
+                          "Fail to run the default synapse")
+
+
+if __name__ == '__main__':
+    unittest.main()

+ 15 - 16
Tests/test_neuron_module.py

@@ -145,31 +145,30 @@ class TestNeuronModule(unittest.TestCase):
         order = "This is the order"
         synapse_name = "Synapse2"
         answer = "This is the {{ answer }}"
+        expected_parameter = {"answer": "order"}
 
-        with mock.patch("kalliope.core.OrderAnalyser.start") as mock_orderAnalyser_start:
+        with mock.patch("kalliope.core.NeuronLauncher.start_neuron_list") as mock_NeuronLauncher_start:
             neuron_mod = NeuronModule()
             neuron_mod.brain = br
 
-            # Success
-            self.assertTrue(neuron_mod.run_synapse_by_name_with_order(order=order,
-                                                                        synapse_name=synapse_name,
-                                                                        order_template=answer),
-                              "fail to find the proper synapse")
+            # Success, run synapse 2
+            launched_synapse = neuron_mod.run_synapse_by_name_with_order(order=order,
+                                                                         synapse_name=synapse_name,
+                                                                         order_template=answer)
+            self.assertEqual(synapse2, launched_synapse)
 
-            # mock_orderAnalyser_start.assert_called_once()
-            mock_orderAnalyser_start.assert_called_once_with(synapses_to_run=[synapse2],
-                                                             external_order=answer)
-            mock_orderAnalyser_start.reset_mock()
+            mock_NeuronLauncher_start.assert_called_once_with(neuron_list=[neuron3, neuron4],
+                                                              parameters_dict=expected_parameter)
+            mock_NeuronLauncher_start.reset_mock()
 
             # Fail
             synapse_name = "Synapse5"
-            self.assertFalse(neuron_mod.run_synapse_by_name_with_order(order=order,
-                                                                      synapse_name=synapse_name,
-                                                                       order_template=answer),
-                            "fail to NOT find the synapse")
+            self.assertIsNone(neuron_mod.run_synapse_by_name_with_order(order=order,
+                                                                        synapse_name=synapse_name,
+                                                                        order_template=answer))
 
-            mock_orderAnalyser_start.assert_not_called()
-            mock_orderAnalyser_start.reset_mock()
+            mock_NeuronLauncher_start.assert_not_called()
+            mock_NeuronLauncher_start.reset_mock()
 
 
 

+ 175 - 0
Tests/test_neuron_parameter_loader.py

@@ -0,0 +1,175 @@
+import unittest
+
+from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
+
+
+class TestNeuronParameterLoader(unittest.TestCase):
+
+    def test_get_parameters(self):
+
+        synapse_order = "this is the {{ sentence }}"
+        user_order = "this is the value"
+        expected_result = {'sentence': 'value'}
+
+        self.assertEquals(NeuronParameterLoader.get_parameters(synapse_order=synapse_order, user_order=user_order),
+                          expected_result,
+                          "Fail to retrieve 'the params' of the synapse_order from the order")
+
+        # Multiple match
+        synapse_order = "this is the {{ sentence }}"
+
+        user_order = "this is the value with multiple words"
+        expected_result = {'sentence': 'value with multiple words'}
+
+        self.assertEqual(NeuronParameterLoader.get_parameters(synapse_order=synapse_order, user_order=user_order),
+                         expected_result,
+                         "Fail to retrieve the 'multiple words params' of the synapse_order from the order")
+
+        # Multiple params
+        synapse_order = "this is the {{ sentence }} with multiple {{ params }}"
+
+        user_order = "this is the value with multiple words"
+        expected_result = {'sentence': 'value',
+                            'params':'words'}
+
+        self.assertEqual(NeuronParameterLoader.get_parameters(synapse_order=synapse_order, user_order=user_order),
+                         expected_result,
+                         "Fail to retrieve the 'multiple params' of the synapse_order from the order")
+
+        # Multiple params with multiple words
+        synapse_order = "this is the {{ sentence }} with multiple {{ params }}"
+
+        user_order = "this is the multiple values with multiple values as words"
+        expected_result = {'sentence': 'multiple values',
+                           'params': 'values as words'}
+
+        self.assertEqual(NeuronParameterLoader.get_parameters(synapse_order=synapse_order, user_order=user_order),
+                         expected_result)
+
+        # params at the begining of the sentence
+        synapse_order = "{{ sentence }} this is the sentence"
+
+        user_order = "hello world this is the multiple values with multiple values as words"
+        expected_result = {'sentence': 'hello world'}
+
+        self.assertEqual(NeuronParameterLoader.get_parameters(synapse_order=synapse_order, user_order=user_order),
+                         expected_result)
+
+        # all of the sentence is a variable
+        synapse_order = "{{ sentence }}"
+
+        user_order = "this is the all sentence is a variable"
+        expected_result = {'sentence': 'this is the all sentence is a variable'}
+
+        self.assertEqual(NeuronParameterLoader.get_parameters(synapse_order=synapse_order, user_order=user_order),
+                         expected_result)
+
+    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(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        # Success
+        order_brain = "This is the {{variable }}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        # Success
+        order_brain = "This is the {{ variable}}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        # Success
+        order_brain = "This is the {{variable}}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        # Fail
+        order_brain = "This is the {variable}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertNotEquals(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                             expected_result)
+
+        # Fail
+        order_brain = "This is the { variable}}"
+        order_user = "This is the value"
+        expected_result = {'variable': 'value'}
+        self.assertNotEquals(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                             expected_result)
+
+        ##
+        # 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(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        # Success
+        order_brain = "This is {{ variable }} the"
+        order_user = " This is value the"
+        expected_result = {'variable': 'value'}
+        self.assertEqual(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        ##
+        # 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(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        ##
+        # 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(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        # 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(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+        ##
+        #  Specific Behaviour
+        ##
+
+        # Upper/Lower case
+        order_brain = "This Is The {{ variable }}"
+        order_user = "ThiS is tHe VAlue"
+        expected_result = {'variable': 'VAlue'}
+        self.assertEqual(NeuronParameterLoader._associate_order_params_to_values(order_user, order_brain),
+                         expected_result)
+
+if __name__ == '__main__':
+    unittest.main()

+ 30 - 508
Tests/test_order_analyser.py

@@ -1,12 +1,11 @@
 import unittest
-import mock
 
+
+from kalliope.core.Models import Brain
+from kalliope.core.Models import Neuron
+from kalliope.core.Models import Order
+from kalliope.core.Models import Synapse
 from kalliope.core.OrderAnalyser import OrderAnalyser
-from kalliope.core.Models.Neuron import Neuron
-from kalliope.core.Models.Synapse import Synapse
-from kalliope.core.Models.Brain import Brain
-from kalliope.core.Models.Settings import Settings
-from kalliope.core.Models.Order import Order
 
 
 class TestOrderAnalyser(unittest.TestCase):
@@ -16,16 +15,7 @@ class TestOrderAnalyser(unittest.TestCase):
     def setUp(self):
         pass
 
-    def test_start(self):
-        """
-        Testing if the matches from the incoming messages and the signals/order sentences.
-        Scenarii :
-            - Order matchs a synapse and the synapse has been launched.
-            - Order does not match but have a default synapse.
-            - Order does not match and does not have default synapse.
-            - Provide synapse without any external orders
-            - Provide synapse with any external orders
-        """
+    def test_get_matching_synapse(self):
         # Init
         neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
         neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2'})
@@ -46,174 +36,37 @@ class TestOrderAnalyser(unittest.TestCase):
 
         br = Brain(synapses=all_synapse_list)
 
-        with mock.patch("kalliope.core.OrderAnalyser._start_neuron") as mock_start_neuron_method:
-            # assert synapses have been launched
-            order_to_match = "this is the sentence"
-            oa = OrderAnalyser(order=order_to_match,
-                               brain=br)
-            expected_result = [synapse1]
-
-            self.assertEquals(oa.start(),
-                              expected_result,
-                              "Fail to run the expected Synapse matching the order")
-
-            calls = [mock.call(neuron1, {}), mock.call(neuron2, {})]
-            mock_start_neuron_method.assert_has_calls(calls=calls)
-            mock_start_neuron_method.reset_mock()
-
-            # No order matching Default Synapse to run
-            order_to_match = "random sentence"
-            oa = OrderAnalyser(order=order_to_match,
-                               brain=br)
-            oa.settings = mock.MagicMock(default_synapse="Synapse3")
-            expected_result = [synapse3]
-            self.assertEquals(oa.start(),
-                              expected_result,
-                              "Fail to run the default Synapse because no other synapses match the order")
-
-            # No order matching no Default Synapse
-            order_to_match = "random sentence"
-            oa = OrderAnalyser(order=order_to_match,
-                               brain=br)
-            oa.settings = mock.MagicMock()
-            expected_result = []
-            self.assertEquals(oa.start(),
-                              expected_result,
-                              "Fail to no synapse because no synapse matchs and no default defined")
+        # TEST1: should return synapse1
+        spoken_order = "this is the sentence"
+        matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
+        self.assertEqual(len(matched_synapses), 1)
+        self.assertTrue(any(synapse1 in matched_synapse for matched_synapse in matched_synapses))
 
-            # Provide synapse to run
-            order_to_match = "this is the sentence"
-            oa = OrderAnalyser(order=order_to_match,
-                               brain=br)
-            expected_result = [synapse1]
-            synapses_to_run = [synapse1]
+        # TEST2: should return synapse1 and 2
+        spoken_order = "this is the second sentence"
+        matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
+        self.assertEqual(len(matched_synapses), 2)
+        self.assertTrue(synapse1, synapse2 in matched_synapses)
 
-            self.assertEquals(oa.start(synapses_to_run=synapses_to_run),
-                              expected_result,
-                              "Fail to run the provided synapse to run")
-            calls = [mock.call(neuron1, {}), mock.call(neuron2, {})]
-            mock_start_neuron_method.assert_has_calls(calls=calls)
-            mock_start_neuron_method.reset_mock()
-
-            # Provide synapse and external orders
-            order_to_match = "this is an external sentence"
-            oa = OrderAnalyser(order=order_to_match,
-                               brain=br)
-            external_orders = "this is an external {{ order }}"
-            synapses_to_run = [synapse2]
-            expected_result = [synapse2]
-
-            self.assertEquals(oa.start(synapses_to_run=synapses_to_run, external_order=external_orders),
-                              expected_result,
-                              "Fail to run a provided synapse with external order")
-            calls = [mock.call(neuron3, {"order":u"sentence"}), mock.call(neuron4, {"order":u"sentence"})]
-            mock_start_neuron_method.assert_has_calls(calls=calls)
-            mock_start_neuron_method.reset_mock()
-
-    def test_start_neuron(self):
-        """
-        Testing params association and starting a Neuron
-        """
-
-        neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4'})
-
-        with mock.patch("kalliope.core.NeuronLauncher.NeuronLauncher.start_neuron") as mock_start_neuron_method:
-            # Assert to the neuron is launched
-            neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
-            params = {
-                'param1':'parval1'
-            }
-            OrderAnalyser._start_neuron(neuron=neuron1,params=params)
-            mock_start_neuron_method.assert_called_with(neuron1)
-            mock_start_neuron_method.reset_mock()
-
-            # Assert the params are well passed to the neuron
-            neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2', 'args': ['arg1', 'arg2']})
-            params = {
-                'arg1':'argval1',
-                'arg2':'argval2'
-            }
-            OrderAnalyser._start_neuron(neuron=neuron2, params=params)
-            neuron2_params = Neuron(name='neurone2',
-                                    parameters={'var2': 'val2',
-                                                'args': ['arg1', 'arg2'],
-                                                'arg1':'argval1',
-                                                'arg2':'argval2'}
-                                    )
-            mock_start_neuron_method.assert_called_with(neuron2_params)
-            mock_start_neuron_method.reset_mock()
-
-            # Assert the Neuron is not started when missing args
-            neuron3 = Neuron(name='neurone3', parameters={'var3': 'val3', 'args': ['arg3', 'arg4']})
-            params = {
-                'arg1': 'argval1',
-                'arg2': 'argval2'
-            }
-            OrderAnalyser._start_neuron(neuron=neuron3, params=params)
-            mock_start_neuron_method.assert_not_called()
-            mock_start_neuron_method.reset_mock()
-
-            # Assert no neuron is launched when waiting for args and none are given
-            neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4', 'args': ['arg5', 'arg6']})
-            params = {}
-            OrderAnalyser._start_neuron(neuron=neuron4, params=params)
-            mock_start_neuron_method.assert_not_called()
-            mock_start_neuron_method.reset_mock()
+        # TEST3: should empty
+        spoken_order = "not a valid order"
+        matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
+        self.assertFalse(matched_synapses)
 
     def test_spelt_order_match_brain_order_via_table(self):
         order_to_test = "this is the order"
         sentence_to_test = "this is the order"
 
         # Success
-        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test),
-                        "Fail matching order with the expected sentence")
+        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
 
         # Failure
         sentence_to_test = "unexpected sentence"
-        self.assertFalse(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test),
-                         "Fail to ensure the expected sentence is not matching the order")
+        self.assertFalse(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
 
         # Upper/lower cases
         sentence_to_test = "THIS is THE order"
-        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test),
-                        "Fail matching Upper/lower cases")
-
-    def test_format_sentences_to_analyse(self):
-        # First capital in sentence
-        order_to_test = "this is the order"
-        sentence_to_test = "This is the order"
-        expected_result = "this is the order", "this is the order"
-        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
-                                                                    user_said=sentence_to_test),
-                         expected_result,
-                         "Fails formatting the sentences with first capital in sentence")
-
-        # random uppercase in sentence
-        order_to_test = "this is the order"
-        sentence_to_test = "This IS the ordeR"
-        expected_result = "this is the order", "this is the order"
-        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
-                                                                    user_said=sentence_to_test),
-                         expected_result,
-                         "Fails formatting the sentences with random in sentence")
-
-        # random uppercase in order
-        order_to_test = "thiS is THE orDer"
-        sentence_to_test = "this is the order"
-        expected_result = "this is the order", "this is the order"
-        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
-                                                                    user_said=sentence_to_test),
-                         expected_result,
-                         "Fails formatting the sentences with random in order")
-
-        # random uppercase in both order and sentence
-        order_to_test = "thiS is THE orDer"
-        sentence_to_test = "THIS is the Order"
-        expected_result = "this is the order", "this is the order"
-        self.assertEqual(OrderAnalyser._format_sentences_to_analyse(order_to_analyse=order_to_test,
-                                                                    user_said=sentence_to_test),
-                         expected_result,
-                         "Fails formatting the sentences with random in both order and sentence")
+        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
 
     def test_get_split_order_without_bracket(self):
         # Success
@@ -242,345 +95,14 @@ class TestOrderAnalyser(unittest.TestCase):
         self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "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'")
-
-        ##
-        #  Specific Behaviour
-        ##
-
-        # Upper/Lower case
-        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 when using Upper/Lower cases")
-
-    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="that is part of 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]
-
-
-
-        # Success
-        expected_result = synapse1
-        oa_tuple_list = OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
-                                                                   order_to_match=order_to_match)
-        self.assertEquals(oa_tuple_list[0].synapse,
-                          expected_result,
-                          "Fail matching 'the expected synapse' from the complete synapse list and the order")
-
-        # Multiple Matching synapses
-        signal2 = Order(sentence="this is the sentence")
-
-        synapse2 = Synapse(name="Synapse2", neurons=[neuron3, neuron4], signals=[signal2])
-        order_to_match = "this is the sentence"
-
-        all_synapse_list = [synapse1,
-                            synapse2,
-                            synapse3]
-
-        expected_result = [synapse1,
-                           synapse2]
-        oa_tuple_list = OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
-                                                                 order_to_match=order_to_match)
-        self.assertEquals(oa_tuple_list[0].synapse,
-                          expected_result[0],
-                          "Fail 'Multiple Matching synapses' from the complete synapse list and the order (first element)")
-        self.assertEquals(oa_tuple_list[1].synapse,
-                          expected_result[1],
-                          "Fail 'Multiple Matching synapses' from the complete synapse list and the order (second element)")
-
-        # matching no synapses
-        order_to_match = "this is not the correct word"
-
-        all_synapse_list = [synapse1,
-                            synapse2,
-                            synapse3]
-
-        expected_result = []
-
-        self.assertEquals(OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
-                                                                   order_to_match=order_to_match),
-                          expected_result,
-                          "Fail matching 'no synapses' from the complete synapse list and the order")
-
-        # matching synapse with all key worlds
-        # /!\ Some words in the order are matching all words in synapses signals !
-        order_to_match = "this is not the correct sentence"
-        all_synapse_list = [synapse1,
-                            synapse2,
-                            synapse3]
-
-        expected_result = [synapse1,
-                           synapse2]
-
-        oa_tuple_list = OrderAnalyser._get_matching_synapse_list(all_synapses_list=all_synapse_list,
-                                                                 order_to_match=order_to_match)
-
-        self.assertEquals(oa_tuple_list[0].synapse,
-                          expected_result[0],
-                          "Fail matching 'synapse with all key worlds' from the complete synapse list and the order (first element)")
-        self.assertEquals(oa_tuple_list[1].synapse,
-                          expected_result[1],
-                          "Fail matching 'synapse with all key worlds' from the complete synapse list and the order (second element)")
-
-    def test_get_params_from_order(self):
-
-        string_order = "this is the {{ sentence }}"
-        order_to_check = "this is the value"
-        expected_result = {'sentence': 'value'}
-
-        self.assertEquals(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
-                          expected_result,
-                          "Fail to retrieve 'the params' of the string_order from the order")
-
-        # Multiple match
-        string_order = "this is the {{ sentence }}"
-
-        order_to_check = "this is the value with multiple words"
-        expected_result = {'sentence': 'value with multiple words'}
-
-        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
-                         expected_result,
-                         "Fail to retrieve the 'multiple words params' of the string_order from the order")
-
-        # Multiple params
-        string_order = "this is the {{ sentence }} with multiple {{ params }}"
-
-        order_to_check = "this is the value with multiple words"
-        expected_result = {'sentence': 'value',
-                            'params':'words'}
-
-        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
-                         expected_result,
-                         "Fail to retrieve the 'multiple params' of the string_order from the order")
-
-        # Multiple params with multiple words
-        string_order = "this is the {{ sentence }} with multiple {{ params }}"
-
-        order_to_check = "this is the multiple values with multiple values as words"
-        expected_result = {'sentence': 'multiple values',
-                           'params': 'values as words'}
-
-        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
-                         expected_result,
-                         "Fail to retrieve the 'multiple params with multiple words' of the string_order from the order")
-
-        # params at the begining of the sentence
-        string_order = "{{ sentence }} this is the sentence"
-
-        order_to_check = "hello world this is the multiple values with multiple values as words"
-        expected_result = {'sentence': 'hello world'}
-
-        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
-                         expected_result,
-                         "Fail to retrieve the 'params at the begining of the sentence' of the string_order from the order")
-
-        # all of the sentence is a variable
-        string_order = "{{ sentence }}"
-
-        order_to_check = "this is the all sentence is a variable"
-        expected_result = {'sentence': 'this is the all sentence is a variable'}
-
-        self.assertEqual(OrderAnalyser._get_params_from_order(string_order=string_order, order_to_check=order_to_check),
-                         expected_result,
-                         "Fail to retrieve the 'all of the sentence is a variable' of the string_order from the order")
-
-    def test_get_default_synapse_from_sysnapses_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="that is part of 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])
-
-        default_synapse_name = "Synapse2"
-        all_synapse_list = [synapse1,
-                            synapse2,
-                            synapse3]
-        expected_result = synapse2
-
-        # Assert equals
-        self.assertEquals(OrderAnalyser._get_default_synapse_from_sysnapses_list(all_synapses_list=all_synapse_list,
-                                                                                 default_synapse_name=default_synapse_name),
-                          expected_result,
-                          "Fail to match the expected default Synapse")
-
-    def test_find_synapse_to_run(self):
-        """
-        Test to find the good synapse to run
-        Scenarii:
-            - 1/ Find the synapse
-            - 2/ No synpase found, no default synapse
-            - 3/ No synapse found, run the default synapse
-        """
-        # 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="that is part of 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])
-
-        all_synapse_list = [synapse1,
-                            synapse2,
-                            synapse3]
-
-        br = Brain(synapses=all_synapse_list)
-        st = Settings()
-        # 1/ Find synapse
-        order = "this is the sentence"
-        expected_result = synapse1
-        oa_tuple_list = OrderAnalyser._find_synapse_to_run(brain=br,settings=st, order=order)
-        self.assertEquals(oa_tuple_list[0].synapse,
-                          expected_result,
-                          "Fail to run the proper synapse matching the order")
-
-        expected_result = signal1.sentence
-        self.assertEquals(oa_tuple_list[0].order,
-                          expected_result,
-                          "Fail to run the proper synapse matching the order")
-
-        # 2/ No Default synapse
-        order = "No default synapse"
-        expected_result = []
-        self.assertEquals(OrderAnalyser._find_synapse_to_run(brain=br,settings=st, order=order),
-                          expected_result,
-                          "Fail to run no synapse, when no default is defined")
+    def test_counter_subset(self):
+        list1 = ("word1", "word2")
+        list2 = ("word3", "word4")
+        list3 = ("word1", "word2", "word3", "word4")
 
-        # 3/ Default synapse
-        st = Settings(default_synapse="Synapse2")
-        order = "default synapse"
-        expected_result = synapse2
-        oa_tuple_list = OrderAnalyser._find_synapse_to_run(brain=br, settings=st, order=order)
-        self.assertEquals(oa_tuple_list[0].synapse,
-                          expected_result,
-                          "Fail to run the default synapse")
+        self.assertFalse(OrderAnalyser._counter_subset(list1, list2))
+        self.assertTrue(OrderAnalyser._counter_subset(list1, list3))
+        self.assertTrue(OrderAnalyser._counter_subset(list2, list3))
 
 
 if __name__ == '__main__':

+ 4 - 4
Tests/test_rest_api.py

@@ -2,8 +2,6 @@ import json
 import os
 import unittest
 
-from werkzeug.datastructures import FileStorage
-
 from flask import Flask
 from flask_testing import LiveServerTestCase
 
@@ -36,6 +34,7 @@ class TestRestAPI(LiveServerTestCase):
         sl.settings.active = True
         sl.settings.port = 5000
         sl.settings.allowed_cors_origin = "*"
+        sl.settings.default_synapse = None
 
         # prepare a test brain
         brain_to_test = full_path_brain_to_test
@@ -237,7 +236,6 @@ class TestRestAPI(LiveServerTestCase):
                 }
             ]
         }
-        print result.get_data()
         self.assertEqual(json.dumps(expected_content), json.dumps(json.loads(result.get_data())))
         self.assertEqual(result.status_code, 201)
 
@@ -245,7 +243,9 @@ class TestRestAPI(LiveServerTestCase):
         url = self.get_server_url() + "/synapses/start/order"
         data = {"order": "non existing order"}
         headers = {"Content-Type": "application/json"}
-        result = self.client.post(url, headers=headers, data=json.dumps(data))
+        result = self.client.post(url,
+                                  headers=headers,
+                                  data=json.dumps(data))
 
         expected_content = {'error': {'error': "The given order doesn't match any synapses"}}
 

+ 80 - 0
Tests/test_synapse_launcher.py

@@ -0,0 +1,80 @@
+import unittest
+
+import mock
+
+from kalliope.core.Models import Brain
+from kalliope.core.Models.Settings import Settings
+from kalliope.core.SynapseLauncher import SynapseLauncher, SynapseNameNotFound
+
+from kalliope.core.Models import Neuron
+from kalliope.core.Models import Order
+from kalliope.core.Models import Synapse
+
+
+class TestSynapseLauncher(unittest.TestCase):
+    """
+    Test the class SynapseLauncher
+    """
+
+    def setUp(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="that is part of the third sentence")
+
+        self.synapse1 = Synapse(name="Synapse1", neurons=[neuron1, neuron2], signals=[signal1])
+        self.synapse2 = Synapse(name="Synapse2", neurons=[neuron3, neuron4], signals=[signal2])
+        self.synapse3 = Synapse(name="Synapse3", neurons=[neuron2, neuron4], signals=[signal3])
+
+        all_synapse_list = [self.synapse1,
+                            self.synapse2,
+                            self.synapse3]
+
+        self.brain_test = Brain(synapses=all_synapse_list)
+        self.settings_test = Settings(default_synapse="Synapse3")
+
+    def test_run_matching_synapse_or_default(self):
+
+        # test_match_synapse1
+        with mock.patch("kalliope.core.NeuronLauncher.start_neuron_list"):
+            order_to_match = "this is the sentence"
+            expected_result = [self.synapse1]
+
+            self.assertEqual(expected_result,
+                             SynapseLauncher.run_matching_synapse_or_default(order_to_match,
+                                                                             brain=self.brain_test,
+                                                                             settings=self.settings_test))
+
+        # test_match_synapse1_and_2
+        with mock.patch("kalliope.core.NeuronLauncher.start_neuron_list"):
+            order_to_match = "this is the second sentence"
+            expected_result = [self.synapse1, self.synapse2]
+
+            self.assertEqual(expected_result,
+                             SynapseLauncher.run_matching_synapse_or_default(order_to_match,
+                                                                             brain=self.brain_test,
+                                                                             settings=self.settings_test))
+
+        # test_match_default_synapse
+        with mock.patch("kalliope.core.NeuronLauncher.start_neuron"):
+            order_to_match = "this is an invalid order"
+            expected_result = [self.synapse3]
+
+            self.assertEqual(expected_result,
+                             SynapseLauncher.run_matching_synapse_or_default(order_to_match,
+                                                                             brain=self.brain_test,
+                                                                             settings=self.settings_test))
+
+    def test_start_synapse(self):
+        with mock.patch("kalliope.core.NeuronLauncher.start_neuron"):
+            expected_result = self.synapse1
+            self.assertEqual(expected_result,
+                             SynapseLauncher.start_synapse("Synapse1", brain=self.brain_test))
+
+        with self.assertRaises(SynapseNameNotFound):
+            SynapseLauncher.start_synapse(name="no_do_exist", brain=self.brain_test)

+ 5 - 5
Tests/test_utils.py

@@ -53,7 +53,7 @@ class TestUtils(unittest.TestCase):
         # Test the absolute path
         dir_path = "/tmp/kalliope/tests/"
         file_name = "test_real_file_path"
-        absolute_path_to_test = os.path.join(dir_path,file_name)
+        absolute_path_to_test = os.path.join(dir_path, file_name)
         expected_result = absolute_path_to_test
         if not os.path.exists(dir_path):
             os.makedirs(dir_path)
@@ -108,7 +108,7 @@ class TestUtils(unittest.TestCase):
         dir_path = "../kalliope/"
         file_name = "test_real_file_path"
         path_to_test = os.path.join(dir_path, file_name)
-        expected_result = os.path.normpath(os.getcwd() + os.sep + os.pardir + os.sep +"kalliope" + os.sep + file_name)
+        expected_result = os.path.normpath(os.getcwd() + os.sep + os.pardir + os.sep + "kalliope" + os.sep + file_name)
         if not os.path.exists(dir_path):
             os.makedirs(dir_path)
 
@@ -119,8 +119,8 @@ class TestUtils(unittest.TestCase):
                           expected_result,
                           "Fail to match the /an/unknown/path/kalliope path")
         # Clean up
-        if os.path.exists(file_name):
-            os.remove(file_name)
+        if os.path.exists(expected_result):
+            os.remove(expected_result)
 
     def test_get_dynamic_class_instantiation(self):
         """
@@ -222,4 +222,4 @@ class TestUtils(unittest.TestCase):
         expected_result = "This is the {{bracket}} {{second}}"
         self.assertEqual(Utils.remove_spaces_in_brackets(sentence=sentence),
                          expected_result,
-                         "Fail to remove spaces in two brackets")
+                         "Fail to remove spaces in two brackets")

+ 11 - 3
kalliope/__init__.py

@@ -5,6 +5,7 @@ import logging
 
 from kalliope.core import ShellGui
 from kalliope.core import Utils
+from kalliope.core.ConfigurationManager import SettingLoader
 from kalliope.core.ConfigurationManager.BrainLoader import BrainLoader
 from kalliope.core.EventManager import EventManager
 from kalliope.core.MainController import MainController
@@ -110,15 +111,22 @@ def main():
     brain_loader = BrainLoader(file_path=brain_file)
     brain = brain_loader.brain
 
+    # load settings
+    # get global configuration once
+    settings_loader = SettingLoader()
+    settings = settings_loader.settings
+
     if args.action == "start":
 
         # user set a synapse to start
         if args.run_synapse is not None:
-            SynapseLauncher.start_synapse(args.run_synapse, brain=brain)
+            SynapseLauncher.start_synapse(args.run_synapse,
+                                          brain=brain)
 
         if args.run_order is not None:
-            order_analyser = OrderAnalyser(args.run_order, brain=brain)
-            order_analyser.start()
+            SynapseLauncher.run_matching_synapse_or_default(args.run_order,
+                                                            brain=brain,
+                                                            settings=settings)
 
         if (args.run_synapse is None) and (args.run_order is None):
             # first, load events in event manager

+ 7 - 7
kalliope/core/MainController.py

@@ -3,6 +3,10 @@ import random
 from time import sleep
 
 from flask import Flask
+
+from kalliope.core.NeuronLauncher import NeuronLauncher
+from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
+from kalliope.core.OrderAnalyser import OrderAnalyser
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from transitions import Machine
 
@@ -108,7 +112,7 @@ class MainController:
         """
         logger.debug("Entering state: %s" % self.state)
         if (not self.on_ready_notification_played_once and self.settings.play_on_ready_notification == "once") or \
-                self.settings.play_on_ready_notification == "always":
+                        self.settings.play_on_ready_notification == "always":
             # we remember that we played the notification one time
             self.on_ready_notification_played_once = True
             # here we tell the user that we are listening
@@ -192,12 +196,8 @@ class MainController:
         Start the order analyser with the caught order to process
         """
         logger.debug("order in analysing_order_thread %s" % self.order_to_process)
-        if self.order_to_process is not None:   # maybe we have received a null audio from STT engine
-            order_analyser = OrderAnalyser(self.order_to_process, brain=self.brain)
-            order_analyser.start()
-        else:
-            if self.settings.default_synapse is not None:
-                SynapseLauncher.start_synapse(name=self.settings.default_synapse, brain=self.brain)
+        SynapseLauncher.run_matching_synapse_or_default(self.order_to_process, self.brain, self.settings)
+
         # return to the state "unpausing_trigger"
         self.unpause_trigger()
 

+ 45 - 0
kalliope/core/NeuronLauncher.py

@@ -32,3 +32,48 @@ class NeuronLauncher:
                                                      parameters=neuron.parameters,
                                                      resources_dir=neuron_folder)
 
+    @classmethod
+    def start_neuron_list(cls, neuron_list, parameters_dict=None):
+        """
+        Execute each neuron from the received neuron_list.
+        Replace parameter if exist in the received dict of parameters_dict
+        :param neuron_list: list of Neuron object to run
+        :param parameters_dict: dict of parameter to load in each neuron if expecting a parameter
+        :return: List of the instantiated neurons (no errors detected)
+        """
+
+        instantiated_neuron = list()
+
+        for neuron in neuron_list:
+            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 parameters_dict 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 parameters_dict:
+                                logger.debug("Parameter %s added to the current parameter "
+                                             "of the neuron: %s" % (arg, neuron.name))
+                                neuron.parameters[arg] = parameters_dict[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:
+                instantiated_neuron.append(cls.start_neuron(neuron))
+            else:
+                Utils.print_danger("A problem has been found in the Synapse.")
+
+        return instantiated_neuron

+ 24 - 9
kalliope/core/NeuronModule.py

@@ -1,15 +1,18 @@
 # coding: utf8
 import logging
 import random
-
 import sys
+
 from jinja2 import Template
 
 from kalliope.core import OrderListener
-from kalliope.core import OrderAnalyser
+from kalliope.core.ConfigurationManager import SettingLoader, BrainLoader
+from kalliope.core.Models import Order
+from kalliope.core.NeuronLauncher import NeuronLauncher
+from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
+from kalliope.core.OrderAnalyser import OrderAnalyser
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from kalliope.core.Utils.Utils import Utils
-from kalliope.core.ConfigurationManager import SettingLoader, BrainLoader
 
 logging.basicConfig()
 logger = logging.getLogger("kalliope")
@@ -186,9 +189,10 @@ class NeuronModule(object):
     def run_synapse_by_name(self, name):
         SynapseLauncher.start_synapse(name=name, brain=self.brain)
 
-    def is_order_matching(self, order_said, order_match):
-        oa = OrderAnalyser(order=order_said, brain=self.brain)
-        return oa.spelt_order_match_brain_order_via_table(order_to_analyse=order_match, user_said=order_said)
+    @staticmethod
+    def is_order_matching(order_said, order_match):
+        return OrderAnalyser().spelt_order_match_brain_order_via_table(order_to_analyse=order_match,
+                                                                       user_said=order_said)
 
     def run_synapse_by_name_with_order(self, order, synapse_name, order_template):
         """
@@ -206,12 +210,23 @@ class NeuronModule(object):
             list_to_run = list()
             list_to_run.append(synapse_to_run)
 
-            oa = OrderAnalyser(order=order, brain=self.brain)
-            oa.start(synapses_to_run=list_to_run, external_order=order_template)
+            # load parameters from the answer
+            parameters = None
+            for signal in synapse_to_run.signals:
+                if isinstance(signal, Order):
+                    parameters = NeuronParameterLoader.get_parameters(synapse_order=order_template,
+                                                                      user_order=order)
+                    if parameters is not None:
+                        logger.debug("[NeuronModule]-> parameter load from user answer: %s" % parameters)
+                        break
+
+            # start the neuron list
+            NeuronLauncher.start_neuron_list(neuron_list=synapse_to_run.neurons, parameters_dict=parameters)
+
         else:
             logger.debug("[NeuronModule]-> run_synapse_by_name_with_order, the synapse has not been found : %s"
                          % synapse_name)
-        return synapse_to_run is not None
+        return synapse_to_run
 
     @staticmethod
     def _get_content_of_file(real_file_template_path):

+ 65 - 0
kalliope/core/NeuronParameterLoader.py

@@ -0,0 +1,65 @@
+from kalliope.core.Utils import Utils
+
+import logging
+
+logging.basicConfig()
+logger = logging.getLogger("kalliope")
+
+
+class NeuronParameterLoader(object):
+
+    @classmethod
+    def get_parameters(cls, synapse_order, user_order):
+        """
+        Class method to get all params coming from a string order. Returns a dict of key/value.
+        """
+        params = dict()
+        if Utils.is_containing_bracket(synapse_order):
+            params = cls._associate_order_params_to_values(user_order, synapse_order)
+            logger.debug("Parameters for order: %s" % params)
+        return params
+
+    @classmethod
+    def _associate_order_params_to_values(cls, order, order_to_check):
+        """
+        Associate the variables from the order to the incoming user order
+        :param order_to_check: the order to check incoming from the brain
+        :type order_to_check: str
+        :param order: the order from user
+        :type order: str
+        :return: the dict corresponding to the key / value of the params
+        """
+        logger.debug("[OrderAnalyser._associate_order_params_to_values] user order: %s, "
+                     "order from synapse: %s" % (order, order_to_check))
+
+        list_word_in_order = Utils.remove_spaces_in_brackets(order_to_check).split()
+
+        # get the order, defined by the first words before {{
+        # /!\ Could be empty if order starts with double brace
+        the_order = order_to_check[:order_to_check.find('{{')]
+
+        # remove sentence before order which are sentences not matching anyway
+        # Manage Upper/Lower case
+        truncate_user_sentence = order[order.lower().find(the_order.lower()):]
+        truncate_list_word_said = truncate_user_sentence.split()
+
+        # make dict var:value
+        dict_var = dict()
+        for idx, ow in enumerate(list_word_in_order):
+            if Utils.is_containing_bracket(ow):
+                # remove bracket and grab the next value / stop value
+                var_name = ow.replace("{{", "").replace("}}", "")
+                stop_value = Utils.get_next_value_list(list_word_in_order[idx:])
+                if stop_value is None:
+                    dict_var[var_name] = " ".join(truncate_list_word_said)
+                    break
+                for word_said in truncate_list_word_said:
+                    if word_said == stop_value:
+                        break
+                    if var_name in dict_var:
+                        dict_var[var_name] += " " + word_said
+                        truncate_list_word_said = truncate_list_word_said[1:]
+                    else:
+                        dict_var[var_name] = word_said
+            truncate_list_word_said = truncate_list_word_said[1:]
+        return dict_var

+ 33 - 251
kalliope/core/OrderAnalyser.py

@@ -1,12 +1,10 @@
 # coding: utf8
-import re
 import collections
 from collections import Counter
 
 from kalliope.core.Utils.Utils import Utils
 from kalliope.core.ConfigurationManager import SettingLoader
 from kalliope.core.Models import Order
-from kalliope.core.NeuronLauncher import NeuronLauncher
 
 import logging
 
@@ -16,226 +14,46 @@ logger = logging.getLogger("kalliope")
 
 class OrderAnalyser:
     """
-    This Class is used to compare the incoming message to the Signal/Order sentences.
+    This Class is used to get a list of synapses that match a given Spoken order
     """
 
-    def __init__(self, order, brain=None):
-        """
-        Class used to load brain and run neuron attached to the received order
-        :param order: spelt order
-        :param brain: loaded brain
-        """
-        sl = SettingLoader()
-        self.settings = sl.settings
-        self.order = order
-        if isinstance(self.order, str):
-            self.order = order.decode('utf-8')
-        self.brain = brain
-        logger.debug("OrderAnalyser, Received order: %s" % self.order)
-
-    def start(self, synapses_to_run=None, external_order=None):
-        """
-        This method matches the incoming messages to the signals/order sentences provided in the Brain.
-
-        Note: we use named tuples:
-        tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder',['synapse', 'order'])
-        """
-
-        synapse_order_tuple = collections.namedtuple('tuple_synapse_matchingOrder', ['synapse', 'order'])
-        synapses_order_tuple_list = list()
-
-        if synapses_to_run is not None and external_order is not None:
-            for synapse in synapses_to_run:
-                synapses_order_tuple_list.append(synapse_order_tuple(synapse=synapse,
-                                                                     order=external_order))
-
-        # if list of synapse is not provided, let's find one
-        else:  # synapses_to_run is None or external_order is None:
-            # create a dict of synapses that have been launched
-            logger.debug("[orderAnalyser.start]-> No Synapse provided, let's find one")
-            synapses_order_tuple_list = self._find_synapse_to_run(brain=self.brain,
-                                                                  settings=self.settings,
-                                                                  order=self.order)
+    brain = None
+    settings = None
 
-        # retrieve params
-        synapses_launched = list()
-        for tuple in synapses_order_tuple_list:
-            logger.debug("[orderAnalyser.start]-> Grab the params")
-            params = self._get_params_from_order(tuple.order, self.order)
-
-            # Start a neuron list with params
-            self._start_list_neurons(list_neurons=tuple.synapse.neurons,
-                                     params=params,
-                                     settings=self.settings)
-            synapses_launched.append(tuple.synapse)
-
-        # return the list of launched synapse
-        return synapses_launched
+    @classmethod
+    def __init__(cls):
+        cls.settings = SettingLoader().settings
 
     @classmethod
-    def _find_synapse_to_run(cls, brain, settings, order):
+    def get_matching_synapse(cls, order, brain=None):
         """
-        Find the list of the synapse matching the order.
-
-        Note: we use named tuples:
-        tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder',['synapse', 'order'])
-
-        :param brain: the brain
-        :param settings: the settings
-        :param order: the provided order to match
-        :return: the list of synapses launched (named tuples)
+        Return the list of matching synapses from the given order
+        :param order: The user order
+        :param brain: The loaded brain
+        :return: The List of synapses matching the given order
         """
+        cls.brain = brain
+        logger.debug("[OrderAnalyser] Received order: %s" % order)
+        if isinstance(order, str):
+            order = order.decode('utf-8')
 
-        synapse_to_run = cls._get_matching_synapse_list(brain.synapses, order)
-        if not synapse_to_run:
-            Utils.print_info("No synapse match the captured order: %s" % order)
-
-            if settings.default_synapse is not None:
-                default_synapse = cls._get_default_synapse_from_sysnapses_list(brain.synapses,
-                                                                               settings.default_synapse)
-
-                if default_synapse is not None:
-                    logger.debug("Default synapse found %s" % default_synapse)
-                    Utils.print_info("Default synapse found: %s, running it" % default_synapse.name)
-                    tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder',
-                                                                         ['synapse', 'order'])
-                    synapse_to_run.append(tuple_synapse_order(synapse=default_synapse,
-                                                                      order=""))
-
-        return synapse_to_run
+        # We use a namedtuple to associate the synapse and the signal of the synapse
+        synapse_order_tuple = collections.namedtuple('tuple_synapse_matchingOrder',
+                                                     ['synapse', 'order'])
 
-    @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.
-
-        Note: we use named tuples:
-        tuple_synapse_matchingOrder = collections.namedtuple('tuple_synapse_matchingOrder',['synapse', 'order'])
+        list_match_synapse = list()
 
-        :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 (named tuples)
-        """
-        tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder', ['synapse', 'order'])
-        matching_synapses_list = list()
-        for synapse in all_synapses_list:
+        # test each synapse from the brain
+        for synapse in cls.brain.synapses:
+            # we are only concerned by synapse with a order type of signal
             for signal in synapse.signals:
                 if type(signal) == Order:
-                    if cls.spelt_order_match_brain_order_via_table(signal.sentence, order_to_match):
-                        matching_synapses_list.append(tuple_synapse_order(synapse=synapse,
-                                                                                  order=signal.sentence))
-                        logger.debug("Order found! Run neurons: %s" % synapse.neurons)
+                    if cls.spelt_order_match_brain_order_via_table(signal.sentence, order):
+                        # the order match the synapse, we add it to the returned list
+                        logger.debug("Order found! Run synapse name: %s" % synapse.name)
                         Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
-        return matching_synapses_list
-
-    @classmethod
-    def _get_params_from_order(cls, string_order, order_to_check):
-        """
-        Class method to get all params coming from a string order. Returns a dict of key/value.
-
-        :param string_order: the  string_order to check
-        :param order_to_check: the order to match
-        :type order_to_check: str
-        :return: the dict key/value
-        """
-        params = dict()
-        if Utils.is_containing_bracket(string_order):
-            params = cls._associate_order_params_to_values(order_to_check, string_order)
-            logger.debug("Parameters for order: %s" % params)
-        return params
-
-    @classmethod
-    def _start_list_neurons(cls, list_neurons, params, settings):
-        # start neurons
-        for neuron in list_neurons:
-            cls._start_neuron(neuron, params)
-
-    @staticmethod
-    def _start_neuron(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:
-            NeuronLauncher.start_neuron(neuron)
-        else:
-            Utils.print_danger("A problem has been found in the Synapse.")
-
-    @staticmethod
-    def _associate_order_params_to_values(order, order_to_check):
-        """
-        Associate the variables from the order to the incoming user order
-        :param order_to_check: the order to check incoming from the brain
-        :type order_to_check: str
-        :param order: the order from user
-        :type order: str
-        :return: the dict corresponding to the key / value of the params
-        """
-        logger.debug("[OrderAnalyser._associate_order_params_to_values] user order: %s, "
-                     "order to check: %s" % (order, order_to_check))
-
-        list_word_in_order = Utils.remove_spaces_in_brackets(order_to_check).split()
-
-        # get the order, defined by the first words before {{
-        # /!\ Could be empty if order starts with double brace
-        the_order = order_to_check[:order_to_check.find('{{')]
-
-        # remove sentence before order which are sentences not matching anyway
-        # Manage Upper/Lower case
-        truncate_user_sentence = order[order.lower().find(the_order.lower()):]
-        truncate_list_word_said = truncate_user_sentence.split()
-
-        # make dict var:value
-        dict_var = dict()
-        for idx, ow in enumerate(list_word_in_order):
-            if Utils.is_containing_bracket(ow):
-                # remove bracket and grab the next value / stop value
-                var_name = ow.replace("{{", "").replace("}}", "")
-                stop_value = Utils.get_next_value_list(list_word_in_order[idx:])
-                if stop_value is None:
-                    dict_var[var_name] = " ".join(truncate_list_word_said)
-                    break
-                for word_said in truncate_list_word_said:
-                    if word_said == stop_value:
-                        break
-                    if var_name in dict_var:
-                        dict_var[var_name] += " " + word_said
-                        truncate_list_word_said = truncate_list_word_said[1:]
-                    else:
-                        dict_var[var_name] = word_said
-            truncate_list_word_said = truncate_list_word_said[1:]
-        return dict_var
-
+                        list_match_synapse.append(synapse_order_tuple(synapse=synapse, order=signal.sentence))
+        return list_match_synapse
 
     @classmethod
     def spelt_order_match_brain_order_via_table(cls, order_to_analyse, user_said):
@@ -246,36 +64,20 @@ class OrderAnalyser:
         :param user_said: String to compare to the order
         :return: True if all string are present in the order
         """
-        logger.debug("[spelt_order_match_brain_order_via_table] before formatting, "
-                     "order to analyse: %s, "
-                     "user sentence: %s"
-                     % (order_to_analyse, user_said))
-        order_to_analyse, user_said = cls._format_sentences_to_analyse(order_to_analyse=order_to_analyse,
-                                                                       user_said=user_said)
-        list_word_user_said = user_said.split()
-        split_order_without_bracket = cls._get_split_order_without_bracket(order_to_analyse)
-
-        # if all words in the list of what the user said in in the list of word in the order
-        return cls._counter_subset(split_order_without_bracket, list_word_user_said)
-
-    @staticmethod
-    def _format_sentences_to_analyse(order_to_analyse, user_said):
-        """
-        return formatted tuple of the order_to_analyse, user_said
-        :param order_to_analyse: String order to test
-        :param user_said: String to compare to the order
-        :return: tuple of the order_to_analyse, user_said
-        """
         # Lowercase all incoming
         order_to_analyse = order_to_analyse.lower()
         user_said = user_said.lower()
 
-        logger.debug("[_format_sentences_to_analyse] formatted, "
+        logger.debug("[spelt_order_match_brain_order_via_table] "
                      "order to analyse: %s, "
                      "user sentence: %s"
                      % (order_to_analyse, user_said))
 
-        return order_to_analyse, user_said
+        list_word_user_said = user_said.split()
+        split_order_without_bracket = cls._get_split_order_without_bracket(order_to_analyse)
+
+        # if all words in the list of what the user said in in the list of word in the order
+        return cls._counter_subset(split_order_without_bracket, list_word_user_said)
 
     @staticmethod
     def _get_split_order_without_bracket(order):
@@ -306,23 +108,3 @@ class OrderAnalyser:
             if n > c2[k]:
                 return False
         return True
-
-    @staticmethod
-    def _get_default_synapse_from_sysnapses_list(all_synapses_list, default_synapse_name):
-        """
-        Static method to get the default synapse if it exists.
-
-        :param all_synapses_list: the complete list of all synapses
-        :param default_synapse_name: the synapse to find
-        :return: the Synapse
-        """
-        default_synapse = None
-        for synapse in all_synapses_list:
-            if synapse.name == default_synapse_name:
-                logger.debug("Default synapse found: %s" % synapse.name)
-                default_synapse = synapse
-                break
-        if default_synapse is None:
-            logger.debug("Default synapse not found")
-            Utils.print_warning("Default synapse not found")
-        return default_synapse

+ 7 - 12
kalliope/core/RestAPI/FlaskAPI.py

@@ -13,9 +13,8 @@ from werkzeug.utils import secure_filename
 from flask import jsonify
 from flask import request
 from flask_restful import abort
-from flask_cors import CORS, cross_origin
+from flask_cors import CORS
 
-from kalliope.core import OrderAnalyser
 from kalliope.core.RestAPI.utils import requires_auth
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from kalliope._version import version_str
@@ -169,8 +168,10 @@ class FlaskAPI(threading.Thread):
         if order is not None:
             # get the order
             order_to_run = order["order"]
-            oa = OrderAnalyser(order=order_to_run, brain=self.brain)
-            launched_synapses = oa.start()
+
+            launched_synapses = SynapseLauncher.run_matching_synapse_or_default(order_to_run,
+                                                                                self.brain,
+                                                                                self.settings)
 
             if launched_synapses:
                 # if the list is not empty, we have launched one or more synapses
@@ -255,14 +256,8 @@ class FlaskAPI(threading.Thread):
         :return:
         """
         logger.debug("order to process %s" % order)
-        if order is not None:  # maybe we have received a null audio from STT engine
-            order_analyser = OrderAnalyser(order, brain=self.brain)
-            synapses_launched = order_analyser.start()
-            self.launched_synapses = synapses_launched
-        else:
-            if self.settings.default_synapse is not None:
-                SynapseLauncher.start_synapse(name=self.settings.default_synapse, brain=self.brain)
-                self.launched_synapses = self.brain.get_synapse_by_name(synapse_name=self.settings.default_synapse)
+        list_launched_synapse = SynapseLauncher.run_matching_synapse_or_default(order, self.brain, self.settings)
+        self.launched_synapses = list_launched_synapse
 
         # this boolean will notify the main process that the order have been processed
         self.order_analyser_return = True

+ 51 - 0
kalliope/core/SynapseLauncher.py

@@ -1,4 +1,12 @@
+import logging
+
 from kalliope.core.NeuronLauncher import NeuronLauncher
+from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
+from kalliope.core.OrderAnalyser import OrderAnalyser
+
+
+logging.basicConfig()
+logger = logging.getLogger("kalliope")
 
 
 class SynapseNameNotFound(Exception):
@@ -30,6 +38,7 @@ class SynapseLauncher(object):
             raise SynapseNameNotFound("The synapse name \"%s\" does not exist in the brain file" % name)
         else:
             cls._run_synapse(synapse=synapse)
+            return synapse
 
     @classmethod
     def _run_synapse(cls, synapse):
@@ -41,3 +50,45 @@ class SynapseLauncher(object):
         for neuron in synapse.neurons:
             NeuronLauncher.start_neuron(neuron)
         return True
+
+    @classmethod
+    def run_matching_synapse_or_default(cls, order_to_process, brain, settings):
+        """
+        This method will run all synapse that match the given order "order_to_process"
+        :param order_to_process: The text order to process in the order analyser
+        :param brain: Brain instance
+        :param settings: Settings instance
+        :return: Return a list of launched synapse
+        """
+        no_synapse_match = False
+        # create a list of launched synapse to return
+        launched_synapses = list()
+        if order_to_process is not None:  # maybe we have received a null audio from STT engine
+            launched_synapses_tuple = OrderAnalyser.get_matching_synapse(order=order_to_process, brain=brain)
+
+            # oa contains the list Named tuple of synapse to run with the associated order that has matched
+            # for each synapse, get neurons, et for each neuron, get parameters
+            if not launched_synapses_tuple:
+                no_synapse_match = True
+            else:
+                # the order match one or more synapses
+                for tuple_el in launched_synapses_tuple:
+                    launched_synapses.append(tuple_el.synapse)
+                    logger.debug("Get parameter for %s " % tuple_el.synapse.name)
+                    parameters = NeuronParameterLoader.get_parameters(synapse_order=tuple_el.order,
+                                                                      user_order=order_to_process)
+                    # start the neuron list
+                    NeuronLauncher.start_neuron_list(neuron_list=tuple_el.synapse.neurons,
+                                                     parameters_dict=parameters)
+        else:
+            no_synapse_match = True
+
+        if no_synapse_match:  # then run the default synapse
+            if settings.default_synapse is not None:
+                logger.debug("No matching Synapse-> running default synapse ")
+                synapses = SynapseLauncher.start_synapse(name=settings.default_synapse,
+                                                         brain=brain)
+                launched_synapses.append(synapses)
+
+        # return the launched synapse list
+        return launched_synapses

+ 3 - 0
kalliope/core/__init__.py

@@ -4,5 +4,8 @@ from kalliope.core.ShellGui import ShellGui
 from kalliope.core.Utils.Utils import Utils
 from kalliope.core.Utils import FileManager
 from kalliope.core.ResourcesManager import ResourcesManager
+from kalliope.core.NeuronLauncher import NeuronLauncher
+from kalliope.core.SynapseLauncher import SynapseLauncher
+
 
 

+ 3 - 1
kalliope/neurons/neurotransmitter/neurotransmitter.py

@@ -40,10 +40,12 @@ class Neurotransmitter(NeuronModule):
             for el in self.from_answer_link:
                 for answer in el["answers"]:
                     if self.is_order_matching(audio, answer):
+                        logger.debug("Neurotransmitter: match answer: %s" % answer)
                         found = self.run_synapse_by_name_with_order(order=audio,
                                                                     synapse_name=el["synapse"],
                                                                     order_template=answer)
-            if not found: # the answer do not correspond to any answer. We run the default synapse
+                        break
+            if not found:  # the answer do not correspond to any answer. We run the default synapse
                 self.run_synapse_by_name(self.default)
 
     def _is_parameters_ok(self):