Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
36 kaklik 1
# Written by Bram Cohen
2
# see LICENSE.txt for license information
3
 
4
from string import join
5
 
6
class FakeHandle:
7
    def __init__(self, name, fakeopen):
8
        self.name = name
9
        self.fakeopen = fakeopen
10
        self.pos = 0
11
 
12
    def flush(self):
13
        pass
14
 
15
    def close(self):
16
        pass
17
 
18
    def seek(self, pos):
19
        self.pos = pos
20
 
21
    def read(self, amount = None):
22
        old = self.pos
23
        f = self.fakeopen.files[self.name]
24
        if self.pos >= len(f):
25
            return ''
26
        if amount is None:
27
            self.pos = len(f)
28
            return join(f[old:], '')
29
        else:
30
            self.pos = min(len(f), old + amount)
31
            return join(f[old:self.pos], '')
32
 
33
    def write(self, s):
34
        f = self.fakeopen.files[self.name]
35
        while len(f) < self.pos:
36
            f.append(chr(0))
37
        self.fakeopen.files[self.name][self.pos : self.pos + len(s)] = list(s)
38
        self.pos += len(s)
39
 
40
class FakeOpen:
41
    def __init__(self, initial = {}):
42
        self.files = {}
43
        for key, value in initial.items():
44
            self.files[key] = list(value)
45
 
46
    def open(self, filename, mode):
47
        """currently treats everything as rw - doesn't support append"""
48
        self.files.setdefault(filename, [])
49
        return FakeHandle(filename, self)
50
 
51
    def exists(self, file):
52
        return self.files.has_key(file)
53
 
54
    def getsize(self, file):
55
        return len(self.files[file])
56
 
57
def test_normal():
58
    f = FakeOpen({'f1': 'abcde'})
59
    assert f.exists('f1')
60
    assert not f.exists('f2')
61
    assert f.getsize('f1') == 5
62
    h = f.open('f1', 'rw')
63
    assert h.read(3) == 'abc'
64
    assert h.read(1) == 'd'
65
    assert h.read() == 'e'
66
    assert h.read(2) == ''
67
    h.write('fpq')
68
    h.seek(4)
69
    assert h.read(2) == 'ef'
70
    h.write('ghij')
71
    h.seek(0)
72
    assert h.read() == 'abcdefghij'
73
    h.seek(2)
74
    h.write('p')
75
    h.write('q')
76
    assert h.read(1) == 'e'
77
    h.seek(1)
78
    assert h.read(5) == 'bpqef'
79
 
80
    h2 = f.open('f2', 'rw')
81
    assert h2.read() == ''
82
    h2.write('mnop')
83
    h2.seek(1)
84
    assert h2.read() == 'nop'
85
 
86
    assert f.exists('f1')
87
    assert f.exists('f2')
88
    assert f.getsize('f1') == 10
89
    assert f.getsize('f2') == 4