8000 Raise ValueError if text-mode file is passed to 'upload_from_file'. · googleapis/google-cloud-python@4a8e952 · GitHub
[go: up one dir, main page]

Skip to content

Commit 4a8e952

Browse files
committed
Raise ValueError if text-mode file is passed to 'upload_from_file'.
Addresses: #1779 (comment)
1 parent ceb1c07 commit 4a8e952

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

gcloud/bigquery/table.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -809,8 +809,9 @@ def upload_from_file(self,
809809
:rtype: :class:`gcloud.bigquery.jobs.LoadTableFromStorageJob`
810810
:returns: the job instance used to load the data (e.g., for
811811
querying status)
812-
:raises: :class:`ValueError` if size is not passed in and can not be
813-
determined
812+
:raises: :class:`ValueError` if ``size`` is not passed in and can not
813+
be determined, or if the ``file_obj`` can be detected to be
814+
a file opened in text mode.
814815
"""
815816
client = self._require_client(client)
816817
connection = client.connection
@@ -820,6 +821,12 @@ def upload_from_file(self,
820821
if rewind:
821822
file_obj.seek(0, os.SEEK_SET)
822823

824+
mode = getattr(file_obj, 'mode', None)
825+
if mode is not None and mode != 'rb':
826+
raise ValueError(
827+
"Cannot upload files opened in text mode: use "
828+
"open(filename, mode='rb')")
829+
823830
# Get the basic stats about the file.
824831
total_bytes = size
825832
if total_bytes is None:

gcloud/bigquery/test_table.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,6 +1289,19 @@ def _row_data(row):
12891289
self.assertEqual(req['path'], '/%s' % PATH)
12901290
self.assertEqual(req['data'], SENT)
12911291

1292+
def test_upload_from_file_text_mode_file_failure(self):
1293+
1294+
class TextModeFile(object):
1295+
mode = 'r'
1296+
1297+
conn = _Connection()
1298+
client = _Client(project=self.PROJECT, connection=conn)
1299+
dataset = _Dataset(client)
1300+
file_obj = TextModeFile()
1301+
table = self._makeOne(self.TABLE_NAME, dataset=dataset)
1302+
with self.assertRaises(ValueError):
1303+
table.upload_from_file(file_obj, 'CSV', size=1234)
1304+
12921305
def test_upload_from_file_size_failure(self):
12931306
conn = _Connection()
12941307
client = _Client(project=self.PROJECT, connection=conn)

0 commit comments

Comments
 (0)
0