-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_refactoring.py
More file actions
executable file
·266 lines (211 loc) · 7.81 KB
/
test_refactoring.py
File metadata and controls
executable file
·266 lines (211 loc) · 7.81 KB
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
#!/usr/bin/env python3
"""
Test script for APS2MQTT refactored modules
This script tests the main components without requiring actual ECU connection
"""
import sys
import logging
from pathlib import Path
# Setup logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def test_imports():
"""Test that all modules can be imported"""
logger.info("Testing imports...")
try:
from aps2mqtt import models
logger.info("✓ models imported")
from aps2mqtt import constants
logger.info("✓ constants imported")
from aps2mqtt import parser
logger.info("✓ parser imported")
from aps2mqtt import ha_discovery
logger.info("✓ ha_discovery imported")
from aps2mqtt import mqtt_handler
logger.info("✓ mqtt_handler imported")
from aps2mqtt import config
logger.info("✓ config imported")
from aps2mqtt.apsystems import ECU
logger.info("✓ ECU imported")
from aps2mqtt.apsystems import APSystemsSocket
logger.info("✓ APSystemsSocket imported")
return True
except ImportError as err:
logger.error(f"✗ Import failed: {err}")
return False
def test_models():
"""Test data models"""
logger.info("\nTesting models...")
try:
from aps2mqtt.models import InverterData, ECUData
# Create test inverter
inverter = InverterData(
uid="123456789ABC",
online=True,
current_software_version="1.2.3",
signal=85,
frequency=50.0,
temperature=35,
model="YC600",
channel_qty=2,
power=[150, 160],
voltage=[230, 235]
)
logger.info(f"✓ InverterData created: {inverter.uid}")
# Create test ECU data
ecu_data = ECUData(
ecu_id="216200063835",
timestamp="2026-01-11 15:30:00",
today_energy=5.5,
lifetime_energy=1234.5,
current_power=310,
qty_of_inverters=1,
qty_of_online_inverters=1,
firmware="ECU_R_1.2.3",
inverters=[inverter]
)
logger.info(f"✓ ECUData created: {ecu_data.ecu_id}")
# Test conversion to dict
data_dict = ecu_data.to_dict()
logger.info(f"✓ ECUData.to_dict() worked, got {len(data_dict)} keys")
return True
except Exception as err:
logger.error(f"✗ Models test failed: {err}", exc_info=True)
return False
def test_parser():
"""Test data parser"""
logger.info("\nTesting parser...")
try:
from aps2mqtt.parser import DataParser
from aps2mqtt.models import InverterData, ECUData
parser = DataParser("test")
logger.info("✓ DataParser created")
# Create test data
inverter = InverterData(
uid="123456789ABC",
online=True,
current_software_version="1.2.3",
signal=85,
frequency=50.0,
temperature=35,
model="YC600",
channel_qty=2,
power=[150, 160],
voltage=[230, 235]
)
ecu_data = ECUData(
ecu_id="216200063835",
timestamp="2026-01-11 15:30:00",
today_energy=5.5,
lifetime_energy=1234.5,
current_power=310,
qty_of_inverters=1,
qty_of_online_inverters=1,
firmware="ECU_R_1.2.3",
inverters=[inverter]
)
# Parse data
topics = parser.parse_ecu_data(ecu_data)
logger.info(f"✓ Parsed {len(topics)} topics")
# Verify some expected topics
expected_topics = [
"test/aps/216200063835/power",
"test/aps/216200063835/energy_today",
"test/aps/216200063835/123456789ABC/online",
]
for topic in expected_topics:
if topic in topics:
logger.info(f"✓ Found expected topic: {topic}")
else:
logger.warning(f"✗ Missing expected topic: {topic}")
return True
except Exception as err:
logger.error(f"✗ Parser test failed: {err}", exc_info=True)
return False
def test_ha_discovery():
"""Test HA discovery generator"""
logger.info("\nTesting HA discovery...")
try:
from aps2mqtt.ha_discovery import HADiscoveryGenerator
# Create with test path (models.csv may not exist)
generator = HADiscoveryGenerator("test", ".")
logger.info("✓ HADiscoveryGenerator created")
# Create test topics
test_topics = {
"test/aps/216200063835/power": "310",
"test/aps/216200063835/energy_today": "5.5",
"test/aps/216200063835/firmware": "ECU_R_1.2.3",
"test/aps/216200063835/123456789ABC/online": "on",
"test/aps/216200063835/123456789ABC/model": "YC600",
}
# Generate entities (may be empty if models.csv doesn't exist)
entities = generator.generate_from_topics(test_topics)
logger.info(f"✓ Generated {len(entities)} entities")
if len(entities) > 0:
logger.info(f" First entity topic: {entities[0].topic}")
else:
logger.info(" (No entities generated - models.csv may be missing)")
return True
except Exception as err:
logger.error(f"✗ HA discovery test failed: {err}", exc_info=True)
return False
def test_constants():
"""Test constants"""
logger.info("\nTesting constants...")
try:
from aps2mqtt import constants
# Check some important constants exist
assert hasattr(constants, 'DEFAULT_MQTT_BROKER_HOST')
assert hasattr(constants, 'DEFAULT_ECU_PORT')
assert hasattr(constants, 'INVERTER_MODELS')
assert hasattr(constants, 'HA_MANUFACTURER')
logger.info(f"✓ Constants loaded")
logger.info(f" DEFAULT_ECU_PORT = {constants.DEFAULT_ECU_PORT}")
logger.info(f" HA_MANUFACTURER = {constants.HA_MANUFACTURER}")
logger.info(f" Inverter models: {len(constants.INVERTER_MODELS)}")
return True
except Exception as err:
logger.error(f"✗ Constants test failed: {err}", exc_info=True)
return False
def main():
"""Run all tests"""
logger.info("=" * 60)
logger.info("APS2MQTT Refactored Modules Test Suite")
logger.info("=" * 60)
tests = [
("Imports", test_imports),
("Constants", test_constants),
("Models", test_models),
("Parser", test_parser),
("HA Discovery", test_ha_discovery),
]
results = []
for name, test_func in tests:
try:
result = test_func()
results.append((name, result))
except Exception as err:
logger.error(f"Test '{name}' crashed: {err}", exc_info=True)
results.append((name, False))
# Summary
logger.info("\n" + "=" * 60)
logger.info("Test Summary")
logger.info("=" * 60)
passed = sum(1 for _, result in results if result)
total = len(results)
for name, result in results:
status = "✓ PASS" if result else "✗ FAIL"
logger.info(f"{status}: {name}")
logger.info("-" * 60)
logger.info(f"Results: {passed}/{total} tests passed")
if passed == total:
logger.info("\n🎉 All tests passed!")
return 0
else:
logger.info(f"\n❌ {total - passed} test(s) failed")
return 1
if __name__ == "__main__":
sys.exit(main())