/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.15 by John Arbash Meinel
Merge bzr.dev 5597 to resolve NEWS, aka bzr-2.3.txt
1
# Copyright (C) 2006-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1553.5.12 by Martin Pool
New LockDir locking mechanism
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1553.5.12 by Martin Pool
New LockDir locking mechanism
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1553.5.12 by Martin Pool
New LockDir locking mechanism
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1553.5.12 by Martin Pool
New LockDir locking mechanism
16
17
"""Tests for LockDir"""
18
1551.10.3 by Aaron Bentley
Lock attempts don't treat permission problems as lock contention
19
import os
1553.5.12 by Martin Pool
New LockDir locking mechanism
20
import time
21
1687.1.5 by Robert Collins
Add break_lock utility function to LockDir.
22
import bzrlib
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
23
from bzrlib import (
2055.2.1 by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email
24
    config,
1551.10.3 by Aaron Bentley
Lock attempts don't treat permission problems as lock contention
25
    errors,
3331.3.13 by Martin Pool
Fix up imports
26
    lock,
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
27
    osutils,
1551.10.4 by Aaron Bentley
Update to skip on win32
28
    tests,
2555.3.9 by Martin Pool
Add test and fix for locking robustly when rename of directories doesn't act as a mutex (thank John)
29
    transport,
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
30
    )
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
31
from bzrlib.errors import (
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
32
    LockBreakMismatch,
33
    LockBroken,
34
    LockContention,
35
    LockFailed,
36
    LockNotHeld,
37
    )
2381.1.4 by Robert Collins
Unbreak lockdir tests after adding fast lockdir timeouts to the test suite default environment.
38
from bzrlib.lockdir import LockDir
5579.3.1 by Jelmer Vernooij
Remove unused imports.
39
from bzrlib.tests import (
40
    features,
41
    TestCaseWithTransport,
42
    )
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
43
from bzrlib.trace import note
1553.5.12 by Martin Pool
New LockDir locking mechanism
44
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
45
# These tests are run on the default transport provided by the test framework
46
# (typically a local disk transport).  That can be changed by the --transport
47
# option to bzr selftest.  The required properties of the transport
48
# implementation are tested separately.  (The main requirement is just that
49
# they don't allow overwriting nonempty directories.)
50
1553.5.12 by Martin Pool
New LockDir locking mechanism
51
class TestLockDir(TestCaseWithTransport):
52
    """Test LockDir operations"""
53
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
54
    def logging_report_function(self, fmt, *args):
55
        self._logged_reports.append((fmt, args))
56
57
    def setup_log_reporter(self, lock_dir):
58
        self._logged_reports = []
59
        lock_dir._report_function = self.logging_report_function
60
1553.5.12 by Martin Pool
New LockDir locking mechanism
61
    def test_00_lock_creation(self):
62
        """Creation of lock file on a transport"""
63
        t = self.get_transport()
64
        lf = LockDir(t, 'test_lock')
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
65
        self.assertFalse(lf.is_held)
1553.5.12 by Martin Pool
New LockDir locking mechanism
66
67
    def test_01_lock_repr(self):
68
        """Lock string representation"""
69
        lf = LockDir(self.get_transport(), 'test_lock')
70
        r = repr(lf)
71
        self.assertContainsRe(r, r'^LockDir\(.*/test_lock\)$')
72
73
    def test_02_unlocked_peek(self):
74
        lf = LockDir(self.get_transport(), 'test_lock')
75
        self.assertEqual(lf.peek(), None)
76
1687.1.3 by Robert Collins
Make LockDir.unlock check the lock is still intact.
77
    def get_lock(self):
78
        return LockDir(self.get_transport(), 'test_lock')
79
80
    def test_unlock_after_break_raises(self):
81
        ld = self.get_lock()
82
        ld2 = self.get_lock()
83
        ld.create()
84
        ld.attempt_lock()
85
        ld2.force_break(ld2.peek())
86
        self.assertRaises(LockBroken, ld.unlock)
