From d3b7bcb0a5752214c377e9193daf88cebdda50a1 Mon Sep 17 00:00:00 2001 From: Erick Daniszewski Date: Thu, 30 Sep 2021 09:22:47 -0400 Subject: [PATCH] bugfix: fix nan check to account for values castable to float (VIO-1616) --- synse_server/cmd/read.py | 8 +++---- tests/unit/cmd/test_read.py | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/synse_server/cmd/read.py b/synse_server/cmd/read.py index 94ad6699..a1809925 100644 --- a/synse_server/cmd/read.py +++ b/synse_server/cmd/read.py @@ -36,13 +36,11 @@ def reading_to_dict(reading: api.V3Reading) -> Dict[str, Any]: # 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: + if math.isnan(float(value)): + value = None + except (ValueError, TypeError): # 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 diff --git a/tests/unit/cmd/test_read.py b/tests/unit/cmd/test_read.py index f92dd473..a249865f 100644 --- a/tests/unit/cmd/test_read.py +++ b/tests/unit/cmd/test_read.py @@ -704,3 +704,45 @@ def test_reading_to_dict_4_nan(state_reading): 'unit': None, 'context': {}, } + + +@pytest.mark.parametrize( + 'reading_value', [ + "000000", + "0", + "1", + "-1", + "ff0033", + "fab", + "FFAADD", + "319a81", + ] +) +def test_reading_to_dict_5_float_not_nan(state_reading, reading_value: str) -> None: + """Convert a reading to a dictionary. Here, the string value is castable to + a float, and thus will go through the NaN check, but should fail the check since + the float values do not resolve to NaN. + + Regression for: https://vaporio.atlassian.net/browse/VIO-1616 + """ + + msg = api.V3Reading( + id='ddd', + timestamp='2019-04-22T13:30:00Z', + type='color', + deviceType='led', + deviceInfo='Example LED Device', + string_value=reading_value, + ) + + actual = reading_to_dict(msg) + assert actual == { + 'device': 'ddd', + 'timestamp': '2019-04-22T13:30:00Z', + 'type': 'color', + 'device_type': 'led', + 'device_info': 'Example LED Device', + 'value': reading_value, + 'unit': None, + 'context': {}, + }