test_extensions.py 6.19 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1
from __future__ import print_function
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
2
import os
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
3
from copy import deepcopy
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
4
import logging
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5

6
7
8
9
10
try:
    from unittest import mock
except ImportError:
    import mock

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
11
from functools import partial
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
12
from senpy.extensions import Senpy
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
13
from senpy.models import Error, Results, Entry, EmotionSet, Emotion, Plugin
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
14
from flask import Flask
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
15
from unittest import TestCase
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
16
17


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
18
class ExtensionsTest(TestCase):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
19
    def setUp(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
20
        self.app = Flask('test_extensions')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
21
        self.dir = os.path.join(os.path.dirname(__file__))
22
23
24
        self.senpy = Senpy(plugin_folder=self.dir,
                           app=self.app,
                           default_plugins=False)
25
        self.senpy.activate_plugin("Dummy", sync=True)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
26
27
28
29
30

    def test_init(self):
        """ Initialising the app with the extension.  """
        assert hasattr(self.app, "senpy")
        tapp = Flask("temp app")
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
31
        self.senpy.init_app(tapp)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
32
33
34
35
        assert hasattr(tapp, "senpy")

    def test_discovery(self):
        """ Discovery of plugins in given folders.  """
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
36
        # noinspection PyProtectedMember
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
37
        assert self.dir in self.senpy._search_folders
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
38
        print(self.senpy.plugins)
39
        assert "Dummy" in self.senpy.plugins
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
40
41

    def test_enabling(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
42
43
44
45
        """ Enabling a plugin """
        info = {
            'name': 'TestPip',
            'module': 'dummy',
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
46
            'description': None,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
47
48
            'requirements': ['noop'],
            'version': 0
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
49
        }
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
50
        root = os.path.join(self.dir, 'plugins', 'dummy_plugin')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
51
52
53
54
        name, module = self.senpy._load_plugin_from_info(info, root=root)
        assert name == 'TestPip'
        assert module
        import noop
55
        dir(noop)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
56
        self.senpy.install_deps()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
57
58

    def test_installing(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
59
        """ Enabling a plugin """
60
        self.senpy.activate_all(sync=True)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
61
        assert len(self.senpy.plugins) >= 3
62
        assert self.senpy.plugins["Sleep"].is_activated
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
63
64
65

    def test_disabling(self):
        """ Disabling a plugin """
66
        self.senpy.deactivate_all(sync=True)
67
68
        assert not self.senpy.plugins["Dummy"].is_activated
        assert not self.senpy.plugins["Sleep"].is_activated
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
69
70
71
72

    def test_default(self):
        """ Default plugin should be set """
        assert self.senpy.default_plugin
73
74
75
76
77
78
79
80
        assert self.senpy.default_plugin.name == "Dummy"
        self.senpy.deactivate_all(sync=True)
        logging.debug("Default: {}".format(self.senpy.default_plugin))
        assert self.senpy.default_plugin is None

    def test_noplugin(self):
        """ Don't analyse if there isn't any plugin installed """
        self.senpy.deactivate_all(sync=True)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
81
82
83
84
85
86
        self.assertRaises(Error, partial(self.senpy.analyse, input="tupni"))
        self.assertRaises(Error,
                          partial(
                              self.senpy.analyse,
                              input="tupni",
                              algorithm='Dummy'))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
87
88
89

    def test_analyse(self):
        """ Using a plugin """
90
91
92
93
        # I was using mock until plugin started inheriting
        # Leaf (defaultdict with  __setattr__ and __getattr__.
        r1 = self.senpy.analyse(
            algorithm="Dummy", input="tupni", output="tuptuo")
94
        r2 = self.senpy.analyse(input="tupni", output="tuptuo")
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
95
96
97
        assert r1.analysis[0] == "plugins/Dummy_0.1"
        assert r2.analysis[0] == "plugins/Dummy_0.1"
        assert r1.entries[0].text == 'input'
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
98

99
100
    def test_analyse_error(self):
        mm = mock.MagicMock()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
101
102
        mm.id = 'magic_mock'
        mm.analyse_entries.side_effect = Error('error on analysis', status=500)
103
        self.senpy.plugins['MOCK'] = mm
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
104
105
106
107
108
109
110
        try:
            self.senpy.analyse(input='nothing', algorithm='MOCK')
            assert False
        except Error as ex:
            assert ex['message'] == 'error on analysis'
            assert ex['status'] == 500

111
        mm.analyse.side_effect = Exception('generic exception on analysis')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
112
        mm.analyse_entries.side_effect = Exception(
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
113
            'generic exception on analysis')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
114
115
116
117
118
119
120

        try:
            self.senpy.analyse(input='nothing', algorithm='MOCK')
            assert False
        except Error as ex:
            assert ex['message'] == 'generic exception on analysis'
            assert ex['status'] == 500
121

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
122
123
    def test_filtering(self):
        """ Filtering plugins """
124
        assert len(self.senpy.filter_plugins(name="Dummy")) > 0
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
125
        assert not len(self.senpy.filter_plugins(name="notdummy"))
126
127
        assert self.senpy.filter_plugins(name="Dummy", is_activated=True)
        self.senpy.deactivate_plugin("Dummy", sync=True)
128
        assert not len(
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
129
            self.senpy.filter_plugins(name="Dummy", is_activated=True))
130
131
132
133

    def test_load_default_plugins(self):
        senpy = Senpy(plugin_folder=self.dir, default_plugins=True)
        assert len(senpy.plugins) > 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
134
135
136

    def test_convert_emotions(self):
        self.senpy.activate_all()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
137
        plugin = Plugin({
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
138
139
            'id': 'imaginary',
            'onyx:usesEmotionModel': 'emoml:fsre-dimensions'
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
140
        })
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
141
        eSet1 = EmotionSet()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
142
        eSet1.prov__wasGeneratedBy = plugin['id']
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        eSet1['onyx:hasEmotion'].append(Emotion({
            'emoml:arousal': 1,
            'emoml:potency': 0,
            'emoml:valence': 0
        }))
        response = Results({
            'entries': [Entry({
                'text': 'much ado about nothing',
                'emotions': [eSet1]
            })]
        })
        params = {'emotionModel': 'emoml:big6',
                  'conversion': 'full'}
        r1 = deepcopy(response)
        self.senpy.convert_emotions(r1,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
158
                                    [plugin, ],
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
159
160
161
162
163
                                    params)
        assert len(r1.entries[0].emotions) == 2
        params['conversion'] = 'nested'
        r2 = deepcopy(response)
        self.senpy.convert_emotions(r2,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
164
                                    [plugin, ],
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
165
166
167
168
169
170
                                    params)
        assert len(r2.entries[0].emotions) == 1
        assert r2.entries[0].emotions[0]['prov:wasDerivedFrom'] == eSet1
        params['conversion'] = 'filtered'
        r3 = deepcopy(response)
        self.senpy.convert_emotions(r3,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
171
                                    [plugin, ],
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
172
173
                                    params)
        assert len(r3.entries[0].emotions) == 1