87
1553.5.12 by Martin Pool
New LockDir locking mechanism
88
    def test_03_readonly_peek(self):
89
        lf = LockDir(self.get_readonly_transport(), 'test_lock')
90
        self.assertEqual(lf.peek(), None)
91
92
    def test_10_lock_uncontested(self):
93
        """Acquire and release a lock"""
94
        t = self.get_transport()
95
        lf = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
96
        lf.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
97
        lf.attempt_lock()
98
        try:
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
99
            self.assertTrue(lf.is_held)
1553.5.12 by Martin Pool
New LockDir locking mechanism
100
        finally:
101
            lf.unlock()
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
102
            self.assertFalse(lf.is_held)
1553.5.12 by Martin Pool
New LockDir locking mechanism
103
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
104
    def test_11_create_readonly_transport(self):
105
        """Fail to create lock on readonly transport"""
106
        t = self.get_readonly_transport()
107
        lf = LockDir(t, 'test_lock')
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
108
        self.assertRaises(LockFailed, lf.create)
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
109
110
    def test_12_lock_readonly_transport(self):
1553.5.12 by Martin Pool
New LockDir locking mechanism
111
        """Fail to lock on readonly transport"""
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
112
        lf = LockDir(self.get_transport(), 'test_lock')
113
        lf.create()
114
        lf = LockDir(self.get_readonly_transport(), 'test_lock')
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
115
        self.assertRaises(LockFailed, lf.attempt_lock)
1553.5.12 by Martin Pool
New LockDir locking mechanism
116
117
    def test_20_lock_contested(self):
118
        """Contention to get a lock"""
119
        t = self.get_transport()
120
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
121
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
122
        lf1.attempt_lock()
123
        lf2 = LockDir(t, 'test_lock')
124
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
125
            # locking is between LockDir instances; aliases within
1553.5.12 by Martin Pool
New LockDir locking mechanism
126
            # a single process are not detected
127
            lf2.attempt_lock()
128
            self.fail('Failed to detect lock collision')
129
        except LockContention, e:
130
            self.assertEqual(e.lock, lf2)
131
            self.assertContainsRe(str(e),
132
                    r'^Could not acquire.*test_lock.*$')
133
        lf1.unlock()
134
135
    def test_20_lock_peek(self):
136
        """Peek at the state of a lock"""
137
        t = self.get_transport()
138
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
139
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
140
        lf1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
141
        self.addCleanup(lf1.unlock)
1553.5.12 by Martin Pool
New LockDir locking mechanism
142
        # lock is held, should get some info on it
143
        info1 = lf1.peek()
144
        self.assertEqual(set(info1.keys()),
145
                         set(['user', 'nonce', 'hostname', 'pid', 'start_time']))
146
        # should get the same info if we look at it through a different
147
        # instance
148
        info2 = LockDir(t, 'test_lock').peek()
149
        self.assertEqual(info1, info2)
150
        # locks which are never used should be not-held
151
        self.assertEqual(LockDir(t, 'other_lock').peek(), None)
152
153
    def test_21_peek_readonly(self):
154
        """Peek over a readonly transport"""
155
        t = self.get_transport()
156
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
157
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
158
        lf2 = LockDir(self.get_readonly_transport(), 'test_lock')
159
        self.assertEqual(lf2.peek(), None)
160
        lf1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
161
        self.addCleanup(lf1.unlock)
1553.5.12 by Martin Pool
New LockDir locking mechanism
162
        info2 = lf2.peek()
163
        self.assertTrue(info2)
164
        self.assertEqual(info2['nonce'], lf1.nonce)
165
166
    def test_30_lock_wait_fail(self):
167
        """Wait on a lock, then fail
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
168
1553.5.12 by Martin Pool
New LockDir locking mechanism
169
        We ask to wait up to 400ms; this should fail within at most one
170
        second.  (Longer times are more realistic but we don't want the test
171
        suite to take too long, and this should do for now.)
172
        """
173
        t = self.get_transport()
