Skip to content

Commit 2b46d8b

Browse files
author
Luiko Czub
committed
_getAttachmentArgs() handle now TypeError #39
1 parent d25bf59 commit 2b46d8b

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

Diff for: src/testlink/testlinkapigeneric.py

+32-9
Original file line numberDiff line numberDiff line change
@@ -1248,26 +1248,49 @@ def _getAttachmentArgs(self, attachmentfile):
12481248
a) a python file descriptor pointing to the file (class file)
12491249
b) a valid file path"""
12501250

1251-
a_file_obj = None
1252-
is_file_obj = isinstance(attachmentfile, file)
1253-
if not is_file_obj:
1254-
# handling a file path
1251+
try:
1252+
# try to handle ATTACHMENTFILE as a file path
12551253
a_file_path = attachmentfile
12561254
a_file_obj = self._openAttachmentForRead(a_file_path)
1257-
else:
1258-
# handling a file object
1255+
already_file_obj = False
1256+
except TypeError:
1257+
# ATTACHMENTFILE seams to be a file object
12591258
a_file_path = attachmentfile.name
12601259
a_file_obj = attachmentfile
1260+
already_file_obj = True
1261+
1262+
try:
1263+
encoded_data = encodebytes(a_file_obj.read())
1264+
except TypeError:
1265+
# a_file_obj seams to have a wrong read mode
1266+
# try to reopen it, if ATTACHMENTFILE already was a file obj
1267+
if already_file_obj:
1268+
encoded_data = self._getAttachmentArgs(attachmentfile.name)
1269+
else:
1270+
raise testlinkerrors.TLArgError(
1271+
'invalid attachment file: %s' % attachmentfile)
1272+
12611273

12621274
return {'filename':os.path.basename(a_file_path),
12631275
'filetype':guess_type(a_file_path)[0],
1264-
'content':encodebytes(a_file_obj.read())
1276+
'content':encoded_data
12651277
}
12661278

12671279
def _openAttachmentForRead(self, a_file_path):
1268-
""" opens the A_FILE_PATH for reading and returns the file descriptor.
1280+
""" open A_FILE_PATH for reading and returns the file descriptor.
12691281
Read mode will be set depending from py version and mimetype
1270-
PY2: text file = 'r', others = 'rb' PY3: general 'rb' """
1282+
PY2: text file = 'r', others = 'rb' PY3: general 'rb'
1283+
1284+
Raise TLArgError, if A_FILE_PATH is not valid
1285+
1286+
site effect: raise TypeError, if A_FILE_PATH is not a string
1287+
"""
1288+
1289+
if not os.path.exists(a_file_path):
1290+
# file path does not exists
1291+
raise testlinkerrors.TLArgError(
1292+
'invalid attachment path: %s' % a_file_path)
1293+
12711294
a_read_mode = 'rb'
12721295
is_text_file = 'text/' in guess_type(a_file_path)
12731296
if not IS_PY3 and is_text_file:

0 commit comments

Comments
 (0)