~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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# Copyright (C) 2005-2010 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

from StringIO import StringIO

import bzrlib
from bzrlib import (
    errors,
    lockdir,
    osutils,
    transport,
    )
from bzrlib.errors import BzrBadParameterNotString, NoSuchFile, ReadOnlyError
from bzrlib.lockable_files import LockableFiles, TransportLock
from bzrlib.symbol_versioning import (
    deprecated_in,
    )
from bzrlib.tests import (
    TestCaseInTempDir,
    TestNotApplicable,
    )
from bzrlib.tests.test_smart import TestCaseWithSmartMedium
from bzrlib.tests.test_transactions import DummyWeave
from bzrlib.transactions import (PassThroughTransaction,
                                 ReadOnlyTransaction,
                                 WriteTransaction,
                                 )


# these tests are applied in each parameterized suite for LockableFiles
#
# they use an old style of parameterization, but we want to remove this class
# so won't modernize them now. - mbp 20080430
class _TestLockableFiles_mixin(object):

    def test_transactions(self):
        self.assertIs(self.lockable.get_transaction().__class__,
                      PassThroughTransaction)
        self.lockable.lock_read()
        try:
            self.assertIs(self.lockable.get_transaction().__class__,
                          ReadOnlyTransaction)
        finally:
            self.lockable.unlock()
        self.assertIs(self.lockable.get_transaction().__class__,
                      PassThroughTransaction)
        self.lockable.lock_write()
        self.assertIs(self.lockable.get_transaction().__class__,
                      WriteTransaction)
        # check that finish is called:
        vf = DummyWeave('a')
        self.lockable.get_transaction().register_dirty(vf)
        self.lockable.unlock()
        self.assertTrue(vf.finished)

    def test__escape(self):
        self.assertEqual('%25', self.lockable._escape('%'))

    def test__escape_empty(self):
        self.assertEqual('', self.lockable._escape(''))

    def test_break_lock(self):
        # some locks are not breakable
        self.lockable.lock_write()
        try:
            self.assertRaises(AssertionError, self.lockable.break_lock)
        except NotImplementedError:
            # this lock cannot be broken
            self.lockable.unlock()
            raise TestNotApplicable("%r is not breakable" % (self.lockable,))
        l2 = self.get_lockable()
        orig_factory = bzrlib.ui.ui_factory
        # silent ui - no need for stdout
        bzrlib.ui.ui_factory = bzrlib.ui.CannedInputUIFactory([True])
        try:
            l2.break_lock()
        finally:
            bzrlib.ui.ui_factory = orig_factory
        try:
            l2.lock_write()
            l2.unlock()
        finally:
            self.assertRaises(errors.LockBroken, self.lockable.unlock)
            self.assertFalse(self.lockable.is_locked())

    def test_lock_write_returns_None_refuses_token(self):
        token = self.lockable.lock_write()
        self.addCleanup(self.lockable.unlock)
        if token is not None:
            # This test does not apply, because this lockable supports
            # tokens.
            raise TestNotApplicable("%r uses tokens" % (self.lockable,))
        self.assertRaises(errors.TokenLockingNotSupported,
                          self.lockable.lock_write, token='token')

    def test_lock_write_returns_token_when_given_token(self):
        token = self.lockable.lock_write()
        self.addCleanup(self.lockable.unlock)
        if token is None:
            # This test does not apply, because this lockable refuses
            # tokens.
            return
        new_lockable = self.get_lockable()
        token_from_new_lockable = new_lockable.lock_write(token=token)
        self.addCleanup(new_lockable.unlock)
        self.assertEqual(token, token_from_new_lockable)

    def test_lock_write_raises_on_token_mismatch(self):
        token = self.lockable.lock_write()
        self.addCleanup(self.lockable.unlock)
        if token is None:
            # This test does not apply, because this lockable refuses
            # tokens.
            return
        different_token = token + 'xxx'
        # Re-using the same lockable instance with a different token will
        # raise TokenMismatch.
        self.assertRaises(errors.TokenMismatch,
                          self.lockable.lock_write, token=different_token)
        # A separate instance for the same lockable will also raise
        # TokenMismatch.
        # This detects the case where a caller claims to have a lock (via
        # the token) for an external resource, but doesn't (the token is
        # different).  Clients need a separate lock object to make sure the
        # external resource is probed, whereas the existing lock object
        # might cache.
        new_lockable = self.get_lockable()
        self.assertRaises(errors.TokenMismatch,
                          new_lockable.lock_write, token=different_token)

    def test_lock_write_with_matching_token(self):
        # If the token matches, so no exception is raised by lock_write.
        token = self.lockable.lock_write()
        self.addCleanup(self.lockable.unlock)
        if token is None:
            # This test does not apply, because this lockable refuses
            # tokens.
            return
        # The same instance will accept a second lock_write if the specified
        # token matches.
        self.lockable.lock_write(token=token)
        self.lockable.unlock()
        # Calling lock_write on a new instance for the same lockable will
        # also succeed.
        new_lockable = self.get_lockable()
        new_lockable.lock_write(token=token)
        new_lockable.unlock()

    def test_unlock_after_lock_write_with_token(self):
        # If lock_write did not physically acquire the lock (because it was
        # passed a token), then unlock should not physically release it.
        token = self.lockable.lock_write()
        self.addCleanup(self.lockable.unlock)
        if token is None:
            # This test does not apply, because this lockable refuses
            # tokens.
            return
        new_lockable = self.get_lockable()
        new_lockable.lock_write(token=token)
        new_lockable.unlock()
        self.assertTrue(self.lockable.get_physical_lock_status())

    def test_lock_write_with_token_fails_when_unlocked(self):
        # Lock and unlock to get a superficially valid token.  This mimics a
        # likely programming error, where a caller accidentally tries to lock
        # with a token that is no longer valid (because the original lock was
        # released).
        token = self.lockable.lock_write()
        self.lockable.unlock()
        if token is None:
            # This test does not apply, because this lockable refuses
            # tokens.
            return

        self.assertRaises(errors.TokenMismatch,
                          self.lockable.lock_write, token=token)

    def test_lock_write_reenter_with_token(self):
        token = self.lockable.lock_write()
        try:
            if token is None:
                # This test does not apply, because this lockable refuses
                # tokens.
                return
            # Relock with a token.
            token_from_reentry = self.lockable.lock_write(token=token)
            try:
                self.assertEqual(token, token_from_reentry)
            finally:
                self.lockable.unlock()
        finally:
            self.lockable.unlock()
        # The lock should be unlocked on disk.  Verify that with a new lock
        # instance.
        new_lockable = self.get_lockable()
        # Calling lock_write now should work, rather than raise LockContention.
        new_lockable.lock_write()
        new_lockable.unlock()

    def test_second_lock_write_returns_same_token(self):
        first_token = self.lockable.lock_write()
        try:
            if first_token is None:
                # This test does not apply, because this lockable refuses
                # tokens.
                return
            # Relock the already locked lockable.  It should return the same
            # token.
            second_token = self.lockable.lock_write()
            try:
                self.assertEqual(first_token, second_token)
            finally:
                self.lockable.unlock()
        finally:
            self.lockable.unlock()

    def test_leave_in_place(self):
        token = self.lockable.lock_write()
        try:
            if token is None:
                # This test does not apply, because this lockable refuses
                # tokens.
                return
            self.lockable.leave_in_place()
        finally:
            self.lockable.unlock()
        # At this point, the lock is still in place on disk
        self.assertRaises(errors.LockContention, self.lockable.lock_write)
        # But should be relockable with a token.
        self.lockable.lock_write(token=token)
        self.lockable.unlock()
        # Cleanup: we should still be able to get the lock, but we restore the
        # behavior to clearing the lock when unlocking.
        self.lockable.lock_write(token=token)
        self.lockable.dont_leave_in_place()
        self.lockable.unlock()

    def test_dont_leave_in_place(self):
        token = self.lockable.lock_write()
        try:
            if token is None:
                # This test does not apply, because this lockable refuses
                # tokens.
                return
            self.lockable.leave_in_place()
        finally:
            self.lockable.unlock()
        # At this point, the lock is still in place on disk.
        # Acquire the existing lock with the token, and ask that it is removed
        # when this object unlocks, and unlock to trigger that removal.
        new_lockable = self.get_lockable()
        new_lockable.lock_write(token=token)
        new_lockable.dont_leave_in_place()
        new_lockable.unlock()
        # At this point, the lock is no longer on disk, so we can lock it.
        third_lockable = self.get_lockable()
        third_lockable.lock_write()
        third_lockable.unlock()