174
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
175
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
176
        lf2 = LockDir(t, 'test_lock')
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
177
        self.setup_log_reporter(lf2)
1553.5.12 by Martin Pool
New LockDir locking mechanism
178
        lf1.attempt_lock()
179
        try:
180
            before = time.time()
181
            self.assertRaises(LockContention, lf2.wait_lock,
182
                              timeout=0.4, poll=0.1)
183
            after = time.time()
1704.2.1 by Martin Pool
Fix time-dependency in LockDir tests -- allow more margin for error in time to detect lock contention
184
            # it should only take about 0.4 seconds, but we allow more time in
185
            # case the machine is heavily loaded
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
186
            self.assertTrue(after - before <= 8.0,
1704.2.1 by Martin Pool
Fix time-dependency in LockDir tests -- allow more margin for error in time to detect lock contention
187
                    "took %f seconds to detect lock contention" % (after - before))
1553.5.12 by Martin Pool
New LockDir locking mechanism
188
        finally:
189
            lf1.unlock()
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
190
        self.assertEqual(1, len(self._logged_reports))
5284.6.3 by Parth Malwankar
fixed tests. closed review comments by mgz.
191
        self.assertEqual(self._logged_reports[0][0],
5284.6.9 by Parth Malwankar
cleaner handling of lock_url display.
192
            '%s lock %s held by %s\n'
5284.6.3 by Parth Malwankar
fixed tests. closed review comments by mgz.
193
            'at %s [process #%s], acquired %s.\n'
194
            'Will continue to try until %s, unless '
195
            'you press Ctrl-C.\n'
196
            'See "bzr help break-lock" for more.')
5284.6.4 by Parth Malwankar
local urls are now shows as they are valid.
197
        start, lock_url, user, hostname, pid, time_ago, deadline_str = \
5284.6.3 by Parth Malwankar
fixed tests. closed review comments by mgz.
198
            self._logged_reports[0][1]
199
        self.assertEqual(start, u'Unable to obtain')
200
        self.assertEqual(user, u'jrandom@example.com')
201
        # skip hostname
202
        self.assertContainsRe(pid, r'\d+')
203
        self.assertContainsRe(time_ago, r'.* ago')
204
        self.assertContainsRe(deadline_str, r'\d{2}:\d{2}:\d{2}')
1553.5.12 by Martin Pool
New LockDir locking mechanism
205
206
    def test_31_lock_wait_easy(self):
207
        """Succeed when waiting on a lock with no contention.
208
        """
209
        t = self.get_transport()
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
210
        lf1 = LockDir(t, 'test_lock')
211
        lf1.create()
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
212
        self.setup_log_reporter(lf1)
1553.5.12 by Martin Pool
New LockDir locking mechanism
213
        try:
214
            before = time.time()
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
215
            lf1.wait_lock(timeout=0.4, poll=0.1)
1553.5.12 by Martin Pool
New LockDir locking mechanism
216
            after = time.time()
217
            self.assertTrue(after - before <= 1.0)
218
        finally:
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
219
            lf1.unlock()
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
220
        self.assertEqual([], self._logged_reports)
1553.5.12 by Martin Pool
New LockDir locking mechanism
221
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
222
    def test_40_confirm_easy(self):
223
        """Confirm a lock that's already held"""
224
        t = self.get_transport()
225
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
226
        lf1.create()
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
227
        lf1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
228
        self.addCleanup(lf1.unlock)
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
229
        lf1.confirm()
230
231
    def test_41_confirm_not_held(self):
232
        """Confirm a lock that's already held"""
233
        t = self.get_transport()
234
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
235
        lf1.create()
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
236
        self.assertRaises(LockNotHeld, lf1.confirm)
1553.5.23 by Martin Pool
Start LockDir.confirm method and LockBroken exception
237
238
    def test_42_confirm_broken_manually(self):
239
        """Confirm a lock broken by hand"""
240
        t = self.get_transport()
241
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
242
        lf1.create()
1553.5.23 by Martin Pool
Start LockDir.confirm method and LockBroken exception
243
        lf1.attempt_lock()
