-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_vehicle_state_log.py
104 lines (80 loc) · 2.82 KB
/
test_vehicle_state_log.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
import json
import os
import time
import unittest
from unittest.mock import MagicMock, patch
import paho.mqtt.client as mqtt
from vehicle_state_log import callback, logger
# Mock the Ankaios class
# Mock the Ankaios class
class MockAnkaios:
def __init__(self):
self.state = {
"workload_states": [
{"workload_id": "1", "state": "RUNNING"},
{"workload_id": "2", "state": "STOPPED"},
]
}
def get_state(self, field_masks=None):
return MagicMock(to_dict=lambda: self.state)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
# Mock the MQTT client
class MockMQTTClient:
def __init__(self):
self.published_messages = []
def publish(self, topic, payload):
self.published_messages.append((topic, payload))
def connect(self, broker, port, keepalive):
pass # No real connection is made
def loop_forever(self):
pass
class TestVehicleStateLog(unittest.TestCase):
def setUp(self):
# Set environment variables
os.environ["MQTT_BROKER_ADDR"] = "localhost"
os.environ["MQTT_BROKER_PORT"] = "1883"
os.environ["VIN"] = "test_vin"
os.environ["INTERVAL"] = "1"
# Mock the Ankaios class
self.ankaios_mock = MockAnkaios()
# Mock the MQTT client
self.mqtt_client_mock = MockMQTTClient()
# Patch the Ankaios and MQTT client
self.ankaios_patch = patch(
"vehicle_state_log.Ankaios", return_value=self.ankaios_mock
)
self.mqtt_client_patch = patch(
"vehicle_state_log.mqtt.Client", return_value=self.mqtt_client_mock
)
self.ankaios_patch.start()
self.mqtt_client_patch.start()
def tearDown(self):
self.ankaios_patch.stop()
self.mqtt_client_patch.stop()
def test_callback(self):
# Test data
topic_name = "vehicle_dynamics"
msg = '{"speed": 60, "direction": "north"}'
timestamp = time.time()
# Call the callback function
callback(topic_name, msg, timestamp)
# Check if the message was published correctly
expected_payload = {
"speed": 60,
"direction": "north",
"workload_states": [
{"workload_id": "1", "state": "RUNNING"},
{"workload_id": "2", "state": "STOPPED"},
],
"vehicle_id": "test_vin",
}
# Verify the published message
self.assertEqual(len(self.mqtt_client_mock.published_messages), 1)
topic, payload = self.mqtt_client_mock.published_messages[0]
self.assertEqual(topic, "vehicle/vehicle_dynamics")
self.assertEqual(json.loads(payload), expected_payload)
if __name__ == "__main__":
unittest.main()