1
|
|
|
import logging |
2
|
|
|
import time |
3
|
|
|
|
4
|
|
|
from unittest.case import TestCase |
5
|
|
|
from unittest.mock import MagicMock, patch |
6
|
|
|
|
7
|
|
|
from paho.mqtt.client import MQTTMessage |
8
|
|
|
|
9
|
|
|
from ospd_openvas.mqtt import MQTTHandler, OpenvasMQTTHandler |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
@patch('paho.mqtt.client.Client', autospec=True) |
13
|
|
|
class TestMQTT(TestCase): |
14
|
|
|
def test_on_message_not_implemented(self, mock_client: MagicMock): |
15
|
|
|
mqtt = MQTTHandler("foo", "bar") |
16
|
|
|
|
17
|
|
|
with self.assertRaises(NotImplementedError): |
18
|
|
|
mqtt.on_message(None, None, None) |
19
|
|
|
|
20
|
|
|
def test_publish_message(self, mock_client: MagicMock): |
21
|
|
|
mqtt = MQTTHandler("foo", "bar") |
22
|
|
|
|
23
|
|
|
logging.Logger.debug = MagicMock() |
24
|
|
|
|
25
|
|
|
mqtt.publish("foo/bar", "test123") |
26
|
|
|
|
27
|
|
|
logging.Logger.debug.assert_called_with( # pylint: disable=no-member |
28
|
|
|
'Published message on topic %s.', "foo/bar" |
29
|
|
|
) |
30
|
|
|
|
31
|
|
|
def test_insert_results(self, mock_client: MagicMock): |
32
|
|
|
|
33
|
|
|
results_dict = {} |
34
|
|
|
expct_dict = { |
35
|
|
|
"1": [ |
36
|
|
|
{ |
37
|
|
|
"type": "foo", |
38
|
|
|
"host_ip": "127.0.0.1", |
39
|
|
|
"hostname": "", |
40
|
|
|
"port": "80", |
41
|
|
|
"OID": "", |
42
|
|
|
"value": "bar", |
43
|
|
|
} |
44
|
|
|
] |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
msg = MQTTMessage() |
48
|
|
|
msg.topic = b"scanner/results" |
49
|
|
|
msg.payload = b'{"scan_id":"1","type":"foo","host_ip":"127.0.0.1","hostname":"","port":"80","OID":"","value":"bar"}' |
50
|
|
|
|
51
|
|
|
def add_results(results, scan_id): |
52
|
|
|
if not scan_id in results_dict: |
|
|
|
|
53
|
|
|
results_dict[scan_id] = [] |
54
|
|
|
results_dict[scan_id] += results |
55
|
|
|
|
56
|
|
|
mqtt = OpenvasMQTTHandler("foo", add_results) |
57
|
|
|
mqtt.on_message( |
58
|
|
|
None, |
59
|
|
|
mqtt, |
60
|
|
|
msg, |
61
|
|
|
) |
62
|
|
|
|
63
|
|
|
self.assertDictEqual(results_dict, {}) |
64
|
|
|
time.sleep(0.3) |
65
|
|
|
self.assertDictEqual(results_dict, expct_dict) |
66
|
|
|
|
67
|
|
|
def test_json_format(self, mock_client: MagicMock): |
68
|
|
|
|
69
|
|
|
msg = MQTTMessage() |
70
|
|
|
msg.topic = b"scanner/results" |
71
|
|
|
msg.payload = b'{"scan_id":"1","type":"foo","host_ip":"127.0.0.1","hostname":"","port":"80","OID":"","value""bar"}' |
72
|
|
|
|
73
|
|
|
def do_nothing(results, scan_id): |
74
|
|
|
return |
75
|
|
|
|
76
|
|
|
logging.Logger.error = MagicMock() |
77
|
|
|
|
78
|
|
|
mqtt = OpenvasMQTTHandler("foo", do_nothing) |
79
|
|
|
mqtt.on_message( |
80
|
|
|
None, |
81
|
|
|
mqtt, |
82
|
|
|
msg, |
83
|
|
|
) |
84
|
|
|
|
85
|
|
|
logging.Logger.error.assert_called_with( # pylint: disable=no-member |
86
|
|
|
"Got MQTT message in non-json format." |
87
|
|
|
) |
88
|
|
|
|