Skip to content

Commit

Permalink
Fix bug in remove_nones() when processing str (#290)
Browse files Browse the repository at this point in the history
`remove_nones()` only works with `list`s and `dict`s, not with other
iterables like `str`. However, the function didn't properly checked its
input and would crash when passed a `list` of `str`s.

Fixes: #289
  • Loading branch information
OrangeTux authored Jan 17, 2022
1 parent 99c12e2 commit 9d23044
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
22 changes: 9 additions & 13 deletions ocpp/charge_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import uuid
import re
import time
from typing import Union, List, Dict
from dataclasses import asdict

from ocpp.routing import create_route_map
Expand Down Expand Up @@ -70,19 +71,14 @@ def snake_to_camel_case(data):
return data


def remove_nones(dict_to_scan):
new_dict = {}
for k, v in dict_to_scan.items():
if isinstance(v, dict):
v = remove_nones(v)
if isinstance(v, list):
new_list = []
for item in v:
new_list.append(remove_nones(item))
v = new_list
if v is not None:
new_dict[k] = v
return new_dict
def remove_nones(data: Union[List, Dict]) -> Union[List, Dict]:
if isinstance(data, dict):
return {k: remove_nones(v) for k, v in data.items() if v is not None}

elif isinstance(data, list):
return [remove_nones(v) for v in data if v is not None]

return data


class ChargePoint:
Expand Down
19 changes: 18 additions & 1 deletion tests/test_charge_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import pytest
from ocpp.v20 import ChargePoint as cp
from ocpp.routing import on, create_route_map
from ocpp.v16.call import BootNotificationPayload, MeterValuesPayload
from ocpp.v16.call import (BootNotificationPayload, MeterValuesPayload,
GetConfigurationPayload)
from ocpp.v16.enums import Action
from ocpp.v16.datatypes import MeterValue, SampledValue
from ocpp.v201.call import SetNetworkProfilePayload
Expand Down Expand Up @@ -148,3 +149,19 @@ def test_nested_list_remove_nones():

payload = asdict(payload)
assert expected_payload == remove_nones(payload)


def test_remove_nones_with_list_of_strings():
""" Make sure that `remove_nones()` doesn't crash when it encounters an
iterable other than a list or dict. See
https://github.com/mobilityhouse/ocpp/issues/289.
"""
payload = asdict(
GetConfigurationPayload(
key=["ClockAlignedDataInterval", "ConnectionTimeOut"]
)
)

assert remove_nones(payload) == {
'key': ['ClockAlignedDataInterval', 'ConnectionTimeOut']
}

0 comments on commit 9d23044

Please sign in to comment.