244
        t.move('test_lock', 'lock_gone_now')
245
        self.assertRaises(LockBroken, lf1.confirm)
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
246
        # Clean up
247
        t.move('lock_gone_now', 'test_lock')
248
        lf1.unlock()
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
249
250
    def test_43_break(self):
251
        """Break a lock whose caller has forgotten it"""
252
        t = self.get_transport()
253
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
254
        lf1.create()
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
255
        lf1.attempt_lock()
256
        # we incorrectly discard the lock object without unlocking it
257
        del lf1
258
        # someone else sees it's still locked
259
        lf2 = LockDir(t, 'test_lock')
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
260
        holder_info = lf2.peek()
261
        self.assertTrue(holder_info)
262
        lf2.force_break(holder_info)
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
263
        # now we should be able to take it
264
        lf2.attempt_lock()
4327.1.4 by Vincent Ladeuil
Fix lock test failures by taking lock breaking into account.
265
        self.addCleanup(lf2.unlock)
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
266
        lf2.confirm()
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
267
268
    def test_44_break_already_released(self):
269
        """Lock break races with regular release"""
270
        t = self.get_transport()
271
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
272
        lf1.create()
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
273
        lf1.attempt_lock()
274
        # someone else sees it's still locked
275
        lf2 = LockDir(t, 'test_lock')
276
        holder_info = lf2.peek()
277
        # in the interim the lock is released
278
        lf1.unlock()
279
        # break should succeed
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
280
        lf2.force_break(holder_info)
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
281
        # now we should be able to take it
282
        lf2.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
283
        self.addCleanup(lf2.unlock)
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
284
        lf2.confirm()
285
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
286
    def test_45_break_mismatch(self):
287
        """Lock break races with someone else acquiring it"""
288
        t = self.get_transport()
289
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
290
        lf1.create()
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
291
        lf1.attempt_lock()
292
        # someone else sees it's still locked
293
        lf2 = LockDir(t, 'test_lock')
294
        holder_info = lf2.peek()
295
        # in the interim the lock is released
296
        lf1.unlock()
297
        lf3 = LockDir(t, 'test_lock')
298
        lf3.attempt_lock()
299
        # break should now *fail*
300
        self.assertRaises(LockBreakMismatch, lf2.force_break,
301
                          holder_info)
302
        lf3.unlock()
1553.5.54 by Martin Pool
Add LockDir.read_lock fake method
303
304
    def test_46_fake_read_lock(self):
305
        t = self.get_transport()
306
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
307
        lf1.create()
1553.5.54 by Martin Pool
Add LockDir.read_lock fake method
308
        lf1.lock_read()
309
        lf1.unlock()
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
310
311
    def test_50_lockdir_representation(self):
312
        """Check the on-disk representation of LockDirs is as expected.
313
314
        There should always be a top-level directory named by the lock.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
315
        When the lock is held, there should be a lockname/held directory
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
316
        containing an info file.
317
        """
318
        t = self.get_transport()
319
        lf1 = LockDir(t, 'test_lock')
320
        lf1.create()
321
        self.assertTrue(t.has('test_lock'))
322
        lf1.lock_write()
323
        self.assertTrue(t.has('test_lock/held/info'))
324
        lf1.unlock()
325
        self.assertFalse(t.has('test_lock/held/info'))
1687.1.5 by Robert Collins
Add break_lock utility function to LockDir.
326
327
    def test_break_lock(self):
328
        # the ui based break_lock routine should Just Work (tm)
329
        ld1 = self.get_lock()
330
        ld2 = self.get_lock()
331
        ld1.create()
332
        ld1.lock_write()
1687.1.6 by Robert Collins
Extend LockableFiles to support break_lock() calls.
333
        # do this without IO redirection to ensure it doesn't prompt.
334
        self.assertRaises(AssertionError, ld1.break_lock)
1687.1.5 by Robert Collins
Add break_lock utility function to LockDir.
335
        orig_factory = bzrlib.ui.ui_factory
