Skip to content
Myr

Increasing super_len compatibilty to include BytesIO and cStringIO objects.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Added a check for 'getvalue' attr, calling it to retrieve the length if we can. We also try/except the fileno() call, which can throw io.UnsupportedOperation for BytesIO because, well, they're not files.

authored by Matt Spitz · committed by Matt Spitz · parent 025543b · Browse files · 2 files+33 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+33 added−1 removed

  • other:+33 added−1 removed

2 files+33 added−1 removed

modified:requests/utils.py+12 added-1 removed
10 unmodified lines
1112import cgi13import codecs14import collections15import io16import os17import platform18import re19import sys
26 unmodified lines
4647def super_len(o):48 if hasattr(o, '__len__'):49 return len(o)5051 if hasattr(o, 'len'):52 return o.len5354 if hasattr(o, 'fileno'):55 try:56 fileno = o.fileno()57 except io.UnsupportedOperation:58 pass59 else:52 return os.fstat(o.fileno()).st_size60 return os.fstat(fileno).st_size6162 if hasattr(o, 'getvalue'):63 # e.g. BytesIO, cStringIO.StringI64 return len(o.getvalue())6566def get_netrc_auth(url):67 """Returns the Requests tuple auth for a given url from netrc."""68
514 unmodified lines
modified:test_requests.py+21 added
871 unmodified lines
872 self.assertEqual(frozenset(cid.keys()), keyset)873 self.assertEqual(frozenset(cid), keyset)874875876class UtilsTestCase(unittest.TestCase):877878 def test_super_len_io_streams(self):879 """ Ensures that we properly deal with different kinds of IO streams. """880 # uses StringIO or io.StringIO (see import above)881 from io import BytesIO882 from requests.utils import super_len883884 self.assertEqual(super_len(StringIO.StringIO()), 0)885 self.assertEqual(super_len(StringIO.StringIO('with so much drama in the LBC')), 29)886887 self.assertEqual(super_len(BytesIO()), 0)888 self.assertEqual(super_len(BytesIO(b"it's kinda hard bein' snoop d-o-double-g")), 40)889890 try:891 import cStringIO892 except ImportError:893 pass894 else:895 self.assertEqual(super_len(cStringIO.StringIO('but some how, some way...')), 25)896897if __name__ == '__main__':898 unittest.main()