-
-
Notifications
You must be signed in to change notification settings - Fork 407
/
test_parser_rasanlu.py
559 lines (487 loc) · 22.5 KB
/
test_parser_rasanlu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import asyncio
import asynctest
import asynctest.mock as amock
import aiohttp
from aiohttp import ClientOSError
from opsdroid.cli.start import configure_lang
from opsdroid.core import OpsDroid
from opsdroid.matchers import match_rasanlu
from opsdroid.events import Message
from opsdroid.parsers import rasanlu
from opsdroid.connector import Connector
class TestParserRasaNLU(asynctest.TestCase):
"""Test the opsdroid Rasa NLU parser."""
async def setup(self):
configure_lang({})
async def getMockSkill(self):
async def mockedskill(opsdroid, config, message):
pass
mockedskill.config = {}
return mockedskill
async def getRaisingMockSkill(self):
async def mockedskill(opsdroid, config, message):
raise Exception()
mockedskill.config = {}
return mockedskill
async def test_call_rasanlu(self):
opsdroid = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
config = {
"name": "rasanlu",
"access-token": "test",
"min-score": 0.3,
"token": "12345",
}
result = amock.Mock()
result.status = 200
result.json = amock.CoroutineMock()
result.json.return_value = {
"entities": [
{
"end": 32,
"entity": "state",
"extractor": "ner_crf",
"confidence": 0.854,
"start": 25,
"value": "running",
}
],
"intent": {"confidence": 0.5745766766665303, "name": "get_weather"},
"intent_ranking": [
{"confidence": 0.5745766766665303, "name": "get_weather"},
{"confidence": 0.42542332333346977, "name": "other_weather"},
],
"text": "how's the weather outside",
}
with amock.patch("aiohttp.ClientSession.post") as patched_request:
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
await rasanlu.call_rasanlu(message.text, config)
self.assertTrue(patched_request.called)
async def test_call_rasanlu_bad_response(self):
opsdroid = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
config = {"name": "rasanlu", "access-token": "test", "min-score": 0.3}
result = amock.Mock()
result.status = 403
result.text = amock.CoroutineMock()
result.text.return_value = "unauthorized"
with amock.patch("aiohttp.ClientSession.post") as patched_request:
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
response = await rasanlu.call_rasanlu(message.text, config)
self.assertTrue(patched_request.called)
self.assertEqual(response, result.text.return_value)
async def test_call_rasanlu_raises(self):
opsdroid = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
config = {"name": "rasanlu", "access-token": "test", "min-score": 0.3}
result = amock.Mock()
result.status = 403
result.text = amock.CoroutineMock()
result.text.return_value = "unauthorized"
with amock.patch("aiohttp.ClientSession.post") as patched_request:
patched_request.side_effect = aiohttp.client_exceptions.ClientConnectorError(
"key", amock.Mock()
)
self.assertEqual(None, await rasanlu.call_rasanlu(message.text, config))
async def test_parse_rasanlu(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "rasanlu", "access-token": "test", "min-score": 0.3}
]
mock_skill = await self.getMockSkill()
opsdroid.skills.append(match_rasanlu("get_weather")(mock_skill))
mock_connector = amock.CoroutineMock()
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
mocked_call_rasanlu.return_value = {
"entities": [
{
"end": 32,
"entity": "state",
"extractor": "ner_crf",
"confidence": 0.854,
"start": 25,
"value": "running",
}
],
"intent": {"confidence": 0.9745766766665303, "name": "get_weather"},
"intent_ranking": [
{"confidence": 0.9745766766665303, "name": "get_weather"},
{"confidence": 0.42542332333346977, "name": "other_weather"},
],
"text": "how's the weather outside",
}
skills = await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertEqual(mock_skill, skills[0]["skill"])
async def test_parse_rasanlu_entities(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "rasanlu", "access-token": "test", "min-score": 0.3}
]
mock_skill = await self.getMockSkill()
opsdroid.skills.append(match_rasanlu("restaurant_search")(mock_skill))
mock_connector = amock.CoroutineMock()
message = Message(
"show me chinese restaurants", "user", "default", mock_connector
)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
mocked_call_rasanlu.return_value = {
"text": "show me chinese restaurants",
"intent": {"name": "restaurant_search", "confidence": 0.98343},
"entities": [
{
"start": 8,
"end": 15,
"value": "chinese",
"entity": "cuisine",
"extractor": "CRFEntityExtractor",
"confidence": 0.854,
"processors": [],
}
],
}
[skill] = await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertEqual(len(skill["message"].entities.keys()), 1)
self.assertTrue("cuisine" in skill["message"].entities.keys())
self.assertEqual(
skill["message"].entities["cuisine"]["value"], "chinese"
)
async def test_parse_rasanlu_raises(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "rasanlu", "access-token": "test", "min-score": 0.3}
]
mock_skill = await self.getRaisingMockSkill()
mock_skill.config = {"name": "mocked-skill"}
opsdroid.skills.append(match_rasanlu("get_weather")(mock_skill))
mock_connector = amock.MagicMock()
mock_connector.send = amock.CoroutineMock()
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
mocked_call_rasanlu.return_value = {
"entities": [
{
"end": 32,
"entity": "state",
"extractor": "ner_crf",
"confidence": 0.854,
"start": 25,
"value": "running",
}
],
"intent": {"confidence": 0.9745766766665303, "name": "get_weather"},
"intent_ranking": [
{"confidence": 0.9745766766665303, "name": "get_weather"},
{"confidence": 0.42542332333346977, "name": "other_weather"},
],
"text": "how's the weather outside",
}
skills = await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertEqual(mock_skill, skills[0]["skill"])
await opsdroid.run_skill(skills[0]["skill"], skills[0]["config"], message)
self.assertLogs("_LOGGER", "exception")
async def test_parse_rasanlu_failure(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "rasanlu", "access-token": "test", "min-score": 0.3}
]
mock_skill = amock.CoroutineMock()
match_rasanlu("get_weather")(mock_skill)
mock_connector = amock.CoroutineMock()
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
mocked_call_rasanlu.return_value = "unauthorized"
skills = await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertFalse(skills)
async def test_parse_rasanlu_low_score(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "rasanlu", "access-token": "test", "min-score": 0.3}
]
mock_skill = amock.CoroutineMock()
match_rasanlu("get_weather")(mock_skill)
mock_connector = amock.CoroutineMock()
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
mocked_call_rasanlu.return_value = {
"entities": [
{
"end": 32,
"entity": "state",
"extractor": "ner_crf",
"confidence": 0.854,
"start": 25,
"value": "running",
}
],
"intent": {"confidence": 0.1745766766665303, "name": "get_weather"},
"intent_ranking": [
{"confidence": 0.1745766766665303, "name": "get_weather"},
{"confidence": 0.42542332333346977, "name": "other_weather"},
],
"text": "how's the weather outside",
}
await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertFalse(mock_skill.called)
async def test_parse_rasanlu_no_entity(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [{"name": "rasanlu", "access-token": "test"}]
mock_skill = amock.CoroutineMock()
match_rasanlu("get_weather")(mock_skill)
mock_connector = amock.CoroutineMock()
message = Message("hi", "user", "default", mock_connector)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
mocked_call_rasanlu.return_value = {
"entities": [],
"intent": None,
"intent_ranking": [],
"text": "hi",
}
await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertFalse(mock_skill.called)
async def test_parse_rasanlu_no_intent(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "rasanlu", "access-token": "test", "min-score": 0.3}
]
mock_skill = amock.CoroutineMock()
match_rasanlu("get_weather")(mock_skill)
mock_connector = amock.CoroutineMock()
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
mocked_call_rasanlu.return_value = {
"entities": [],
"intent": None,
"intent_ranking": [],
"text": "hi",
}
await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertFalse(mock_skill.called)
async def test_parse_rasanlu_raise_ClientOSError(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "rasanlu", "access-token": "test", "min-score": 0.3}
]
mock_skill = amock.CoroutineMock()
match_rasanlu("get_weather")(mock_skill)
mock_connector = amock.CoroutineMock()
message = Message(
"how's the weather outside", "user", "default", mock_connector
)
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call:
mocked_call.side_effect = ClientOSError()
await rasanlu.parse_rasanlu(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertFalse(mock_skill.called)
self.assertTrue(mocked_call.called)
async def test__get_all_intents(self):
skills = [
await self.getMockSkill(),
await self.getMockSkill(),
await self.getMockSkill(),
]
skills[0] = {"intents": "Hello"}
skills[1] = {"intents": None}
skills[2] = {"intents": "World"}
intents = await rasanlu._get_all_intents(skills)
self.assertEqual(type(intents), type(b""))
self.assertEqual(intents, b"Hello\n\nWorld")
async def test__get_all_intents_fails(self):
skills = []
intents = await rasanlu._get_all_intents(skills)
self.assertEqual(intents, None)
async def test__get_intents_fingerprint(self):
fingerprint = await rasanlu._get_intents_fingerprint(b"")
self.assertEqual(
fingerprint,
"e3b0c44298fc1c149afbf4c8996fb924" + "27ae41e4649b934ca495991b7852b855",
)
fingerprint = await rasanlu._get_intents_fingerprint(b"Hello World")
self.assertEqual(
fingerprint,
"a591a6d40bf420404a011733cfb7b190" + "d62c65bf0bcda32b57b277d9ad9f146e",
)
fingerprint = await rasanlu._get_intents_fingerprint(b"Hello\n\nWorld")
self.assertEqual(
fingerprint,
"286346b7b2f097fc1c8d8c0436c5e3b1" + "b661768a549f7585a3bda9cc7af2b079",
)
async def test__build_training_url(self):
config = {}
with self.assertRaises(KeyError):
await rasanlu._build_training_url(config)
config = {"model": "helloworld"}
url = await rasanlu._build_training_url(config)
self.assertTrue("helloworld" in url)
config = {"model": "helloworld", "token": "abc123"}
url = await rasanlu._build_training_url(config)
self.assertTrue("&token=abc123" in url)
config = {
"url": "http://example.com",
"project": "myproject",
"model": "helloworld",
}
url = await rasanlu._build_training_url(config)
self.assertTrue("http://example.com" in url)
self.assertTrue("myproject" in url)
self.assertTrue("helloworld" in url)
async def test__build_status_url(self):
config = {"url": "http://example.com"}
url = await rasanlu._build_status_url(config)
self.assertTrue("http://example.com" in url)
async def test__init_model(self):
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call:
mocked_call.return_value = {"data": "Some data"}
self.assertEqual(await rasanlu._init_model({}), True)
mocked_call.return_value = None
self.assertEqual(await rasanlu._init_model({}), False)
async def test__get_existing_models(self):
result = amock.Mock()
result.status = 200
result.json = amock.CoroutineMock()
result.json.return_value = {
"available_projects": {
"default": {"available_models": ["fallback"], "status": "ready"},
"opsdroid": {"available_models": ["hello", "world"], "status": "ready"},
}
}
with amock.patch("aiohttp.ClientSession.get") as patched_request:
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
models = await rasanlu._get_existing_models({"project": "opsdroid"})
self.assertEqual(models, ["hello", "world"])
async def test__get_existing_models_exception(self):
with amock.patch("aiohttp.ClientSession.get") as patched_request:
patched_request.return_value = asyncio.Future()
patched_request.side_effect = ClientOSError()
models = await rasanlu._get_existing_models({"project": "opsdroid"})
self.assertRaises(ClientOSError)
self.assertEqual(models, [])
async def test__get_existing_models_fails(self):
result = amock.Mock()
result.status = 404
result.json = amock.CoroutineMock()
result.json.return_value = {}
with amock.patch("aiohttp.ClientSession.get") as patched_request:
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
models = await rasanlu._get_existing_models({})
self.assertEqual(models, [])
async def test_train_rasanlu_fails(self):
result = amock.Mock()
result.status = 404
result.text = amock.CoroutineMock()
result.json = amock.CoroutineMock()
result.json.return_value = {"info": "new model trained: abc123"}
with amock.patch(
"aiohttp.ClientSession.post"
) as patched_request, amock.patch.object(
rasanlu, "_get_all_intents"
) as mock_gai, amock.patch.object(
rasanlu, "_init_model"
) as mock_im, amock.patch.object(
rasanlu, "_build_training_url"
) as mock_btu, amock.patch.object(
rasanlu, "_get_existing_models"
) as mock_gem, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
) as mock_gif:
mock_gai.return_value = None
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
mock_gai.return_value = "Hello World"
mock_gem.return_value = ["abc123"]
mock_gif.return_value = "abc123"
self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
self.assertTrue(mock_im.called)
self.assertFalse(mock_btu.called)
mock_gem.return_value = []
mock_btu.return_value = "http://example.com"
patched_request.side_effect = aiohttp.client_exceptions.ClientConnectorError(
"key", amock.Mock()
)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
result.json.return_value = {"info": "error"}
patched_request.return_value = asyncio.Future()
patched_request.side_effect = None
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
async def test_train_rasanlu_succeeded(self):
result = amock.Mock()
result.text = amock.CoroutineMock()
result.json = amock.CoroutineMock()
result.status = 200
result.json.return_value = {"info": "new model trained: abc1234"}
with amock.patch(
"aiohttp.ClientSession.post"
) as patched_request, amock.patch.object(
rasanlu, "_get_all_intents"
) as mock_gai, amock.patch.object(
rasanlu, "_init_model"
) as mock_im, amock.patch.object(
rasanlu, "_build_training_url"
) as mock_btu, amock.patch.object(
rasanlu, "_get_existing_models"
) as mock_gem, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
) as mock_gif:
mock_gem.return_value = ["abc123"]
mock_btu.return_value = "http://example.com"
mock_gai.return_value = "Hello World"
mock_gif.return_value = "abc1234"
result.content_type = "application/json"
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
result.json.return_value = {}
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
result.content_type = "application/zip"
result.content_disposition.type = "attachment"
result.json.return_value = {"info": "new model trained: abc1234"}
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)