4449.3.27 by Martin Pool
More test updates to use CannedInputUIFactory
336
        bzrlib.ui.ui_factory = bzrlib.ui.CannedInputUIFactory([True])
1687.1.5 by Robert Collins
Add break_lock utility function to LockDir.
337
        try:
338
            ld2.break_lock()
339
            self.assertRaises(LockBroken, ld1.unlock)
340
        finally:
341
            bzrlib.ui.ui_factory = orig_factory
1955.1.1 by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile.
342
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
343
    def test_break_lock_corrupt_info(self):
344
        """break_lock works even if the info file is corrupt (and tells the UI
345
        that it is corrupt).
346
        """
347
        ld = self.get_lock()
348
        ld2 = self.get_lock()
349
        ld.create()
350
        ld.lock_write()
351
        ld.transport.put_bytes_non_atomic('test_lock/held/info', '\0')
352
        class LoggingUIFactory(bzrlib.ui.SilentUIFactory):
353
            def __init__(self):
354
                self.prompts = []
355
            def get_boolean(self, prompt):
356
                self.prompts.append(('boolean', prompt))
357
                return True
358
        ui = LoggingUIFactory()
5599.2.1 by John Arbash Meinel
Fix breaking corrupt lock files on Windows.
359
        self.overrideAttr(bzrlib.ui, 'ui_factory', ui)
360
        ld2.break_lock()
361
        self.assertLength(1, ui.prompts)
362
        self.assertEqual('boolean', ui.prompts[0][0])
363
        self.assertStartsWith(ui.prompts[0][1], 'Break (corrupt LockDir')
364
        self.assertRaises(LockBroken, ld.unlock)
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
365
366
    def test_break_lock_missing_info(self):
367
        """break_lock works even if the info file is missing (and tells the UI
368
        that it is corrupt).
369
        """
370
        ld = self.get_lock()
371
        ld2 = self.get_lock()
372
        ld.create()
373
        ld.lock_write()
374
        ld.transport.delete('test_lock/held/info')
375
        class LoggingUIFactory(bzrlib.ui.SilentUIFactory):
376
            def __init__(self):
377
                self.prompts = []
378
            def get_boolean(self, prompt):
379
                self.prompts.append(('boolean', prompt))
380
                return True
381
        ui = LoggingUIFactory()
382
        orig_factory = bzrlib.ui.ui_factory
383
        bzrlib.ui.ui_factory = ui
384
        try:
385
            ld2.break_lock()
386
            self.assertRaises(LockBroken, ld.unlock)
387
            self.assertLength(0, ui.prompts)
388
        finally:
389
            bzrlib.ui.ui_factory = orig_factory
390
        # Suppress warnings due to ld not being unlocked
391
        # XXX: if lock_broken hook was invoked in this case, this hack would
392
        # not be necessary.  - Andrew Bennetts, 2010-09-06.
393
        del self._lock_actions[:]
394
1955.1.1 by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile.
395
    def test_create_missing_base_directory(self):
396
        """If LockDir.path doesn't exist, it can be created
397
398
        Some people manually remove the entire lock/ directory trying
399
        to unlock a stuck repository/branch/etc. Rather than failing
400
        after that, just create the lock directory when needed.
401
        """
402
        t = self.get_transport()
403
        lf1 = LockDir(t, 'test_lock')
404
405
        lf1.create()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
406
        self.assertTrue(t.has('test_lock'))
1955.1.1 by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile.
407
408
        t.rmdir('test_lock')
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
409
        self.assertFalse(t.has('test_lock'))
1955.1.1 by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile.
410
411
        # This will create 'test_lock' if it needs to
412
        lf1.lock_write()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
413
        self.assertTrue(t.has('test_lock'))
414
        self.assertTrue(t.has('test_lock/held/info'))
1955.1.1 by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile.
415
416
        lf1.unlock()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
417
        self.assertFalse(t.has('test_lock/held/info'))
