Skip to content

Commit

Permalink
Raise ValueError if text-mode file is passed to 'upload_from_file'.
Browse files Browse the repository at this point in the history
Addresses:
#1779 (comment)
  • Loading branch information
tseaver committed May 11, 2016
1 parent ceb1c07 commit 4a8e952
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
11 changes: 9 additions & 2 deletions gcloud/bigquery/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -809,8 +809,9 @@ def upload_from_file(self,
:rtype: :class:`gcloud.bigquery.jobs.LoadTableFromStorageJob`
:returns: the job instance used to load the data (e.g., for
querying status)
:raises: :class:`ValueError` if size is not passed in and can not be
determined
:raises: :class:`ValueError` if ``size`` is not passed in and can not
be determined, or if the ``file_obj`` can be detected to be
a file opened in text mode.
"""
client = self._require_client(client)
connection = client.connection
Expand All @@ -820,6 +821,12 @@ def upload_from_file(self,
if rewind:
file_obj.seek(0, os.SEEK_SET)

mode = getattr(file_obj, 'mode', None)
if mode is not None and mode != 'rb':
raise ValueError(
"Cannot upload files opened in text mode: use "
"open(filename, mode='rb')")

# Get the basic stats about the file.
total_bytes = size
if total_bytes is None:
Expand Down
13 changes: 13 additions & 0 deletions gcloud/bigquery/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1289,6 +1289,19 @@ def _row_data(row):
self.assertEqual(req['path'], '/%s' % PATH)
self.assertEqual(req['data'], SENT)

def test_upload_from_file_text_mode_file_failure(self):

class TextModeFile(object):
mode = 'r'

conn = _Connection()
client = _Client(project=self.PROJECT, connection=conn)
dataset = _Dataset(client)
file_obj = TextModeFile()
table = self._makeOne(self.TABLE_NAME, dataset=dataset)
with self.assertRaises(ValueError):
table.upload_from_file(file_obj, 'CSV', size=1234)

def test_upload_from_file_size_failure(self):
conn = _Connection()
client = _Client(project=self.PROJECT, connection=conn)
Expand Down

0 comments on commit 4a8e952

Please sign in to comment.