Skip to content

Commit 04c5f59

Browse files
committed
handle server inconsistency and unit tests
1 parent c0e4595 commit 04c5f59

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

google/cloud/bigquery/schema.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,15 @@ def from_api_repr(cls, api_repr: dict) -> "SchemaField":
279279
"""
280280
placeholder = cls("this_will_be_replaced", "PLACEHOLDER")
281281

282+
# The API would return a string despite we send an integer. To ensure
283+
# success of resending received schema, we convert string to integer
284+
# to ensure consistency.
285+
if (
286+
isinstance(api_repr, dict)
287+
and type(api_repr.get("timestampPrecision")) is str
288+
):
289+
api_repr["timestampPrecision"] = int(api_repr["timestampPrecision"])
290+
282291
# Note: we don't make a copy of api_repr because this can cause
283292
# unnecessary slowdowns, especially on deeply nested STRUCT / RECORD
284293
# fields. See https://github.com/googleapis/python-bigquery/issues/6

tests/unit/test_schema.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,17 @@ def test_from_api_repr_defaults(self):
294294
self.assertNotIn("policyTags", field._properties)
295295
self.assertNotIn("rangeElementType", field._properties)
296296

297+
def test_from_api_repr_timestamp_precision_str(self):
298+
# The backend would return timestampPrecision field as a string, even
299+
# if we send over an integer. This test verifies we manually converted
300+
# it into integer to ensure resending could succeed.
301+
field = self._get_target_class().from_api_repr(
302+
{
303+
"timestampPrecision": "12",
304+
}
305+
)
306+
self.assertEqual(field._properties["timestampPrecision"], 12)
307+
297308
def test_name_property(self):
298309
name = "lemon-ness"
299310
schema_field = self._make_one(name, "INTEGER")
@@ -353,6 +364,14 @@ def test_foreign_type_definition_property_str(self):
353364
schema_field._properties["foreignTypeDefinition"] = FOREIGN_TYPE_DEFINITION
354365
self.assertEqual(schema_field.foreign_type_definition, FOREIGN_TYPE_DEFINITION)
355366

367+
def test_timestamp_precision_unsupported_type(self):
368+
with pytest.raises(ValueError) as e:
369+
self._make_one("test", "TIMESTAMP", timestamp_precision=12)
370+
371+
assert "timestamp_precision must be class enums.TimestampPrecision" in str(
372+
e.value
373+
)
374+
356375
def test_timestamp_precision_property(self):
357376
TIMESTAMP_PRECISION = enums.TimestampPrecision.PICOSECOND
358377
schema_field = self._make_one("test", "TIMESTAMP")

0 commit comments

Comments
 (0)