1957.1.6 by John Arbash Meinel
[merge] bzr.dev 2009
418
1957.1.5 by John Arbash Meinel
Create a helper function for formatting lock information
419
    def test__format_lock_info(self):
420
        ld1 = self.get_lock()
421
        ld1.create()
422
        ld1.lock_write()
423
        try:
424
            info_list = ld1._format_lock_info(ld1.peek())
425
        finally:
426
            ld1.unlock()
5284.6.3 by Parth Malwankar
fixed tests. closed review comments by mgz.
427
        self.assertEqual(info_list[0], u'jrandom@example.com')
428
        # info_list[1] is hostname. we skip this.
429
        self.assertContainsRe(info_list[2], '^\d+$') # pid
430
        self.assertContainsRe(info_list[3], r'^\d+ seconds? ago$') # time_ago
2055.2.1 by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email
431
432
    def test_lock_without_email(self):
433
        global_config = config.GlobalConfig()
434
        # Intentionally has no email address
435
        global_config.set_user_option('email', 'User Identity')
436
        ld1 = self.get_lock()
437
        ld1.create()
438
        ld1.lock_write()
439
        ld1.unlock()
1551.10.3 by Aaron Bentley
Lock attempts don't treat permission problems as lock contention
440
441
    def test_lock_permission(self):
4797.70.1 by Vincent Ladeuil
Skip chmodbits dependent tests when running as root
442
        self.requireFeature(features.not_running_as_root)
1551.10.4 by Aaron Bentley
Update to skip on win32
443
        if not osutils.supports_posix_readonly():
3107.2.2 by John Arbash Meinel
feedback from Martin.
444
            raise tests.TestSkipped('Cannot induce a permission failure')
1551.10.3 by Aaron Bentley
Lock attempts don't treat permission problems as lock contention
445
        ld1 = self.get_lock()
446
        lock_path = ld1.transport.local_abspath('test_lock')
447
        os.mkdir(lock_path)
448
        osutils.make_readonly(lock_path)
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
449
        self.assertRaises(errors.LockFailed, ld1.attempt_lock)
2555.3.5 by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek()
450
451
    def test_lock_by_token(self):
452
        ld1 = self.get_lock()
453
        token = ld1.lock_write()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
454
        self.addCleanup(ld1.unlock)
2555.3.5 by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek()
455
        self.assertNotEqual(None, token)
456
        ld2 = self.get_lock()
457
        t2 = ld2.lock_write(token)
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
458
        self.addCleanup(ld2.unlock)
2555.3.5 by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek()
459
        self.assertEqual(token, t2)
2555.3.9 by Martin Pool
Add test and fix for locking robustly when rename of directories doesn't act as a mutex (thank John)
460
461
    def test_lock_with_buggy_rename(self):
462
        # test that lock acquisition handles servers which pretend they
463
        # renamed correctly but that actually fail
464
        t = transport.get_transport('brokenrename+' + self.get_url())
465
        ld1 = LockDir(t, 'test_lock')
466
        ld1.create()
467
        ld1.attempt_lock()
468
        ld2 = LockDir(t, 'test_lock')
2555.3.14 by Martin Pool
Better handling in LockDir of rename that moves one directory within another
469
        # we should fail to lock
470
        e = self.assertRaises(errors.LockContention, ld2.attempt_lock)
471
        # now the original caller should succeed in unlocking
472
        ld1.unlock()
473
        # and there should be nothing left over
474
        self.assertEquals([], t.list_dir('test_lock'))
2555.3.12 by Martin Pool
Add test for https://bugs.launchpad.net/bzr/+bug/109169 -- test_failed_lock_leaves_no_trash
475
476
    def test_failed_lock_leaves_no_trash(self):
477
        # if we fail to acquire the lock, we don't leave pending directories
478
        # behind -- https://bugs.launchpad.net/bzr/+bug/109169
479
        ld1 = self.get_lock()
480
        ld2 = self.get_lock()
481
        # should be nothing before we start
482
        ld1.create()
483
        t = self.get_transport().clone('test_lock')
484
        def check_dir(a):
