1
2from __future__ import absolute_import
3from io import BytesIO
4
5from wvtest import *
6
7from bup import vint
8from buptest import no_lingering_errors
9
10
11def encode_and_decode_vuint(x):
12    f = BytesIO()
13    vint.write_vuint(f, x)
14    return vint.read_vuint(BytesIO(f.getvalue()))
15
16
17@wvtest
18def test_vuint():
19    with no_lingering_errors():
20        for x in (0, 1, 42, 128, 10**16):
21            WVPASSEQ(encode_and_decode_vuint(x), x)
22        WVEXCEPT(Exception, vint.write_vuint, BytesIO(), -1)
23        WVEXCEPT(EOFError, vint.read_vuint, BytesIO())
24
25
26def encode_and_decode_vint(x):
27    f = BytesIO()
28    vint.write_vint(f, x)
29    return vint.read_vint(BytesIO(f.getvalue()))
30
31
32@wvtest
33def test_vint():
34    with no_lingering_errors():
35        values = (0, 1, 42, 64, 10**16)
36        for x in values:
37            WVPASSEQ(encode_and_decode_vint(x), x)
38        for x in [-x for x in values]:
39            WVPASSEQ(encode_and_decode_vint(x), x)
40        WVEXCEPT(EOFError, vint.read_vint, BytesIO())
41        WVEXCEPT(EOFError, vint.read_vint, BytesIO(b"\x80\x80"))
42
43
44def encode_and_decode_bvec(x):
45    f = BytesIO()
46    vint.write_bvec(f, x)
47    return vint.read_bvec(BytesIO(f.getvalue()))
48
49
50@wvtest
51def test_bvec():
52    with no_lingering_errors():
53        values = (b'', b'x', b'foo', b'\0', b'\0foo', b'foo\0bar\0')
54        for x in values:
55            WVPASSEQ(encode_and_decode_bvec(x), x)
56        WVEXCEPT(EOFError, vint.read_bvec, BytesIO())
57        outf = BytesIO()
58        for x in (b'foo', b'bar', b'baz', b'bax'):
59            vint.write_bvec(outf, x)
60        inf = BytesIO(outf.getvalue())
61        WVPASSEQ(vint.read_bvec(inf), b'foo')
62        WVPASSEQ(vint.read_bvec(inf), b'bar')
63        vint.skip_bvec(inf)
64        WVPASSEQ(vint.read_bvec(inf), b'bax')
65
66
67def pack_and_unpack(types, *values):
68    data = vint.pack(types, *values)
69    return vint.unpack(types, data)
70
71
72@wvtest
73def test_pack_and_unpack():
74    with no_lingering_errors():
75        tests = [('', []),
76                 ('s', [b'foo']),
77                 ('ss', [b'foo', b'bar']),
78                 ('sV', [b'foo', 0]),
79                 ('sv', [b'foo', -1]),
80                 ('V', [0]),
81                 ('Vs', [0, b'foo']),
82                 ('VV', [0, 1]),
83                 ('Vv', [0, -1]),
84                 ('v', [0]),
85                 ('vs', [0, b'foo']),
86                 ('vV', [0, 1]),
87                 ('vv', [0, -1])]
88        for test in tests:
89            (types, values) = test
90            WVPASSEQ(pack_and_unpack(types, *values), values)
91        WVEXCEPT(Exception, vint.pack, 's')
92        WVEXCEPT(Exception, vint.pack, 's', 'foo', 'bar')
93        WVEXCEPT(Exception, vint.pack, 'x', 1)
94        WVEXCEPT(Exception, vint.unpack, 's', '')
95        WVEXCEPT(Exception, vint.unpack, 'x', '')
96