summaryrefslogtreecommitdiff
path: root/tests/basics/io_buffered_writer.py
blob: 60cf2c837d10f11c737582a41bc7782dea902d13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import io

try:
    io.BytesIO
    io.BufferedWriter
except AttributeError:
    print('SKIP')
    raise SystemExit

bts = io.BytesIO()
buf = io.BufferedWriter(bts, 8)

buf.write(b"foobar")
print(bts.getvalue())
buf.write(b"foobar")
# CPython has different flushing policy, so value below is different
print(bts.getvalue())
buf.flush()
print(bts.getvalue())
buf.flush()
print(bts.getvalue())

# special case when alloc is a factor of total buffer length
bts = io.BytesIO()
buf = io.BufferedWriter(bts, 1)
buf.write(b"foo")
print(bts.getvalue())

# hashing a BufferedWriter
print(type(hash(buf)))

# Test failing flush()
class MyIO(io.IOBase):
    def __init__(self):
        self.count = 0

    def write(self, buf):
        self.count += 1
        if self.count < 3:
            return None
        print("writing", buf)
        return len(buf)


buf = io.BufferedWriter(MyIO(), 8)

buf.write(b"foobar")

for _ in range(4):
    try:
        buf.flush()
        print("flushed")
    except OSError:
        print("OSError")