485
            self.assertEquals(a, t.list_dir('.'))
486
        check_dir([])
487
        # when held, that's all we see
488
        ld1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
489
        self.addCleanup(ld1.unlock)
2555.3.12 by Martin Pool
Add test for https://bugs.launchpad.net/bzr/+bug/109169 -- test_failed_lock_leaves_no_trash
490
        check_dir(['held'])
491
        # second guy should fail
492
        self.assertRaises(errors.LockContention, ld2.attempt_lock)
493
        # no kibble
494
        check_dir(['held'])
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
495
4634.138.1 by Martin Pool
Add failing test for \#185103
496
    def test_no_lockdir_info(self):
497
        """We can cope with empty info files."""
498
        # This seems like a fairly common failure case - see
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
499
        # <https://bugs.launchpad.net/bzr/+bug/185103> and all its dupes.
4634.138.1 by Martin Pool
Add failing test for \#185103
500
        # Processes are often interrupted after opening the file
501
        # before the actual contents are committed.
502
        t = self.get_transport()
503
        t.mkdir('test_lock')
504
        t.mkdir('test_lock/held')
505
        t.put_bytes('test_lock/held/info', '')
506
        lf = LockDir(t, 'test_lock')
4634.138.2 by Martin Pool
Copy with lock info file being empty
507
        info = lf.peek()
508
        formatted_info = lf._format_lock_info(info)
509
        self.assertEquals(
5284.6.3 by Parth Malwankar
fixed tests. closed review comments by mgz.
510
            ['<unknown>', '<unknown>', '<unknown>', '(unknown)'],
4634.138.2 by Martin Pool
Copy with lock info file being empty
511
            formatted_info)
4634.138.1 by Martin Pool
Add failing test for \#185103
512
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
513
    def test_corrupt_lockdir_info(self):
514
        """We can cope with corrupt (and thus unparseable) info files."""
515
        # This seems like a fairly common failure case too - see
4634.165.4 by Vincent Ladeuil
Fix all comments where bugs.edge.launchpad.net was used.
516
        # <https://bugs.launchpad.net/bzr/+bug/619872> for instance.
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
517
        # In particular some systems tend to fill recently created files with
518
        # nul bytes after recovering from a system crash.
519
        t = self.get_transport()
520
        t.mkdir('test_lock')
521
        t.mkdir('test_lock/held')
522
        t.put_bytes('test_lock/held/info', '\0')
523
        lf = LockDir(t, 'test_lock')
524
        self.assertRaises(errors.LockCorrupt, lf.peek)
525
        # Currently attempt_lock gives LockContention, but LockCorrupt would be
526
        # a reasonable result too.
527
        self.assertRaises(
528
            (errors.LockCorrupt, errors.LockContention), lf.attempt_lock)
529
        self.assertRaises(errors.LockCorrupt, lf.validate_token, 'fake token')
530
531
    def test_missing_lockdir_info(self):
532
        """We can cope with absent info files."""
533
        t = self.get_transport()
534
        t.mkdir('test_lock')
535
        t.mkdir('test_lock/held')
536
        lf = LockDir(t, 'test_lock')
537
        # In this case we expect the 'not held' result from peek, because peek
538
        # cannot be expected to notice that there is a 'held' directory with no
539
        # 'info' file.
540
        self.assertEqual(None, lf.peek())
541
        # And lock/unlock may work or give LockContention (but not any other
542
        # error).
543
        try:
544
            lf.attempt_lock()
545
        except LockContention:
546
            # LockContention is ok, and expected on Windows
547
            pass
548
        else:
549
            # no error is ok, and expected on POSIX (because POSIX allows
550
            # os.rename over an empty directory).
551
            lf.unlock()
552
        # Currently raises TokenMismatch, but LockCorrupt would be reasonable
553
        # too.
554
        self.assertRaises(
555
            (errors.TokenMismatch, errors.LockCorrupt),
556
            lf.validate_token, 'fake token')
