Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strip empty fields in MultipartEncoder #326

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions requests_toolbelt/multipart/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ def __init__(self, fields, boundary=None, encoding='utf-8'):
# Load boundary into buffer
self._write_boundary()

def __eq__(self, other) -> bool:
if isinstance(other, bytes):
return self.to_string() == other
else:
super().__eq__(other)

@property
def len(self):
"""Length of the multipart/form-data body.
Expand Down Expand Up @@ -227,6 +233,8 @@ def _iter_fields(self):
file_name, file_pointer, file_type = v
else:
file_name, file_pointer, file_type, file_headers = v
elif v is None:
continue
else:
file_pointer = v

Expand Down
25 changes: 20 additions & 5 deletions tests/test_multipart_encoder.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
# -*- coding: utf-8 -*-
import unittest
import io
import unittest

import requests

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

from . import get_betamax

preserve_bytes = {'preserve_exact_body_bytes': True}

Expand Down Expand Up @@ -273,6 +276,18 @@ def test_regression_2(self):

assert read_so_far == total_size

def test_empty_files_key(self):
"""Ensure empty `fields` keys are stripped from the request"""

fields = {
"test": "this is a test",
"empty": None
}

m = MultipartEncoder(fields=fields)

assert len(m.parts) == 1

def test_handles_empty_unicode_values(self):
"""Verify that the Encoder can handle empty unicode strings.

Expand Down