Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix validation of payloads containing floats #45

Merged
merged 2 commits into from
Nov 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 40 additions & 13 deletions ocpp/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
also contain some helper functions for packing and unpacking messages. """
import os
import json
import decimal
from dataclasses import asdict, is_dataclass

from jsonschema import validate
Expand Down Expand Up @@ -61,11 +62,14 @@ def pack(msg):
return msg.to_json()


def get_schema(message_type_id, action, ocpp_version):
def get_schema(message_type_id, action, ocpp_version, parse_float=float):
"""
Read schema from disk and return in. Reads will be cached for performance
reasons.

The `parse_float` argument can be used to set the conversion method that
is used to parse floats. It must be a callable taking 1 argument. By
default it is `float()`, but certain schema's require `decimal.Decimal()`.
"""
if ocpp_version not in ["1.6", "2.0"]:
raise ValueError
Expand Down Expand Up @@ -95,7 +99,7 @@ def get_schema(message_type_id, action, ocpp_version):
# Unexpected UTF-8 BOM (decode using utf-8-sig):
with open(path, 'r', encoding='utf-8-sig') as f:
data = f.read()
_schemas[relative_path] = json.loads(data)
_schemas[relative_path] = json.loads(data, parse_float=parse_float)

return _schemas[relative_path]

Expand All @@ -108,21 +112,44 @@ def validate_payload(message, ocpp_version):
"be either 'Call' or 'CallResult'.")

try:
schema = get_schema(
message.message_type_id, message.action, ocpp_version
)
# 3 OCPP 1.6 schedules have fields of type floats. The JSON schema
# defines a certain precision for these fields of 1 decimal. A value of
# 21.4 is valid, whereas a value if 4.11 is not.
#
# The problem is that Python's internal representation of 21.4 might
# have more than 1 decimal. It might be 21.399999999999995. This would
# make the validation fail, although the payload is correct. This is a
# known issue with jsonschemas, see:
# https://github.com/Julian/jsonschema/issues/247
#
# This issue can be fixed by using a different parser for floats than
# the default one that is used.
#
# Both the schema and the payload must be parsed using the different
# parser for floats.
if ocpp_version == '1.6' and (
(type(message) == Call and
message.action in ['SetChargingProfile', 'RemoteStartTransaction']) # noqa
or
(type(message) == CallResult and
message.action == ['GetCompositeSchedule'])
):
schema = get_schema(
message.message_type_id, message.action,
ocpp_version, parse_float=decimal.Decimal
)

message.payload = json.loads(
json.dumps(message.payload), parse_float=decimal.Decimal
)
else:
schema = get_schema(
message.message_type_id, message.action, ocpp_version
)
except (OSError, json.JSONDecodeError) as e:
raise ValidationError("Failed to load validation schema for action "
f"'{message.action}': {e}")

if message.action in [
'RemoteStartTransaction',
'SetChargingProfile',
'RequestStartTransaction',
]:
# todo: special actions
pass

try:
validate(message.payload, schema)
except SchemaValidationError as e:
Expand Down
32 changes: 32 additions & 0 deletions tests/test_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,38 @@ def test_get_schema_with_valid_name():
}


def test_validate_set_charging_profile_payload():
"""" Test if payloads with floats are validated correctly.

This test uses the value of 21.4, which is internally represented as
21.39999999999999857891452847979962825775146484375.
You can verify this using `decimal.Decimal(21.4)`
"""
message = Call(
unique_id="1234",
action="SetChargingProfile",
payload={
'connectorId': 1,
'csChargingProfiles': {
'chargingProfileId': 1,
'stackLevel': 0,
'chargingProfilePurpose': 'TxProfile',
'chargingProfileKind': 'Relative',
'chargingSchedule': {
'chargingRateUnit': 'A',
'chargingSchedulePeriod': [{
'startPeriod': 0,
'limit': 21.4
}]
},
'transactionId': 123456789,
}
}
)

validate_payload(message, ocpp_version="1.6")


def test_get_schema_with_invalid_name():
"""
Test if OSError is raised when schema validation file cannnot be found.
Expand Down