557
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
558
559
class TestLockDirHooks(TestCaseWithTransport):
560
561
    def setUp(self):
562
        super(TestLockDirHooks, self).setUp()
563
        self._calls = []
564
565
    def get_lock(self):
566
        return LockDir(self.get_transport(), 'test_lock')
567
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
568
    def record_hook(self, result):
569
        self._calls.append(result)
570
3331.3.12 by Martin Pool
Remove PhysicalLock class
571
    def test_LockDir_acquired_success(self):
572
        # the LockDir.lock_acquired hook fires when a lock is acquired.
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
573
        LockDir.hooks.install_named_hook('lock_acquired',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
574
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
575
        ld = self.get_lock()
576
        ld.create()
577
        self.assertEqual([], self._calls)
578
        result = ld.attempt_lock()
3331.3.2 by Robert Collins
Polish on lock hooks to be easier to use.
579
        lock_path = ld.transport.abspath(ld.path)
580
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
581
        ld.unlock()
3331.3.2 by Robert Collins
Polish on lock hooks to be easier to use.
582
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
583
3331.3.12 by Martin Pool
Remove PhysicalLock class
584
    def test_LockDir_acquired_fail(self):
585
        # the LockDir.lock_acquired hook does not fire on failure.
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
586
        ld = self.get_lock()
587
        ld.create()
588
        ld2 = self.get_lock()
589
        ld2.attempt_lock()
590
        # install a lock hook now, when the disk lock is locked
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
591
        LockDir.hooks.install_named_hook('lock_acquired',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
592
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
593
        self.assertRaises(errors.LockContention, ld.attempt_lock)
594
        self.assertEqual([], self._calls)
595
        ld2.unlock()
596
        self.assertEqual([], self._calls)
597
3331.3.12 by Martin Pool
Remove PhysicalLock class
598
    def test_LockDir_released_success(self):
599
        # the LockDir.lock_released hook fires when a lock is acquired.
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
600
        LockDir.hooks.install_named_hook('lock_released',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
601
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
602
        ld = self.get_lock()
603
        ld.create()
604
        self.assertEqual([], self._calls)
605
        result = ld.attempt_lock()
606
        self.assertEqual([], self._calls)
607
        ld.unlock()
3331.3.2 by Robert Collins
Polish on lock hooks to be easier to use.
608
        lock_path = ld.transport.abspath(ld.path)
609
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
610
3331.3.12 by Martin Pool
Remove PhysicalLock class
611
    def test_LockDir_released_fail(self):
612
        # the LockDir.lock_released hook does not fire on failure.
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
613
        ld = self.get_lock()
614
        ld.create()
615
        ld2 = self.get_lock()
616
        ld.attempt_lock()
617
        ld2.force_break(ld2.peek())
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
618
        LockDir.hooks.install_named_hook('lock_released',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
619
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
620
        self.assertRaises(LockBroken, ld.unlock)
621
        self.assertEqual([], self._calls)
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
622
623
    def test_LockDir_broken_success(self):
624
        # the LockDir.lock_broken hook fires when a lock is broken.
625
        ld = self.get_lock()
626
        ld.create()
627
        ld2 = self.get_lock()
628
        result = ld.attempt_lock()
629
        LockDir.hooks.install_named_hook('lock_broken',
630
                                         self.record_hook, 'record_hook')
631
        ld2.force_break(ld2.peek())
632
        lock_path = ld.transport.abspath(ld.path)
633
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
634
635
    def test_LockDir_broken_failure(self):
636
        # the LockDir.lock_broken hook does not fires when a lock is already
637
        # released.
638
        ld = self.get_lock()
639
        ld.create()
640
        ld2 = self.get_lock()
641
        result = ld.attempt_lock()
642
        holder_info = ld2.peek()
643
        ld.unlock()
644
        LockDir.hooks.install_named_hook('lock_broken',
645
                                         self.record_hook, 'record_hook')
646
        ld2.force_break(holder_info)
647
        lock_path = ld.transport.abspath(ld.path)
648
        self.assertEqual([], self._calls)