test_models.py 6.49 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1 2 3 4 5
import logging

import jsonschema

import json
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
6
import rdflib
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
7
from unittest import TestCase
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
8 9 10 11 12 13
from senpy.models import (Emotion,
                          EmotionAnalysis,
                          EmotionSet,
                          Entry,
                          Error,
                          Results,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
14 15
                          Sentiment,
                          Plugins,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
16 17 18
                          Plugin,
                          from_string,
                          from_dict)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
19
from senpy import plugins
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
20 21 22 23 24
from pprint import pprint


class ModelsTest(TestCase):
    def test_jsonld(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
25
        prueba = {"id": "test", "analysis": [], "entries": []}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
26 27
        r = Results(**prueba)
        print("Response's context: ")
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
28
        pprint(r._context)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
29

30 31
        assert r.id == "test"

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
32 33 34
        j = r.jsonld(with_context=True)
        print("As JSON:")
        pprint(j)
J. Fernando Sánchez's avatar
YAPFed  
J. Fernando Sánchez committed
35 36 37 38
        assert ("@context" in j)
        assert ("marl" in j["@context"])
        assert ("entries" in j["@context"])
        assert (j["@id"] == "test")
39
        assert "id" not in j
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
40 41

        r6 = Results(**prueba)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
42
        e = Entry({"@id": "ohno", "nif:isString": "Just testing"})
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
43
        r6.entries.append(e)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
44
        logging.debug("Reponse 6: %s", r6)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
45 46
        assert ("marl" in r6._context)
        assert ("entries" in r6._context)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
47 48
        j6 = r6.jsonld(with_context=True)
        logging.debug("jsonld: %s", j6)
J. Fernando Sánchez's avatar
YAPFed  
J. Fernando Sánchez committed
49 50 51
        assert ("@context" in j6)
        assert ("entries" in j6)
        assert ("analysis" in j6)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
52 53 54
        resp = r6.flask()
        received = json.loads(resp.data.decode())
        logging.debug("Response: %s", j6)
J. Fernando Sánchez's avatar
YAPFed  
J. Fernando Sánchez committed
55 56 57
        assert (received["entries"])
        assert (received["entries"][0]["nif:isString"] == "Just testing")
        assert (received["entries"][0]["nif:isString"] != "Not testing")
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
58

59
    def test_id(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
60 61
        """ Adding the id after creation should overwrite the automatic ID
        """
62 63 64 65 66 67 68 69
        r = Entry()
        j = r.jsonld()
        assert '@id' in j
        r.id = "test"
        j2 = r.jsonld()
        assert j2['@id'] == 'test'
        assert 'id' not in j2

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    def test_entries(self):
        e = Entry()
        self.assertRaises(jsonschema.ValidationError, e.validate)
        e.nif__isString = "this is a test"
        e.nif__beginIndex = 0
        e.nif__endIndex = 10
        e.validate()

    def test_sentiment(self):
        s = Sentiment()
        self.assertRaises(jsonschema.ValidationError, s.validate)
        s.nif__anchorOf = "so much testing"
        s.prov__wasGeneratedBy = ""
        s.validate()

    def test_emotion_set(self):
        e = EmotionSet()
        self.assertRaises(jsonschema.ValidationError, e.validate)
        e.nif__anchorOf = "so much testing"
        e.prov__wasGeneratedBy = ""
        e.validate()

    def test_results(self):
        r = Results()
        e = Entry()
        e.nif__isString = "Results test"
        r.entries.append(e)
        r.id = ":test_results"
        r.validate()

    def test_plugins(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
101
        self.assertRaises(Error, plugins.Plugin)
102
        p = plugins.Plugin({"name": "dummy",
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
103
                            "description": "I do nothing",
104 105 106 107 108 109 110 111
                            "version": 0,
                            "extra_params": {
                                "none": {
                                    "options": ["es", ],
                                    "required": False,
                                    "default": "0"
                                }
                            }})
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
112
        c = p.jsonld()
113 114 115 116 117 118
        assert '@type' in c
        assert c['@type'] == 'plugin'
        assert 'info' not in c
        assert 'repo' not in c
        assert 'extra_params' in c
        logging.debug('Framed:')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
119 120
        logging.debug(c)
        p.validate()
121
        assert 'es' in c['extra_params']['none']['options']
122
        assert isinstance(c['extra_params']['none']['options'], list)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
123

124 125 126
    def test_str(self):
        """The string representation shouldn't include private variables"""
        r = Results()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
127 128 129
        p = plugins.Plugin({"name": "STR test",
                            "description": "Test of private variables.",
                            "version": 0})
130 131 132 133 134 135 136
        p._testing = 0
        s = str(p)
        assert "_testing" not in s
        r.analysis.append(p)
        s = str(r)
        assert "_testing" not in s

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    def test_turtle(self):
        """Any model should be serializable as a turtle file"""
        ana = EmotionAnalysis()
        res = Results()
        res.analysis.append(ana)
        entry = Entry(text='Just testing')
        eSet = EmotionSet()
        emotion = Emotion()
        entry.emotions.append(eSet)
        res.entries.append(entry)
        eSet.onyx__hasEmotion.append(emotion)
        eSet.prov__wasGeneratedBy = ana.id
        triples = ('ana a :Analysis',
                   'entry a :entry',
                   '      nif:isString "Just testing"',
                   '      onyx:hasEmotionSet eSet',
                   'eSet a onyx:EmotionSet',
                   '     prov:wasGeneratedBy ana',
                   '     onyx:hasEmotion emotion',
                   'emotion a onyx:Emotion',
                   'res a :results',
                   '    me:AnalysisInvoloved ana',
                   '    prov:used entry')

        t = res.serialize(format='turtle')
        print(t)
        g = rdflib.Graph().parse(data=t, format='turtle')
        assert len(g) == len(triples)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
165

166 167 168 169 170 171 172
    def test_plugin_list(self):
        """The plugin list should be of type \"plugins\""""
        plugs = Plugins()
        c = plugs.jsonld()
        assert '@type' in c
        assert c['@type'] == 'plugins'

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
173 174 175
    def test_single_plugin(self):
        """A response with a single plugin should still return a list"""
        plugs = Plugins()
176
        p = Plugin({'id': str(1),
177 178 179
                    'version': 0,
                    'description': 'dummy'})
        plugs.plugins.append(p)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
180 181 182
        assert isinstance(plugs.plugins, list)
        js = plugs.jsonld()
        assert isinstance(js['plugins'], list)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
183 184 185 186 187 188 189 190

    def test_from_string(self):
        results = {
            '@type': 'results',
            '@id': 'prueba',
            'entries': [{
                '@id': 'entry1',
                '@type': 'entry',
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
191
                'nif:isString': 'TEST'
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
192 193 194 195 196 197 198 199 200 201
            }]
        }
        recovered = from_dict(results)
        assert isinstance(recovered, Results)
        assert isinstance(recovered.entries[0], Entry)

        string = json.dumps(results)
        recovered = from_string(string)
        assert isinstance(recovered, Results)
        assert isinstance(recovered.entries[0], Entry)