Skip to content

Commit f84058e

Browse files
tweak binary funcs param checking + tests
1 parent 67689f7 commit f84058e

File tree

3 files changed

+50
-13
lines changed

3 files changed

+50
-13
lines changed

tests/test_binary_vdf.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,16 @@ def test_dumps_unicode(self):
6565
def test_dumps_unicode_alternative(self):
6666
self.assertEqual(vdf.binary_dumps({u('a'): u('b')}, alt_format=True), b'\x01a\x00b\x00\x0b')
6767

68+
def test_dump_params_invalid(self):
69+
with self.assertRaises(TypeError):
70+
vdf.binary_dump([], BytesIO())
71+
vdf.binary_dump({}, b'aaaa')
72+
73+
def test_dumps_params_invalid(self):
74+
with self.assertRaises(TypeError):
75+
vdf.binary_dumps([])
76+
vdf.binary_dumps(b'aaaa')
77+
6878
def test_dumps_key_invalid_type(self):
6979
with self.assertRaises(TypeError):
7080
vdf.binary_dumps({1:1})
@@ -81,6 +91,19 @@ def test_alternative_format(self):
8191
with self.assertRaises(SyntaxError):
8292
vdf.binary_loads(b'\x00a\x00\x00b\x00\x08\x08', alt_format=True)
8393

94+
def test_load_params_invalid(self):
95+
with self.assertRaises(TypeError):
96+
vdf.binary_load(b'aaaa')
97+
vdf.binary_load(1234)
98+
vdf.binary_load(BytesIO(b'aaaa'), b'bbbb')
99+
100+
def test_loads_params_invalid(self):
101+
with self.assertRaises(TypeError):
102+
vdf.binary_loads([])
103+
vdf.binary_loads(11111)
104+
vdf.binary_loads(BytesIO())
105+
vdf.binary_load(b'', b'bbbb')
106+
84107
def test_loads_unbalanced_nesting(self):
85108
with self.assertRaises(SyntaxError):
86109
vdf.binary_loads(b'\x00a\x00\x00b\x00\x08')

tests/test_vdf.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,14 @@ def setUp(self):
8484
def tearDown(self):
8585
self.f.close()
8686

87+
def test_dump_params_invalid(self):
88+
with self.assertRaises(TypeError):
89+
# pretty/escaped only accept bool
90+
vdf.dump({'a': 1}, StringIO(), pretty=1)
91+
vdf.dumps({'a': 1}, pretty=1)
92+
vdf.dump({'a': 1}, StringIO(), escaped=1)
93+
vdf.dumps({'a': 1}, escaped=1)
94+
8795
def test_routine_dumps_asserts(self):
8896
for x in [5, 5.5, 1.0j, True, None, (), {}, lambda: 0, sys.stdin, self.f]:
8997
for y in [5, 5.5, 1.0j, None, [], (), {}, lambda: 0, sys.stdin, self.f]:

vdf/__init__.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,14 @@
88
import sys
99
import struct
1010
from binascii import crc32
11-
from io import StringIO as unicodeIO
1211
from io import BytesIO
12+
from io import StringIO as unicodeIO
13+
14+
try:
15+
from collections.abc import Mapping
16+
except:
17+
from collections import Mapping
18+
1319
from vdf.vdict import VDFDict
1420

