Skip to content
Open
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
4 changes: 3 additions & 1 deletion AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,6 @@ Patches and Suggestions

- Chris van Marle (https://github.com/qistoph)

- Florence Blanc-Renaud <flo@redhat.com> (@flo-renaud)
- Florence Blanc-Renaud <flo@redhat.com> (@flo-renaud)

- Nash Aschenbath (@Aschenbath)
15 changes: 13 additions & 2 deletions requests_toolbelt/multipart/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ class MultipartEncoder(object):
The ``MultipartEncoder`` object is a generic interface to the engine that
will create a ``multipart/form-data`` body for you.

File-like bodies must have a known length. If the length cannot be
determined, construction raises ``TypeError`` without reading the body.

The basic usage is:

.. code-block:: python
Expand Down Expand Up @@ -485,7 +488,11 @@ def __init__(self, headers, body):
self.headers = headers
self.body = body
self.headers_unread = True
self.len = len(self.headers) + total_len(self.body)
body_len = total_len(self.body)
if body_len is None:
raise TypeError(
'Could not determine the length of a multipart body')
self.len = len(self.headers) + body_len

@classmethod
def from_field(cls, field, encoding):
Expand Down Expand Up @@ -570,7 +577,11 @@ def __init__(self, file_object):

@property
def len(self):
return total_len(self.fd) - self.fd.tell()
file_len = total_len(self.fd)
if file_len is None:
raise TypeError(
'Could not determine the length of a file-like object')
return file_len - self.fd.tell()

def read(self, length=-1):
return self.fd.read(length)
Expand Down
60 changes: 59 additions & 1 deletion tests/test_multipart_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,72 @@

import pytest
from requests_toolbelt.multipart.encoder import (
CustomBytesIO, MultipartEncoder, FileFromURLWrapper, FileNotSupportedError)
CustomBytesIO, MultipartEncoder, FileFromURLWrapper, FileNotSupportedError,
total_len)
from requests_toolbelt._compat import filepost
from . import get_betamax


preserve_bytes = {'preserve_exact_body_bytes': True}


class UnknownLengthStream(object):
def read(self, size=-1):
raise AssertionError('Constructing the encoder must not read the body')


class UnsupportedFilenoStream(UnknownLengthStream):
def fileno(self):
raise io.UnsupportedOperation('No file descriptor')

def tell(self):
return 0


@pytest.mark.parametrize('stream_type', [
UnknownLengthStream, UnsupportedFilenoStream])
def test_unknown_length_stream_error(stream_type):
stream = stream_type()
assert total_len(stream) is None
with pytest.raises(TypeError, match='determine the length'):
MultipartEncoder({'file': ('sample.bin', stream)})


@pytest.mark.parametrize('payload', [b'', b'content'])
def test_known_length_stream(payload):
fields = [('file', ('sample.bin', io.BytesIO(payload),
'application/octet-stream'))]
encoder = MultipartEncoder(fields, boundary='boundary')
expected = filepost.encode_multipart_formdata(
[('file', ('sample.bin', payload))], boundary='boundary')[0]
assert encoder.len == len(expected)
assert encoder.to_string() == expected


def test_stream_length_exception_propagates():
error = TypeError('Broken length implementation')

class BrokenLengthStream(UnknownLengthStream):
def __len__(self):
raise error

with pytest.raises(TypeError) as caught:
MultipartEncoder({'file': ('sample.bin', BrokenLengthStream())})
assert caught.value is error


def test_stream_fileno_exception_propagates():
error = OSError('Broken file descriptor')

class BrokenFilenoStream(UnsupportedFilenoStream):
def fileno(self):
raise error

with pytest.raises(OSError) as caught:
MultipartEncoder({'file': ('sample.bin', BrokenFilenoStream())})
assert caught.value is error


class LargeFileMock(object):
def __init__(self):
# Let's keep track of how many bytes we've given
Expand Down