Skip to content

Commit

Permalink
fix: inserting non-finite floats with insert_rows() (#728)
Browse files Browse the repository at this point in the history
  • Loading branch information
plamut committed Jul 1, 2021
1 parent ddd9ce7 commit d047419
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 7 additions & 1 deletion google/cloud/bigquery/_helpers.py
Expand Up @@ -17,6 +17,7 @@
import base64
import datetime
import decimal
import math
import re

from google.cloud._helpers import UTC
Expand Down Expand Up @@ -305,7 +306,12 @@ def _int_to_json(value):

def _float_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
return value if value is None else float(value)
if value is None:
return None
elif math.isnan(value) or math.isinf(value):
return str(value)
else:
return float(value)


def _decimal_to_json(value):
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test__helpers.py
Expand Up @@ -656,9 +656,24 @@ def _call_fut(self, value):

return _float_to_json(value)

def test_w_none(self):
self.assertEqual(self._call_fut(None), None)

def test_w_float(self):
self.assertEqual(self._call_fut(1.23), 1.23)

def test_w_nan(self):
result = self._call_fut(float("nan"))
self.assertEqual(result.lower(), "nan")

def test_w_infinity(self):
result = self._call_fut(float("inf"))
self.assertEqual(result.lower(), "inf")

def test_w_negative_infinity(self):
result = self._call_fut(float("-inf"))
self.assertEqual(result.lower(), "-inf")


class Test_decimal_to_json(unittest.TestCase):
def _call_fut(self, value):
Expand Down

0 comments on commit d047419

Please sign in to comment.