Debian Codegraph @

tests/test_messages.py

raw
1 import decimal
2 import json
3 import threading
4 from datetime import datetime
5
6 import pytest
7 from hypothesis import given
8 from hypothesis.strategies import binary
9
10 import ocpp
11 from ocpp.exceptions import (
12 FormatViolationError,
13 NotImplementedError,
14 PropertyConstraintViolationError,
15 ProtocolError,
16 TypeConstraintViolationError,
17 UnknownCallErrorCodeError,
18 ValidationError,
19 )
20 from ocpp.messages import (
21 Call,
22 CallError,
23 CallResult,
24 MessageType,
25 _DecimalEncoder,
26 _validate_payload,
27 _validators,
28 get_validator,
29 pack,
30 unpack,
31 validate_payload,
32 )
33 from ocpp.v16.enums import Action
34
35
36 def test_unpack_with_invalid_json():
37 """
38 Test that correct exception is raised when unpack is called with invalid
39 JSON.
40 """
41 with pytest.raises(FormatViolationError):
42 unpack(b"\x01")
43
44
45 @given(binary())
46 def test_unpack_and_pack(data):
47 try:
48 assert unpack(data) == pack(data)
49 except Exception as e:
50 assert type(e) in [
51 FormatViolationError,
52 ProtocolError,
53 PropertyConstraintViolationError,
54 ]
55
56
57 def test_unpack_without_jsonified_list():
58 """
59 OCPP messages are JSONified lists. This test make sure that the correct
60 exception is raised when input is not a JSONified list.
61 """
62 with pytest.raises(ProtocolError):
63 unpack(json.dumps("3"))
64
65
66 def test_unpack_without_message_type_id_in_json():
67 """
68 OCPP must contain the MessageTypeID as first element of the message.
69 This test validates if correct exception is raised when this is not
70 the case
71 """
72 with pytest.raises(ProtocolError):
73 unpack(json.dumps([]))
74
75
76 def test_unpack_with_invalid_message_type_id_in_json():
77 """
78 OCPP messages only have 3 valid values for MessageTypeID, that is the first
79 element of the OCPP message. This test validates that correct exception is
80 raised when this value is invalid.
81 """
82 with pytest.raises(PropertyConstraintViolationError):
83 unpack(json.dumps([5, 1]))
84
85
86 def test_get_validator_with_valid_name():
87 """
88 Test if correct validator is returned and if validator is added to cache.
89 """
90 schema = get_validator(MessageType.Call, "Reset", ocpp_version="1.6")
91
92 assert schema == _validators["Reset_1.6"]
93 assert schema.schema == {
94 "$schema": "http://json-schema.org/draft-04/schema#",
95 "title": "ResetRequest",
96 "type": "object",
97 "properties": {
98 "type": {
99 "additionalProperties": False,
100 "type": "string",
101 "enum": ["Hard", "Soft"],
102 }
103 },
104 "additionalProperties": False,
105 "required": ["type"],
106 }
107
108
109 def test_get_validator_with_invalid_name():
110 """
111 Test if OSError is raised when schema validation file cannnot be found.
112 """
113 with pytest.raises(OSError):
114 get_validator(MessageType.Call, "non-existing", ocpp_version="1.6")
115
116
117 def test_validate_set_charging_profile_payload():
118 """ " Test if payloads with floats are validated correctly.
119
120 This test uses the value of 21.4, which is internally represented as
121 21.39999999999999857891452847979962825775146484375.
122 You can verify this using `decimal.Decimal(21.4)`
123 """
124 message = Call(
125 unique_id="1234",
126 action=Action.set_charging_profile,
127 payload={
128 "connectorId": 1,
129 "csChargingProfiles": {
130 "chargingProfileId": 1,
131 "stackLevel": 0,
132 "chargingProfilePurpose": "TxProfile",
133 "chargingProfileKind": "Relative",
134 "chargingSchedule": {
135 "chargingRateUnit": "A",
136 "chargingSchedulePeriod": [{"startPeriod": 0, "limit": 21.4}],
137 },
138 "transactionId": 123456789,
139 },
140 },
141 )
142
143 _validate_payload(message, ocpp_version="1.6")
144
145
146 def test_validate_get_composite_profile_payload():
147 """ " Test if payloads with floats are validated correctly.
148
149 This test uses the value of 15.2, which is internally represented as
150 15.19999999999999857891452847979962825775146484375.
151 You can verify this using `decimal.Decimal(15.2)`
152 """
153 message = CallResult(
154 unique_id="1234",
155 action=Action.get_composite_schedule,
156 payload={
157 "status": "Accepted",
158 "connectorId": 1,
159 "scheduleStart": "2021-06-15T14:01:32Z",
160 "chargingSchedule": {
161 "duration": 60,
162 "chargingRateUnit": "A",
163 "chargingSchedulePeriod": [{"startPeriod": 0, "limit": 15.2}],
164 },
165 },
166 )
167
168 _validate_payload(message, ocpp_version="1.6")
169
170
171 @pytest.mark.parametrize("ocpp_version", ["1.6", "2.0.1"])
172 def test_validate_payload_with_valid_payload(ocpp_version):
173 """
174 Test if validate_payload doesn't return any exceptions when it's
175 validating a valid payload.
176 """
177 message = CallResult(
178 unique_id="1234",
179 action=Action.heartbeat,
180 payload={"currentTime": datetime.now().isoformat()},
181 )
182
183 _validate_payload(message, ocpp_version=ocpp_version)
184
185
186 def test_validate_payload_with_invalid_additional_properties_payload():
187 """
188 Test if validate_payload raises FormatViolationError when validation of
189 payload with unrequested properties fails.
190 """
191 message = CallResult(
192 unique_id="1234",
193 action=Action.heartbeat,
194 payload={"invalid_key": True},
195 )
196
197 with pytest.raises(FormatViolationError):
198 _validate_payload(message, ocpp_version="1.6")
199
200
201 def test_validate_payload_with_invalid_type_payload():
202 """
203 Test if validate_payload raises TypeConstraintViolationError when
204 validation of payload with mismatched type fails.
205 """
206 message = Call(
207 unique_id="1234",
208 action=Action.start_transaction,
209 payload={
210 "connectorId": 1,
211 "idTag": "okTag",
212 "meterStart": "invalid_type",
213 "timestamp": "2022-01-25T19:18:30.018Z",
214 },
215 )
216
217 with pytest.raises(TypeConstraintViolationError):
218 _validate_payload(message, ocpp_version="1.6")
219
220
221 def test_validate_payload_with_invalid_missing_property_payload():
222 """
223 Test if validate_payload raises ProtocolError when validation of
224 payload with missing properties fails.
225 """
226 message = Call(
227 unique_id="1234",
228 action=Action.start_transaction,
229 payload={
230 "connectorId": 1,
231 "idTag": "okTag",
232 # meterStart is purposely missing
233 "timestamp": "2022-01-25T19:18:30.018Z",
234 },
235 )
236
237 with pytest.raises(ProtocolError):
238 _validate_payload(message, ocpp_version="1.6")
239
240
241 def test_validate_payload_with_invalid_message_type_id():
242 """
243 Test if validate_payload raises ValidationError when it is called with
244 a message type id other than 2, Call, or 3, CallError.
245 """
246 with pytest.raises(ValidationError):
247 _validate_payload(dict(), ocpp_version="1.6")
248
249
250 def test_validate_payload_with_non_existing_schema():
251 """
252 Test if correct exception is raised when a validation schema cannot be
253 found.
254 """
255 message = CallResult(
256 unique_id="1234",
257 action="MagicSpell",
258 payload={"invalid_key": True},
259 )
260
261 with pytest.raises(NotImplementedError):
262 _validate_payload(message, ocpp_version="1.6")
263
264
265 def test_call_error_representation():
266 call = CallError(
267 unique_id=1,
268 error_code="GenericError",
269 error_description="Some message",
270 error_details={},
271 )
272
273 assert (
274 str(call) == "<CallError - unique_id=1, error_code=GenericError, "
275 "error_description=Some message, error_details={}>"
276 )
277
278
279 def test_call_representation():
280 call = Call(unique_id="1", action=Action.heartbeat, payload={})
281
282 assert str(call) == "<Call - unique_id=1, action=Heartbeat, payload={}>"
283
284
285 def test_call_result_representation():
286 call = CallResult(
287 unique_id="1", action=Action.authorize, payload={"status": "Accepted"}
288 )
289
290 assert (
291 str(call) == "<CallResult - unique_id=1, action=Authorize, payload={'status': "
292 "'Accepted'}>"
293 )
294
295
296 def test_creating_exception_from_call_error():
297 call_error = CallError(
298 unique_id="1337",
299 error_code="ProtocolError",
300 error_description="Something went wrong",
301 error_details="Some details about the error",
302 )
303
304 assert call_error.to_exception() == ProtocolError(
305 description="Something went wrong", details="Some details about the error"
306 )
307
308
309 def test_creating_exception_from_call_error_with_unknown_error_code():
310 call_error = CallError(
311 unique_id="1337",
312 error_code="418",
313 error_description="I'm a teapot",
314 )
315
316 with pytest.raises(UnknownCallErrorCodeError):
317 call_error.to_exception()
318
319
320 def test_serializing_decimal():
321 assert json.dumps([decimal.Decimal(2.000001)], cls=_DecimalEncoder) == "[2.0]"
322
323
324 def test_serializing_custom_types():
325 """
326 validate_payload() raises an exception receives an invalid OCPP message.
327 This exception contains the Call causing the problem.
328
329 The exception is turned into a CallError which in serialized to JSON.
330 https://github.com/mobilityhouse/ocpp/issues/395 tracks a bug where serialization
331 would fails because Call is not serializable.
332
333 This test verifies that fix for that bug.
334
335 """
336 message = Call(
337 unique_id="1234",
338 action=Action.start_transaction,
339 payload={
340 "connectorId": 1,
341 "idTag": "okTag",
342 "meterStart": "invalid_type",
343 "timestamp": "2022-01-25T19:18:30.018Z",
344 },
345 )
346
347 try:
348 _validate_payload(message, ocpp_version="1.6")
349 except TypeConstraintViolationError as error:
350 # Before the fix, this call would fail with a TypError. Lack of any error
351 # makes this test pass.
352 _ = message.create_call_error(error).to_json()
353
354
355 def test_validate_meter_values_hertz():
356 """
357 Tests that a unit of measure called "Hertz" is permitted in validation.
358 This was missing from the original 1.6 spec, but was added as an errata
359 (see the OCPP 1.6 Errata sheet, v4.0 Release, 2019-10-23, page 34).
360 """
361 message = Call(
362 unique_id="1234",
363 action=Action.meter_values,
364 payload={
365 "connectorId": 1,
366 "transactionId": 123456789,
367 "meterValue": [
368 {
369 "timestamp": "2020-02-21T13:48:45.459756Z",
370 "sampledValue": [
371 {
372 "value": "50.0",
373 "measurand": "Frequency",
374 "unit": "Hertz",
375 }
376 ],
377 }
378 ],
379 },
380 )
381
382 _validate_payload(message, ocpp_version="1.6")
383
384
385 def test_validate_set_maxlength_violation_payload():
386 """
387 Test if payloads that violate maxLength raise a
388 TypeConstraintViolationError
389 """
390 message = Call(
391 unique_id="1234",
392 action=Action.start_transaction,
393 payload={
394 "idTag": "012345678901234567890",
395 "connectorId": 1,
396 },
397 )
398
399 with pytest.raises(TypeConstraintViolationError):
400 _validate_payload(message, ocpp_version="1.6")
401
402
403 @pytest.mark.parametrize("use_threads", [False, True])
404 @pytest.mark.asyncio
405 async def test_validate_payload_threads(use_threads):
406 """
407 Test that threads usage can be configured
408 """
409 message = CallResult(
410 unique_id="1234",
411 action=Action.heartbeat,
412 payload={"currentTime": datetime.now().isoformat()},
413 )
414
415 assert threading.active_count() == 1
416 ocpp.messages.ASYNC_VALIDATION = use_threads
417 await validate_payload(message, ocpp_version="1.6")
418 if use_threads:
419 assert threading.active_count() > 1
420 else:
421 assert threading.active_count() == 1