Skip to content

Commit

Permalink
bugfix: convert NaN to None when parsing readings [VIO-1369]
Browse files Browse the repository at this point in the history
  • Loading branch information
edaniszewski committed Sep 14, 2021
1 parent ca32147 commit 8e17725
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
12 changes: 12 additions & 0 deletions synse_server/cmd/read.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

import asyncio
import math
import queue
import threading
from typing import Any, AsyncIterable, Dict, List, Optional, Union
Expand Down Expand Up @@ -32,6 +33,17 @@ def reading_to_dict(reading: api.V3Reading) -> Dict[str, Any]:
if field is not None:
value = getattr(reading, field)

# Ensure the value is not NaN, as NaN is not a part of the
# JSON spec and could cause clients to error.
try:
float(value)
except ValueError:
# Not a real number, nothing to do.
pass
else:
if math.isnan(value):
value = None

if not reading.unit or (reading.unit.symbol == '' and reading.unit.name == ''):
unit = None
else:
Expand Down
31 changes: 30 additions & 1 deletion tests/unit/cmd/test_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import asynctest
import pytest
from synse_grpc import client
from synse_grpc import api, client

from synse_server import cmd, errors, plugin
from synse_server.cmd.read import reading_to_dict
Expand Down Expand Up @@ -675,3 +675,32 @@ def test_reading_to_dict_3(state_reading):
'unit': None,
'context': {},
}


def test_reading_to_dict_4_nan(state_reading):
"""Handle NaN when converting the gRPC message to JSON, as NaN is not
part of the JSON spec. NaN should be converted to None.
Regression for: https://vaporio.atlassian.net/browse/VIO-1369
"""

msg = api.V3Reading(
id='ddd',
timestamp='2019-04-22T13:30:00Z',
type='temperature',
deviceType='temperature',
deviceInfo='Example Temperature Device',
float64_value=float('nan'),
)

actual = reading_to_dict(msg)
assert actual == {
'device': 'ddd',
'timestamp': '2019-04-22T13:30:00Z',
'type': 'temperature',
'device_type': 'temperature',
'device_info': 'Example Temperature Device',
'value': None,
'unit': None,
'context': {},
}

0 comments on commit 8e17725

Please sign in to comment.