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: insert_rows() error with floats as strings #824

Merged
merged 1 commit into from
Jul 28, 2021
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
12 changes: 7 additions & 5 deletions google/cloud/bigquery/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import decimal
import math
import re
from typing import Union

from google.cloud._helpers import UTC
from google.cloud._helpers import _date_from_iso8601_date
Expand Down Expand Up @@ -338,14 +339,15 @@ def _int_to_json(value):
return value


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

if isinstance(value, str):
value = float(value)

return str(value) if (math.isnan(value) or math.isinf(value)) else float(value)


def _decimal_to_json(value):
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/test__helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,21 +690,45 @@ def _call_fut(self, value):
def test_w_none(self):
self.assertEqual(self._call_fut(None), None)

def test_w_non_numeric(self):
with self.assertRaises(TypeError):
self._call_fut(object())

def test_w_integer(self):
result = self._call_fut(123)
self.assertIsInstance(result, float)
self.assertEqual(result, 123.0)

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

def test_w_float_as_string(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_nan_as_string(self):
result = self._call_fut("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_infinity_as_string(self):
result = self._call_fut("inf")
self.assertEqual(result.lower(), "inf")

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

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


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