# This method of adapting tests to parameters is different to
# the TestProviderAdapters used elsewhere, but seems simpler for this
# case.
class TestLockableFiles_TransportLock(TestCaseInTempDir,
                                      _TestLockableFiles_mixin):

    def setUp(self):
        TestCaseInTempDir.setUp(self)
        t = transport.get_transport('.')
        t.mkdir('.bzr')
        self.sub_transport = t.clone('.bzr')
        self.lockable = self.get_lockable()
        self.lockable.create_lock()

    def stop_server(self):
        super(TestLockableFiles_TransportLock, self).stop_server()
        # free the subtransport so that we do not get a 5 second
        # timeout due to the SFTP connection cache.
        try:
            del self.sub_transport
        except AttributeError:
            pass

    def get_lockable(self):
        return LockableFiles(self.sub_transport, 'my-lock', TransportLock)


class TestLockableFiles_LockDir(TestCaseInTempDir,
                              _TestLockableFiles_mixin):
    """LockableFile tests run with LockDir underneath"""

    def setUp(self):
        TestCaseInTempDir.setUp(self)
        self.transport = transport.get_transport('.')
        self.lockable = self.get_lockable()
        # the lock creation here sets mode - test_permissions on branch
        # tests that implicitly, but it might be a good idea to factor
        # out the mode checking logic and have it applied to loackable files
        # directly. RBC 20060418
        self.lockable.create_lock()

    def get_lockable(self):
        return LockableFiles(self.transport, 'my-lock', lockdir.LockDir)

    def test_lock_created(self):
        self.assertTrue(self.transport.has('my-lock'))
        self.lockable.lock_write()
        self.assertTrue(self.transport.has('my-lock/held/info'))
        self.lockable.unlock()
        self.assertFalse(self.transport.has('my-lock/held/info'))
        self.assertTrue(self.transport.has('my-lock'))

    def test__file_modes(self):
        self.transport.mkdir('readonly')
        osutils.make_readonly('readonly')
        lockable = LockableFiles(self.transport.clone('readonly'), 'test-lock',
                                 lockdir.LockDir)
        # The directory mode should be read-write-execute for the current user
        self.assertEqual(00700, lockable._dir_mode & 00700)
        # Files should be read-write for the current user
        self.assertEqual(00600, lockable._file_mode & 00700)


class TestLockableFiles_RemoteLockDir(TestCaseWithSmartMedium,
                              _TestLockableFiles_mixin):
    """LockableFile tests run with RemoteLockDir on a branch."""

    def setUp(self):
        TestCaseWithSmartMedium.setUp(self)
        # can only get a RemoteLockDir with some RemoteObject...
        # use a branch as thats what we want. These mixin tests test the end
        # to end behaviour, so stubbing out the backend and simulating would
        # defeat the purpose. We test the protocol implementation separately
        # in test_remote and test_smart as usual.
        b = self.make_branch('foo')
        self.addCleanup(b.bzrdir.transport.disconnect)
        self.transport = transport.get_transport('.')
        self.lockable = self.get_lockable()

    def get_lockable(self):
        # getting a new lockable involves opening a new instance of the branch
        branch = bzrlib.branch.Branch.open(self.get_url('foo'))
        self.addCleanup(branch.bzrdir.transport.disconnect)
        return branch.control_files