~bzr-pqm/bzr/bzr.dev

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# Copyright (C) 2004, 2005 by Canonical Ltd

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


from bzrlib.selftest import TestCaseInTempDir

def test_transport(tester, t, readonly=False):
    """Test a transport object. Basically, it assumes that the
    Transport object is connected to the current working directory.
    So that whatever is done through the transport, should show
    up in the working directory, and vice-versa.

    This also tests to make sure that the functions work with both
    generators and lists (assuming iter(list) is effectively a generator)
    """
    import tempfile, os
    from bzrlib.transport.local import LocalTransport

    # Test has
    files = ['a', 'b', 'e', 'g']
    tester.build_tree(files)
    tester.assertEqual(t.has('a'), True)
    tester.assertEqual(t.has('c'), False)
    tester.assertEqual(list(t.has_multi(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])),
            [True, True, False, False, True, False, True, False])
    tester.assertEqual(list(t.has_multi(iter(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']))),
            [True, True, False, False, True, False, True, False])

    # Test get
    tester.assertEqual(t.get('a').read(), open('a').read())
    content_f = t.get_multi(files)
    for path,f in zip(files, content_f):
        tester.assertEqual(open(path).read(), f.read())

    content_f = t.get_multi(iter(files))
    for path,f in zip(files, content_f):
        tester.assertEqual(open(path).read(), f.read())

    tester.assertRaises(NoSuchFile, t.get, 'c')
    try:
        files = list(t.get_multi(['a', 'b', 'c']))
    except NoSuchFile:
        pass
    else:
        tester.fail('Failed to raise NoSuchFile for missing file in get_multi')
    try:
        files = list(t.get_multi(iter(['a', 'b', 'c', 'e'])))
    except NoSuchFile:
        pass
    else:
        tester.fail('Failed to raise NoSuchFile for missing file in get_multi')

    # Test put
    if readonly:
        open('c', 'wb').write('some text for c\n')
    else:
        t.put('c', 'some text for c\n')
    tester.assert_(os.path.exists('c'))
    tester.assertEqual(open('c').read(), 'some text for c\n')
    tester.assertEqual(t.get('c').read(), 'some text for c\n')
    # Make sure 'has' is updated
    tester.assertEqual(list(t.has_multi(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])),
            [True, True, True, False, True, False, True, False])
    if readonly:
        open('a', 'wb').write('new\ncontents for\na\n')
        open('d', 'wb').write('contents\nfor d\n')
    else:
        # Put also replaces contents
        tester.assertEqual(t.put_multi([('a', 'new\ncontents for\na\n'),
                                      ('d', 'contents\nfor d\n')]),
                         2)
    tester.assertEqual(list(t.has_multi(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])),
            [True, True, True, True, True, False, True, False])
    tester.assertEqual(open('a').read(), 'new\ncontents for\na\n')
    tester.assertEqual(open('d').read(), 'contents\nfor d\n')

    if readonly:
        open('a', 'wb').write('diff\ncontents for\na\n')
        open('d', 'wb').write('another contents\nfor d\n')
    else:
        tester.assertEqual(
            t.put_multi(iter([('a', 'diff\ncontents for\na\n'),
                              ('d', 'another contents\nfor d\n')]))
                         , 2)
    tester.assertEqual(open('a').read(), 'diff\ncontents for\na\n')
    tester.assertEqual(open('d').read(), 'another contents\nfor d\n')

    if not readonly:
        tester.assertRaises(NoSuchFile, t.put, 'path/doesnt/exist/c', 'contents')

    # Test mkdir
    os.mkdir('dir_a')
    tester.assertEqual(t.has('dir_a'), True)
    tester.assertEqual(t.has('dir_b'), False)

    if readonly:
        os.mkdir('dir_b')
    else:
        t.mkdir('dir_b')
    tester.assertEqual(t.has('dir_b'), True)
    tester.assert_(os.path.isdir('dir_b'))

    if readonly:
        os.mkdir('dir_c')
        os.mkdir('dir_d')
    else:
        t.mkdir_multi(['dir_c', 'dir_d'])
    tester.assertEqual(list(t.has_multi(['dir_a', 'dir_b', 'dir_c', 'dir_d', 'dir_e', 'dir_b'])),
            [True, True, True, True, False, True])
    for d in ['dir_a', 'dir_b', 'dir_c', 'dir_d']:
        tester.assert_(os.path.isdir(d))

    if not readonly:
        tester.assertRaises(NoSuchFile, t.mkdir, 'path/doesnt/exist')
        tester.assertRaises(FileExists, t.mkdir, 'dir_a') # Creating a directory again should fail

    # Make sure the transport recognizes when a
    # directory is created by other means
    # Caching Transports will fail, because dir_e was already seen not
    # to exist. So instead, we will search for a new directory
    #os.mkdir('dir_e')
    #if not readonly:
    #    tester.assertRaises(FileExists, t.mkdir, 'dir_e')

    os.mkdir('dir_f')
    if not readonly:
        tester.assertRaises(FileExists, t.mkdir, 'dir_f')

    # Test get/put in sub-directories
    if readonly:
        open('dir_a/a', 'wb').write('contents of dir_a/a')
        open('dir_b/b', 'wb').write('contents of dir_b/b')
    else:
        tester.assertEqual(
            t.put_multi([('dir_a/a', 'contents of dir_a/a'),
                         ('dir_b/b', 'contents of dir_b/b')])
                      , 2)
    for f in ('dir_a/a', 'dir_b/b'):
        tester.assertEqual(t.get(f).read(), open(f).read())

    # Test copy_to
    dtmp = tempfile.mkdtemp(dir='.', prefix='test-transport-')
    dtmp_base = os.path.basename(dtmp)
    local_t = LocalTransport(dtmp)

    files = ['a', 'b', 'c', 'd']
    t.copy_to(files, local_t)
    for f in files:
        tester.assertEquals(open(f).read(), open(os.path.join(dtmp_base, f)).read())

    # TODO: Test append
    # TODO: Make sure all entries support file-like objects as well as strings.

class LocalTransportTest(TestCaseInTempDir):
    def test_local_transport(self):
        from bzrlib.transport.local import LocalTransport

        t = LocalTransport('.')
        test_transport(self, t)

class HttpServer(object):
    """This just encapsulates spawning and stopping
    an httpserver.
    """
    def __init__(self):
        """This just spawns a separate process to serve files from
        this directory. Call the .stop() function to kill the
        process.
        """
        from BaseHTTPServer import HTTPServer
        from SimpleHTTPServer import SimpleHTTPRequestHandler
        import os
        if hasattr(os, 'fork'):
            self.pid = os.fork()
            if self.pid != 0:
                return
        else: # How do we handle windows, which doesn't have fork?
            raise NotImplementedError('At present HttpServer cannot fork on Windows')

            # We might be able to do something like os.spawn() for the
            # python executable, and give it a simple script to run.
            # but then how do we kill it?

        try:
            self.s = HTTPServer(('', 9999), SimpleHTTPRequestHandler)
            # TODO: Is there something nicer than killing the server when done?
            self.s.serve_forever()
        except KeyboardInterrupt:
            pass
        os._exit(0)

    def stop(self):
        import os
        if self.pid is None:
            return
        if hasattr(os, 'kill'):
            import signal
            os.kill(self.pid, signal.SIGINT)
            os.waitpid(self.pid, 0)
            self.pid = None
        else:
            raise NotImplementedError('At present HttpServer cannot stop on Windows')

class HttpTransportTest(TestCaseInTempDir):
    def test_http_transport(self):
        from bzrlib.transport.http import HttpTransport

        s = HttpServer()

        t = HttpTransport('http://localhost:9999/')
        test_transport(self, t, readonly=True)

        s.stop()