Skip to content
Myr

Merge pull request #3535 from nateprewitt/3339_avoid_getvalues

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

avoid use of getvalues in super_len

authored by Cory Benfield · committed by GitHub · parents 2041adb, f5c5974 · Browse files · 2 files+45 added−6 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+45 added−6 removed

  • tests:+28 added−0 removed
  • other:+17 added−6 removed

2 files+45 added−6 removed

modified:requests/utils.py+17 added-6 removed
43 unmodified lines
44 return d454647def super_len(o):48 total_length = 048 total_length = None49 current_position = 05051 if hasattr(o, '__len__'):52 total_length = len(o)5354 elif hasattr(o, 'len'):55 total_length = o.len5657 elif hasattr(o, 'getvalue'):58 # e.g. BytesIO, cStringIO.StringIO59 total_length = len(o.getvalue())6057 elif hasattr(o, 'fileno'):58 try:59 fileno = o.fileno()60 except io.UnsupportedOperation:
21 unmodified lines
82 # This can happen in some weird situations, such as when the file83 # is actually a special file descriptor like stdin. In this84 # instance, we don't know what the length is, so set it to zero and85 # let requests chunk it instead.86 if total_length is not None:90 current_position = total_length87 current_position = total_length8889 if hasattr(o, 'seek') and total_length is None:90 # StringIO and BytesIO have seek but no useable fileno9192 # seek to end of file93 o.seek(0, 2)94 total_length = o.tell()9596 # seek back to current position to support97 # partially read file-like objects98 o.seek(current_position or 0)99100 if total_length is None:101 total_length = 0102103 return max(0, total_length - current_position)104105106def get_netrc_auth(url, raise_errors=False):
722 unmodified lines
modified:tests/test_utils.py+28 added
64 unmodified lines
65 with file_obj.open(mode) as fd:66 assert super_len(fd) == 467 assert len(recwarn) == warnings_num6869 def test_super_len_with__len__(self):70 foo = [1,2,3,4]71 len_foo = super_len(foo)72 assert len_foo == 47374 def test_super_len_with_no__len__(self):75 class LenFile(object):76 def __init__(self):77 self.len = 57879 assert super_len(LenFile()) == 58081 def test_super_len_with_tell(self):82 foo = StringIO.StringIO('12345')83 assert super_len(foo) == 584 foo.read(2)85 assert super_len(foo) == 38687 def test_super_len_with_fileno(self):88 with open(__file__, 'rb') as f:89 length = super_len(f)90 file_data = f.read()91 assert length == len(file_data)9293 def test_super_len_with_no_matches(self):94 """Ensure that objects without any length methods default to 0"""95 assert super_len(object()) == 0969798class TestToKeyValList:99100 @pytest.mark.parametrize(101 'value, expected', (
402 unmodified lines