1521
# Py2 & Py3 compatibility
@@ -72,7 +78,7 @@ def parse(fp, mapper=dict, merge_duplicate_keys=True, escaped=True):
7278
same key into one instead of overwriting. You can se this to ``False`` if you are
7379
using ``VDFDict`` and need to preserve the duplicates.
7480
"""
75-
if not issubclass(mapper, dict):
81+
if not issubclass(mapper, Mapping):
7682
raise TypeError("Expected mapper to be subclass of dict, got %s" % type(mapper))
7783
if not hasattr(fp, 'readline'):
7884
raise TypeError("Expected fp to be a file-like object supporting line iteration")
@@ -200,7 +206,7 @@ def dumps(obj, pretty=False, escaped=True):
200206
"""
201207
Serialize ``obj`` to a VDF formatted ``str``.
202208
"""
203-
if not isinstance(obj, dict):
209+
if not isinstance(obj, Mapping):
204210
raise TypeError("Expected data to be an instance of``dict``")
205211
if not isinstance(pretty, bool):
206212
raise TypeError("Expected pretty to be of type bool")
@@ -215,7 +221,7 @@ def dump(obj, fp, pretty=False, escaped=True):
215221
Serialize ``obj`` as a VDF formatted stream to ``fp`` (a
216222
``.write()``-supporting file-like object).
217223
"""
218-
if not isinstance(obj, dict):
224+
if not isinstance(obj, Mapping):
219225
raise TypeError("Expected data to be an instance of``dict``")
220226
if not hasattr(fp, 'write'):
221227
raise TypeError("Expected fp to have write() method")
@@ -239,7 +245,7 @@ def _dump_gen(data, pretty=False, escaped=True, level=0):
239245
if escaped and isinstance(key, string_type):
240246
key = _escape(key)
241247

242-
if isinstance(value, dict):
248+
if isinstance(value, Mapping):
243249
yield '%s"%s"\n%s{\n' % (line_indent, key, line_indent)
244250
for chunk in _dump_gen(value, pretty, escaped, level+1):
245251
yield chunk
@@ -295,12 +301,8 @@ def binary_loads(b, mapper=dict, merge_duplicate_keys=True, alt_format=False, ra
295301
"""
296302
if not isinstance(b, bytes):
297303
raise TypeError("Expected s to be bytes, got %s" % type(b))
298-
if not issubclass(mapper, dict):
299-
raise TypeError("Expected mapper to be subclass of dict, got %s" % type(mapper))
300-
301-
fp = BytesIO(b)
302304

303-
return binary_load(fp, mapper, merge_duplicate_keys, alt_format, raise_on_remaining)
305+
return binary_load(BytesIO(b), mapper, merge_duplicate_keys, alt_format, raise_on_remaining)
304306

305307
def binary_load(fp, mapper=dict, merge_duplicate_keys=True, alt_format=False, raise_on_remaining=False):
306308
"""
@@ -317,7 +319,7 @@ def binary_load(fp, mapper=dict, merge_duplicate_keys=True, alt_format=False, ra
317319
"""
318320
if not hasattr(fp, 'read') or not hasattr(fp, 'tell') or not hasattr(fp, 'seek'):
319321
raise TypeError("Expected fp to be a file-like object with tell()/seek() and read() returning bytes")
320-
if not issubclass(mapper, dict):
322+
if not issubclass(mapper, Mapping):
321323
raise TypeError("Expected mapper to be subclass of dict, got %s" % type(mapper))
322324

323325
# helpers
@@ -415,12 +417,16 @@ def binary_dumps(obj, alt_format=False):
415417
"""
416418
Serialize ``obj`` to a binary VDF formatted ``bytes``.
417419
"""
418-
return b''.join(_binary_dump_gen(obj, alt_format=alt_format))
420+
buf = BytesIO()
421+
binary_dump(obj, buf, alt_format)
422+
return buf.getvalue()
419423

420424
def binary_dump(obj, fp, alt_format=False):
421425
"""
422426
Serialize ``obj`` to a binary VDF formatted ``bytes`` and write it to ``fp`` filelike object
423427
"""
428+
if not isinstance(obj, Mapping):
429+
raise TypeError("Expected obj to be type of Mapping")
424430
if not hasattr(fp, 'write'):
425431
raise TypeError("Expected fp to have write() method")
426432

@@ -442,7 +448,7 @@ def _binary_dump_gen(obj, level=0, alt_format=False):
442448
else:
443449
raise TypeError("dict keys must be of type str, got %s" % type(key))
444450

445-
if isinstance(value, dict):
451+
if isinstance(value, Mapping):
446452
yield BIN_NONE + key + BIN_NONE
447453
for chunk in _binary_dump_gen(value, level+1, alt_format=alt_format):
448454
yield chunk

0 commit comments

Comments
 (0)