~bzr-pqm/bzr/bzr.dev

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,
5425.4.9 by Martin Pool
Defensively handle 'localhost' in detecting dead locks
27
    lockdir,
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
28
    osutils,
1551.10.4 by Aaron Bentley
Update to skip on win32
29
    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)
30
    transport,
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
31
    )
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
32
from bzrlib.errors import (
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
33
    LockBreakMismatch,
34
    LockBroken,
35
    LockContention,
36
    LockFailed,
37
    LockNotHeld,
38
    )
5425.4.6 by Martin Pool
Move preparation of new locks into LockHeldInfo
39
from bzrlib.lockdir import (
40
    LockDir,
41
    LockHeldInfo,
42
    )
5579.3.1 by Jelmer Vernooij
Remove unused imports.
43
from bzrlib.tests import (
44
    features,
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
45
    TestCase,
5579.3.1 by Jelmer Vernooij
Remove unused imports.
46
    TestCaseWithTransport,
47
    )
1553.5.12 by Martin Pool
New LockDir locking mechanism
48
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
49
# These tests are run on the default transport provided by the test framework
50
# (typically a local disk transport).  That can be changed by the --transport
51
# option to bzr selftest.  The required properties of the transport
52
# implementation are tested separately.  (The main requirement is just that
53
# they don't allow overwriting nonempty directories.)
54
5425.4.27 by Martin Pool
pep8 cleanups
55
1553.5.12 by Martin Pool
New LockDir locking mechanism
56
class TestLockDir(TestCaseWithTransport):
57
    """Test LockDir operations"""
58
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
59
    def logging_report_function(self, fmt, *args):
60
        self._logged_reports.append((fmt, args))
61
62
    def setup_log_reporter(self, lock_dir):
63
        self._logged_reports = []
64
        lock_dir._report_function = self.logging_report_function
65
1553.5.12 by Martin Pool
New LockDir locking mechanism
66
    def test_00_lock_creation(self):
67
        """Creation of lock file on a transport"""
68
        t = self.get_transport()
69
        lf = LockDir(t, 'test_lock')
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
70
        self.assertFalse(lf.is_held)
1553.5.12 by Martin Pool
New LockDir locking mechanism
71
72
    def test_01_lock_repr(self):
73
        """Lock string representation"""
74
        lf = LockDir(self.get_transport(), 'test_lock')
75
        r = repr(lf)
76
        self.assertContainsRe(r, r'^LockDir\(.*/test_lock\)$')
77
78
    def test_02_unlocked_peek(self):
79
        lf = LockDir(self.get_transport(), 'test_lock')
80
        self.assertEqual(lf.peek(), None)
81
1687.1.3 by Robert Collins
Make LockDir.unlock check the lock is still intact.
82
    def get_lock(self):
83
        return LockDir(self.get_transport(), 'test_lock')
84
85
    def test_unlock_after_break_raises(self):
86
        ld = self.get_lock()
87
        ld2 = self.get_lock()
88
        ld.create()
89
        ld.attempt_lock()
90
        ld2.force_break(ld2.peek())
91
        self.assertRaises(LockBroken, ld.unlock)
92
1553.5.12 by Martin Pool
New LockDir locking mechanism
93
    def test_03_readonly_peek(self):
94
        lf = LockDir(self.get_readonly_transport(), 'test_lock')
95
        self.assertEqual(lf.peek(), None)
96
97
    def test_10_lock_uncontested(self):
98
        """Acquire and release a lock"""
99
        t = self.get_transport()
100
        lf = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
101
        lf.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
102
        lf.attempt_lock()
103
        try:
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
104
            self.assertTrue(lf.is_held)
1553.5.12 by Martin Pool
New LockDir locking mechanism
105
        finally:
106
            lf.unlock()
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
107
            self.assertFalse(lf.is_held)
1553.5.12 by Martin Pool
New LockDir locking mechanism
108
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
109
    def test_11_create_readonly_transport(self):
110
        """Fail to create lock on readonly transport"""
111
        t = self.get_readonly_transport()
112
        lf = LockDir(t, 'test_lock')
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
113
        self.assertRaises(LockFailed, lf.create)
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
114
115
    def test_12_lock_readonly_transport(self):
1553.5.12 by Martin Pool
New LockDir locking mechanism
116
        """Fail to lock on readonly transport"""
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
117
        lf = LockDir(self.get_transport(), 'test_lock')
118
        lf.create()
119
        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).
120
        self.assertRaises(LockFailed, lf.attempt_lock)
1553.5.12 by Martin Pool
New LockDir locking mechanism
121
122
    def test_20_lock_contested(self):
123
        """Contention to get a lock"""
124
        t = self.get_transport()
125
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
126
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
127
        lf1.attempt_lock()
128
        lf2 = LockDir(t, 'test_lock')
129
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
130
            # locking is between LockDir instances; aliases within
1553.5.12 by Martin Pool
New LockDir locking mechanism
131
            # a single process are not detected
132
            lf2.attempt_lock()
133
            self.fail('Failed to detect lock collision')
134
        except LockContention, e:
135
            self.assertEqual(e.lock, lf2)
136
            self.assertContainsRe(str(e),
137
                    r'^Could not acquire.*test_lock.*$')
138
        lf1.unlock()
139
140
    def test_20_lock_peek(self):
141
        """Peek at the state of a lock"""
142
        t = self.get_transport()
143
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
144
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
145
        lf1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
146
        self.addCleanup(lf1.unlock)
1553.5.12 by Martin Pool
New LockDir locking mechanism
147
        # lock is held, should get some info on it
148
        info1 = lf1.peek()
5425.4.3 by Martin Pool
Represent lock held info as an object, not just a dict
149
        self.assertEqual(set(info1.info_dict.keys()),
5425.4.27 by Martin Pool
pep8 cleanups
150
            set(['user', 'nonce', 'hostname', 'pid', 'start_time']))
1553.5.12 by Martin Pool
New LockDir locking mechanism
151
        # should get the same info if we look at it through a different
152
        # instance
153
        info2 = LockDir(t, 'test_lock').peek()
154
        self.assertEqual(info1, info2)
155
        # locks which are never used should be not-held
156
        self.assertEqual(LockDir(t, 'other_lock').peek(), None)
157
158
    def test_21_peek_readonly(self):
159
        """Peek over a readonly transport"""
160
        t = self.get_transport()
161
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
162
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
163
        lf2 = LockDir(self.get_readonly_transport(), 'test_lock')
164
        self.assertEqual(lf2.peek(), None)
165
        lf1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
166
        self.addCleanup(lf1.unlock)
1553.5.12 by Martin Pool
New LockDir locking mechanism
167
        info2 = lf2.peek()
168
        self.assertTrue(info2)
5425.4.3 by Martin Pool
Represent lock held info as an object, not just a dict
169
        self.assertEqual(info2.get('nonce'), lf1.nonce)
1553.5.12 by Martin Pool
New LockDir locking mechanism
170
171
    def test_30_lock_wait_fail(self):
172
        """Wait on a lock, then fail
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
173
1553.5.12 by Martin Pool
New LockDir locking mechanism
174
        We ask to wait up to 400ms; this should fail within at most one
175
        second.  (Longer times are more realistic but we don't want the test
176
        suite to take too long, and this should do for now.)
177
        """
178
        t = self.get_transport()
179
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
180
        lf1.create()
1553.5.12 by Martin Pool
New LockDir locking mechanism
181
        lf2 = LockDir(t, 'test_lock')
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
182
        self.setup_log_reporter(lf2)
1553.5.12 by Martin Pool
New LockDir locking mechanism
183
        lf1.attempt_lock()
184
        try:
185
            before = time.time()
186
            self.assertRaises(LockContention, lf2.wait_lock,
187
                              timeout=0.4, poll=0.1)
188
            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
189
            # it should only take about 0.4 seconds, but we allow more time in
190
            # case the machine is heavily loaded
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
191
            self.assertTrue(after - before <= 8.0,
5425.4.27 by Martin Pool
pep8 cleanups
192
                "took %f seconds to detect lock contention" % (after - before))
1553.5.12 by Martin Pool
New LockDir locking mechanism
193
        finally:
194
            lf1.unlock()
1957.1.7 by John Arbash Meinel
Add the ability to report if the lock changes from underneath you
195
        self.assertEqual(1, len(self._logged_reports))
5425.4.18 by Martin Pool
Cleaner and consistent user-orientend representation of LockHeldInfo
196
        self.assertContainsRe(self._logged_reports[0][0],
197
            r'Unable to obtain lock .* held by jrandom@example\.com on .*'
198
            r' \(process #\d+\), acquired .* ago\.\n'
199
            r'Will continue to try until \d{2}:\d{2}:\d{2}, unless '
200
            r'you press Ctrl-C.\n'
201
            r'See "bzr help break-lock" for more.')
1553.5.12 by Martin Pool
New LockDir locking mechanism
202
203
    def test_31_lock_wait_easy(self):
204
        """Succeed when waiting on a lock with no contention.
205
        """
206
        t = self.get_transport()
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
207
        lf1 = LockDir(t, 'test_lock')
208
        lf1.create()
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
209
        self.setup_log_reporter(lf1)
1553.5.12 by Martin Pool
New LockDir locking mechanism
210
        try:
211
            before = time.time()
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
212
            lf1.wait_lock(timeout=0.4, poll=0.1)
1553.5.12 by Martin Pool
New LockDir locking mechanism
213
            after = time.time()
214
            self.assertTrue(after - before <= 1.0)
215
        finally:
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
216
            lf1.unlock()
1957.1.1 by John Arbash Meinel
Report to the user when we are spinning on a lock
217
        self.assertEqual([], self._logged_reports)
1553.5.12 by Martin Pool
New LockDir locking mechanism
218
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
219
    def test_40_confirm_easy(self):
220
        """Confirm a lock that's already held"""
221
        t = self.get_transport()
222
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
223
        lf1.create()
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
224
        lf1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
225
        self.addCleanup(lf1.unlock)
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
226
        lf1.confirm()
227
228
    def test_41_confirm_not_held(self):
229
        """Confirm a lock that's already held"""
230
        t = self.get_transport()
231
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
232
        lf1.create()
1553.5.20 by Martin Pool
Start adding LockDir.confirm() method
233
        self.assertRaises(LockNotHeld, lf1.confirm)
1553.5.23 by Martin Pool
Start LockDir.confirm method and LockBroken exception
234
235
    def test_42_confirm_broken_manually(self):
236
        """Confirm a lock broken by hand"""
237
        t = self.get_transport()
238
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
239
        lf1.create()
1553.5.23 by Martin Pool
Start LockDir.confirm method and LockBroken exception
240
        lf1.attempt_lock()
241
        t.move('test_lock', 'lock_gone_now')
242
        self.assertRaises(LockBroken, lf1.confirm)
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
243
        # Clean up
244
        t.move('lock_gone_now', 'test_lock')
245
        lf1.unlock()
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
246
247
    def test_43_break(self):
248
        """Break a lock whose caller has forgotten it"""
249
        t = self.get_transport()
250
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
251
        lf1.create()
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
252
        lf1.attempt_lock()
253
        # we incorrectly discard the lock object without unlocking it
254
        del lf1
255
        # someone else sees it's still locked
256
        lf2 = LockDir(t, 'test_lock')
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
257
        holder_info = lf2.peek()
258
        self.assertTrue(holder_info)
259
        lf2.force_break(holder_info)
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
260
        # now we should be able to take it
261
        lf2.attempt_lock()
4327.1.4 by Vincent Ladeuil
Fix lock test failures by taking lock breaking into account.
262
        self.addCleanup(lf2.unlock)
1553.5.25 by Martin Pool
New LockDir.force_break and simple test case
263
        lf2.confirm()
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
264
265
    def test_44_break_already_released(self):
266
        """Lock break races with regular release"""
267
        t = self.get_transport()
268
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
269
        lf1.create()
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
270
        lf1.attempt_lock()
271
        # someone else sees it's still locked
272
        lf2 = LockDir(t, 'test_lock')
273
        holder_info = lf2.peek()
274
        # in the interim the lock is released
275
        lf1.unlock()
276
        # break should succeed
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
277
        lf2.force_break(holder_info)
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
278
        # now we should be able to take it
279
        lf2.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
280
        self.addCleanup(lf2.unlock)
1553.5.26 by Martin Pool
Breaking an already-released lock should just succeed
281
        lf2.confirm()
282
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
283
    def test_45_break_mismatch(self):
284
        """Lock break races with someone else acquiring it"""
285
        t = self.get_transport()
286
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
287
        lf1.create()
1553.5.27 by Martin Pool
Confirm that only the intended holder of a lock was broken.
288
        lf1.attempt_lock()
289
        # someone else sees it's still locked
290
        lf2 = LockDir(t, 'test_lock')
291
        holder_info = lf2.peek()
292
        # in the interim the lock is released
293
        lf1.unlock()
294
        lf3 = LockDir(t, 'test_lock')
295
        lf3.attempt_lock()
296
        # break should now *fail*
297
        self.assertRaises(LockBreakMismatch, lf2.force_break,
298
                          holder_info)
299
        lf3.unlock()
1553.5.54 by Martin Pool
Add LockDir.read_lock fake method
300
301
    def test_46_fake_read_lock(self):
302
        t = self.get_transport()
303
        lf1 = LockDir(t, 'test_lock')
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
304
        lf1.create()
1553.5.54 by Martin Pool
Add LockDir.read_lock fake method
305
        lf1.lock_read()
306
        lf1.unlock()
1553.5.58 by Martin Pool
Change LockDirs to format "lock-name/held/info"
307
308
    def test_50_lockdir_representation(self):
309
        """Check the on-disk representation of LockDirs is as expected.
310
311
        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
312
        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"
313
        containing an info file.
314
        """
315
        t = self.get_transport()
316
        lf1 = LockDir(t, 'test_lock')
317
        lf1.create()
318
        self.assertTrue(t.has('test_lock'))
319
        lf1.lock_write()
320
        self.assertTrue(t.has('test_lock/held/info'))
321
        lf1.unlock()
322
        self.assertFalse(t.has('test_lock/held/info'))
1687.1.5 by Robert Collins
Add break_lock utility function to LockDir.
323
324
    def test_break_lock(self):
325
        # the ui based break_lock routine should Just Work (tm)
326
        ld1 = self.get_lock()
327
        ld2 = self.get_lock()
328
        ld1.create()
329
        ld1.lock_write()
1687.1.6 by Robert Collins
Extend LockableFiles to support break_lock() calls.
330
        # do this without IO redirection to ensure it doesn't prompt.
331
        self.assertRaises(AssertionError, ld1.break_lock)
1687.1.5 by Robert Collins
Add break_lock utility function to LockDir.
332
        orig_factory = bzrlib.ui.ui_factory
4449.3.27 by Martin Pool
More test updates to use CannedInputUIFactory
333
        bzrlib.ui.ui_factory = bzrlib.ui.CannedInputUIFactory([True])
1687.1.5 by Robert Collins
Add break_lock utility function to LockDir.
334
        try:
335
            ld2.break_lock()
336
            self.assertRaises(LockBroken, ld1.unlock)
337
        finally:
338
            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.
339
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
340
    def test_break_lock_corrupt_info(self):
341
        """break_lock works even if the info file is corrupt (and tells the UI
342
        that it is corrupt).
343
        """
344
        ld = self.get_lock()
345
        ld2 = self.get_lock()
346
        ld.create()
347
        ld.lock_write()
348
        ld.transport.put_bytes_non_atomic('test_lock/held/info', '\0')
5425.4.27 by Martin Pool
pep8 cleanups
349
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
350
        class LoggingUIFactory(bzrlib.ui.SilentUIFactory):
351
            def __init__(self):
352
                self.prompts = []
5425.4.27 by Martin Pool
pep8 cleanups
353
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
354
            def get_boolean(self, prompt):
355
                self.prompts.append(('boolean', prompt))
356
                return True
5425.4.27 by Martin Pool
pep8 cleanups
357
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
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')
5425.4.27 by Martin Pool
pep8 cleanups
375
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
376
        class LoggingUIFactory(bzrlib.ui.SilentUIFactory):
377
            def __init__(self):
378
                self.prompts = []
5425.4.27 by Martin Pool
pep8 cleanups
379
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
380
            def get_boolean(self, prompt):
381
                self.prompts.append(('boolean', prompt))
382
                return True
5425.4.27 by Martin Pool
pep8 cleanups
383
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
384
        ui = LoggingUIFactory()
385
        orig_factory = bzrlib.ui.ui_factory
386
        bzrlib.ui.ui_factory = ui
387
        try:
388
            ld2.break_lock()
389
            self.assertRaises(LockBroken, ld.unlock)
390
            self.assertLength(0, ui.prompts)
391
        finally:
392
            bzrlib.ui.ui_factory = orig_factory
393
        # Suppress warnings due to ld not being unlocked
394
        # XXX: if lock_broken hook was invoked in this case, this hack would
395
        # not be necessary.  - Andrew Bennetts, 2010-09-06.
396
        del self._lock_actions[:]
397
1955.1.1 by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile.
398
    def test_create_missing_base_directory(self):
399
        """If LockDir.path doesn't exist, it can be created
400
401
        Some people manually remove the entire lock/ directory trying
402
        to unlock a stuck repository/branch/etc. Rather than failing
403
        after that, just create the lock directory when needed.
404
        """
405
        t = self.get_transport()
406
        lf1 = LockDir(t, 'test_lock')
407
408
        lf1.create()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
409
        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.
410
411
        t.rmdir('test_lock')
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
412
        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.
413
414
        # This will create 'test_lock' if it needs to
415
        lf1.lock_write()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
416
        self.assertTrue(t.has('test_lock'))
417
        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.
418
419
        lf1.unlock()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
420
        self.assertFalse(t.has('test_lock/held/info'))
1957.1.6 by John Arbash Meinel
[merge] bzr.dev 2009
421
5425.4.3 by Martin Pool
Represent lock held info as an object, not just a dict
422
    def test_display_form(self):
1957.1.5 by John Arbash Meinel
Create a helper function for formatting lock information
423
        ld1 = self.get_lock()
424
        ld1.create()
425
        ld1.lock_write()
426
        try:
5425.4.18 by Martin Pool
Cleaner and consistent user-orientend representation of LockHeldInfo
427
            info_list = ld1.peek().to_readable_dict()
1957.1.5 by John Arbash Meinel
Create a helper function for formatting lock information
428
        finally:
429
            ld1.unlock()
5425.4.18 by Martin Pool
Cleaner and consistent user-orientend representation of LockHeldInfo
430
        self.assertEqual(info_list['user'], u'jrandom@example.com')
5425.4.27 by Martin Pool
pep8 cleanups
431
        self.assertContainsRe(info_list['pid'], '^\d+$')
432
        self.assertContainsRe(info_list['time_ago'], r'^\d+ seconds? ago$')
2055.2.1 by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email
433
434
    def test_lock_without_email(self):
435
        global_config = config.GlobalConfig()
436
        # Intentionally has no email address
437
        global_config.set_user_option('email', 'User Identity')
438
        ld1 = self.get_lock()
439
        ld1.create()
440
        ld1.lock_write()
441
        ld1.unlock()
1551.10.3 by Aaron Bentley
Lock attempts don't treat permission problems as lock contention
442
443
    def test_lock_permission(self):
4797.70.1 by Vincent Ladeuil
Skip chmodbits dependent tests when running as root
444
        self.requireFeature(features.not_running_as_root)
1551.10.4 by Aaron Bentley
Update to skip on win32
445
        if not osutils.supports_posix_readonly():
3107.2.2 by John Arbash Meinel
feedback from Martin.
446
            raise tests.TestSkipped('Cannot induce a permission failure')
1551.10.3 by Aaron Bentley
Lock attempts don't treat permission problems as lock contention
447
        ld1 = self.get_lock()
448
        lock_path = ld1.transport.local_abspath('test_lock')
449
        os.mkdir(lock_path)
450
        osutils.make_readonly(lock_path)
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
451
        self.assertRaises(errors.LockFailed, ld1.attempt_lock)
2555.3.5 by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek()
452
453
    def test_lock_by_token(self):
454
        ld1 = self.get_lock()
455
        token = ld1.lock_write()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
456
        self.addCleanup(ld1.unlock)
2555.3.5 by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek()
457
        self.assertNotEqual(None, token)
458
        ld2 = self.get_lock()
459
        t2 = ld2.lock_write(token)
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
460
        self.addCleanup(ld2.unlock)
2555.3.5 by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek()
461
        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)
462
463
    def test_lock_with_buggy_rename(self):
464
        # test that lock acquisition handles servers which pretend they
465
        # renamed correctly but that actually fail
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
466
        t = transport.get_transport_from_url(
467
            'brokenrename+' + self.get_url())
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)
468
        ld1 = LockDir(t, 'test_lock')
469
        ld1.create()
470
        ld1.attempt_lock()
471
        ld2 = LockDir(t, 'test_lock')
2555.3.14 by Martin Pool
Better handling in LockDir of rename that moves one directory within another
472
        # we should fail to lock
473
        e = self.assertRaises(errors.LockContention, ld2.attempt_lock)
474
        # now the original caller should succeed in unlocking
475
        ld1.unlock()
476
        # and there should be nothing left over
477
        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
478
479
    def test_failed_lock_leaves_no_trash(self):
480
        # if we fail to acquire the lock, we don't leave pending directories
481
        # behind -- https://bugs.launchpad.net/bzr/+bug/109169
482
        ld1 = self.get_lock()
483
        ld2 = self.get_lock()
484
        # should be nothing before we start
485
        ld1.create()
486
        t = self.get_transport().clone('test_lock')
5425.4.27 by Martin Pool
pep8 cleanups
487
2555.3.12 by Martin Pool
Add test for https://bugs.launchpad.net/bzr/+bug/109169 -- test_failed_lock_leaves_no_trash
488
        def check_dir(a):
489
            self.assertEquals(a, t.list_dir('.'))
5425.4.27 by Martin Pool
pep8 cleanups
490
2555.3.12 by Martin Pool
Add test for https://bugs.launchpad.net/bzr/+bug/109169 -- test_failed_lock_leaves_no_trash
491
        check_dir([])
492
        # when held, that's all we see
493
        ld1.attempt_lock()
4327.1.1 by Vincent Ladeuil
Start addressing test failing when run with -Dlock.
494
        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
495
        check_dir(['held'])
496
        # second guy should fail
497
        self.assertRaises(errors.LockContention, ld2.attempt_lock)
498
        # no kibble
499
        check_dir(['held'])
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
500
4634.138.1 by Martin Pool
Add failing test for \#185103
501
    def test_no_lockdir_info(self):
502
        """We can cope with empty info files."""
503
        # 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
504
        # <https://bugs.launchpad.net/bzr/+bug/185103> and all its dupes.
4634.138.1 by Martin Pool
Add failing test for \#185103
505
        # Processes are often interrupted after opening the file
506
        # before the actual contents are committed.
507
        t = self.get_transport()
508
        t.mkdir('test_lock')
509
        t.mkdir('test_lock/held')
510
        t.put_bytes('test_lock/held/info', '')
511
        lf = LockDir(t, 'test_lock')
4634.138.2 by Martin Pool
Copy with lock info file being empty
512
        info = lf.peek()
5425.4.18 by Martin Pool
Cleaner and consistent user-orientend representation of LockHeldInfo
513
        formatted_info = info.to_readable_dict()
4634.138.2 by Martin Pool
Copy with lock info file being empty
514
        self.assertEquals(
5425.4.18 by Martin Pool
Cleaner and consistent user-orientend representation of LockHeldInfo
515
            dict(user='<unknown>', hostname='<unknown>', pid='<unknown>',
516
                time_ago='(unknown)'),
4634.138.2 by Martin Pool
Copy with lock info file being empty
517
            formatted_info)
4634.138.1 by Martin Pool
Add failing test for \#185103
518
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
519
    def test_corrupt_lockdir_info(self):
520
        """We can cope with corrupt (and thus unparseable) info files."""
521
        # 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.
522
        # <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.
523
        # In particular some systems tend to fill recently created files with
524
        # nul bytes after recovering from a system crash.
525
        t = self.get_transport()
526
        t.mkdir('test_lock')
527
        t.mkdir('test_lock/held')
528
        t.put_bytes('test_lock/held/info', '\0')
529
        lf = LockDir(t, 'test_lock')
530
        self.assertRaises(errors.LockCorrupt, lf.peek)
531
        # Currently attempt_lock gives LockContention, but LockCorrupt would be
532
        # a reasonable result too.
533
        self.assertRaises(
534
            (errors.LockCorrupt, errors.LockContention), lf.attempt_lock)
535
        self.assertRaises(errors.LockCorrupt, lf.validate_token, 'fake token')
536
537
    def test_missing_lockdir_info(self):
538
        """We can cope with absent info files."""
539
        t = self.get_transport()
540
        t.mkdir('test_lock')
541
        t.mkdir('test_lock/held')
542
        lf = LockDir(t, 'test_lock')
543
        # In this case we expect the 'not held' result from peek, because peek
544
        # cannot be expected to notice that there is a 'held' directory with no
545
        # 'info' file.
546
        self.assertEqual(None, lf.peek())
547
        # And lock/unlock may work or give LockContention (but not any other
548
        # error).
549
        try:
550
            lf.attempt_lock()
551
        except LockContention:
552
            # LockContention is ok, and expected on Windows
553
            pass
554
        else:
555
            # no error is ok, and expected on POSIX (because POSIX allows
556
            # os.rename over an empty directory).
557
            lf.unlock()
558
        # Currently raises TokenMismatch, but LockCorrupt would be reasonable
559
        # too.
560
        self.assertRaises(
561
            (errors.TokenMismatch, errors.LockCorrupt),
562
            lf.validate_token, 'fake token')
563
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
564
565
class TestLockDirHooks(TestCaseWithTransport):
566
567
    def setUp(self):
568
        super(TestLockDirHooks, self).setUp()
569
        self._calls = []
570
571
    def get_lock(self):
572
        return LockDir(self.get_transport(), 'test_lock')
573
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
574
    def record_hook(self, result):
575
        self._calls.append(result)
576
3331.3.12 by Martin Pool
Remove PhysicalLock class
577
    def test_LockDir_acquired_success(self):
578
        # the LockDir.lock_acquired hook fires when a lock is acquired.
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
579
        LockDir.hooks.install_named_hook('lock_acquired',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
580
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
581
        ld = self.get_lock()
582
        ld.create()
583
        self.assertEqual([], self._calls)
584
        result = ld.attempt_lock()
3331.3.2 by Robert Collins
Polish on lock hooks to be easier to use.
585
        lock_path = ld.transport.abspath(ld.path)
586
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
587
        ld.unlock()
3331.3.2 by Robert Collins
Polish on lock hooks to be easier to use.
588
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
589
3331.3.12 by Martin Pool
Remove PhysicalLock class
590
    def test_LockDir_acquired_fail(self):
591
        # 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
592
        ld = self.get_lock()
593
        ld.create()
594
        ld2 = self.get_lock()
595
        ld2.attempt_lock()
596
        # install a lock hook now, when the disk lock is locked
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
597
        LockDir.hooks.install_named_hook('lock_acquired',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
598
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
599
        self.assertRaises(errors.LockContention, ld.attempt_lock)
600
        self.assertEqual([], self._calls)
601
        ld2.unlock()
602
        self.assertEqual([], self._calls)
603
3331.3.12 by Martin Pool
Remove PhysicalLock class
604
    def test_LockDir_released_success(self):
605
        # the LockDir.lock_released hook fires when a lock is acquired.
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
606
        LockDir.hooks.install_named_hook('lock_released',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
607
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
608
        ld = self.get_lock()
609
        ld.create()
610
        self.assertEqual([], self._calls)
611
        result = ld.attempt_lock()
612
        self.assertEqual([], self._calls)
613
        ld.unlock()
3331.3.2 by Robert Collins
Polish on lock hooks to be easier to use.
614
        lock_path = ld.transport.abspath(ld.path)
615
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
616
3331.3.12 by Martin Pool
Remove PhysicalLock class
617
    def test_LockDir_released_fail(self):
618
        # 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
619
        ld = self.get_lock()
620
        ld.create()
621
        ld2 = self.get_lock()
622
        ld.attempt_lock()
623
        ld2.force_break(ld2.peek())
3331.3.11 by Martin Pool
Move LockDir hooks onto LockDir
624
        LockDir.hooks.install_named_hook('lock_released',
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
625
                                         self.record_hook, 'record_hook')
3331.3.1 by Robert Collins
* ``LockDir`` lock acquisition and release now trigger hooks allowing
626
        self.assertRaises(LockBroken, ld.unlock)
627
        self.assertEqual([], self._calls)
4327.1.2 by Vincent Ladeuil
Introduce a new lock_broken hook.
628
629
    def test_LockDir_broken_success(self):
630
        # the LockDir.lock_broken hook fires when a lock is broken.
631
        ld = self.get_lock()
632
        ld.create()
633
        ld2 = self.get_lock()
634
        result = ld.attempt_lock()
635
        LockDir.hooks.install_named_hook('lock_broken',
636
                                         self.record_hook, 'record_hook')
637
        ld2.force_break(ld2.peek())
638
        lock_path = ld.transport.abspath(ld.path)
639
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
640
641
    def test_LockDir_broken_failure(self):
642
        # the LockDir.lock_broken hook does not fires when a lock is already
643
        # released.
644
        ld = self.get_lock()
645
        ld.create()
646
        ld2 = self.get_lock()
647
        result = ld.attempt_lock()
648
        holder_info = ld2.peek()
649
        ld.unlock()
650
        LockDir.hooks.install_named_hook('lock_broken',
651
                                         self.record_hook, 'record_hook')
652
        ld2.force_break(holder_info)
653
        lock_path = ld.transport.abspath(ld.path)
654
        self.assertEqual([], self._calls)
5425.4.1 by Martin Pool
add xfail tests for stale locks
655
656
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
657
class TestLockHeldInfo(TestCase):
658
    """Can get information about the lock holder, and detect whether they're
659
    still alive."""
5425.4.1 by Martin Pool
add xfail tests for stale locks
660
5425.4.17 by Martin Pool
Add test for LockHeldInfo repr
661
    def test_repr(self):
662
        info = LockHeldInfo.for_this_process(None)
5425.4.18 by Martin Pool
Cleaner and consistent user-orientend representation of LockHeldInfo
663
        self.assertContainsRe(repr(info), r"LockHeldInfo\(.*\)")
664
665
    def test_unicode(self):
666
        info = LockHeldInfo.for_this_process(None)
667
        self.assertContainsRe(unicode(info),
668
            r'held by .* on .* \(process #\d+\), acquired .* ago')
5425.4.17 by Martin Pool
Add test for LockHeldInfo repr
669
5425.4.7 by Martin Pool
Add and test is_locked_by_this_process
670
    def test_is_locked_by_this_process(self):
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
671
        info = LockHeldInfo.for_this_process(None)
5425.4.7 by Martin Pool
Add and test is_locked_by_this_process
672
        self.assertTrue(info.is_locked_by_this_process())
5425.4.6 by Martin Pool
Move preparation of new locks into LockHeldInfo
673
5425.4.8 by Martin Pool
Basic detection of known dead lock holders
674
    def test_is_not_locked_by_this_process(self):
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
675
        info = LockHeldInfo.for_this_process(None)
5425.4.27 by Martin Pool
pep8 cleanups
676
        info.info_dict['pid'] = '123123123123123'
5425.4.8 by Martin Pool
Basic detection of known dead lock holders
677
        self.assertFalse(info.is_locked_by_this_process())
678
679
    def test_lock_holder_live_process(self):
680
        """Detect that the holder (this process) is still running."""
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
681
        info = LockHeldInfo.for_this_process(None)
5425.4.8 by Martin Pool
Basic detection of known dead lock holders
682
        self.assertFalse(info.is_lock_holder_known_dead())
5425.4.27 by Martin Pool
pep8 cleanups
683
5425.4.8 by Martin Pool
Basic detection of known dead lock holders
684
    def test_lock_holder_dead_process(self):
685
        """Detect that the holder (this process) is still running."""
6060.3.1 by Jelmer Vernooij
Fix lockdir tests when the hostname is set to 'localhost'.
686
        self.overrideAttr(lockdir, 'get_host_name',
687
            lambda: 'aproperhostname')
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
688
        info = LockHeldInfo.for_this_process(None)
5425.4.27 by Martin Pool
pep8 cleanups
689
        info.info_dict['pid'] = '123123123'
5425.4.8 by Martin Pool
Basic detection of known dead lock holders
690
        self.assertTrue(info.is_lock_holder_known_dead())
5425.4.27 by Martin Pool
pep8 cleanups
691
5425.4.1 by Martin Pool
add xfail tests for stale locks
692
    def test_lock_holder_other_machine(self):
693
        """The lock holder isn't here so we don't know if they're alive."""
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
694
        info = LockHeldInfo.for_this_process(None)
5425.6.1 by Martin Pool
Only detect as stale locks from the same user
695
        info.info_dict['hostname'] = 'egg.example.com'
5425.4.27 by Martin Pool
pep8 cleanups
696
        info.info_dict['pid'] = '123123123'
5425.6.1 by Martin Pool
Only detect as stale locks from the same user
697
        self.assertFalse(info.is_lock_holder_known_dead())
698
699
    def test_lock_holder_other_user(self):
700
        """Only auto-break locks held by this user."""
701
        info = LockHeldInfo.for_this_process(None)
702
        info.info_dict['user'] = 'notme@example.com'
5425.4.27 by Martin Pool
pep8 cleanups
703
        info.info_dict['pid'] = '123123123'
5425.4.8 by Martin Pool
Basic detection of known dead lock holders
704
        self.assertFalse(info.is_lock_holder_known_dead())
5425.4.1 by Martin Pool
add xfail tests for stale locks
705
706
    def test_no_good_hostname(self):
707
        """Correctly handle ambiguous hostnames.
708
709
        If the lock's recorded with just 'localhost' we can't really trust
5425.4.9 by Martin Pool
Defensively handle 'localhost' in detecting dead locks
710
        it's the same 'localhost'.  (There are quite a few of them. :-)
711
        So even if the process is known not to be alive, we can't say that's
712
        known for sure.
5425.4.1 by Martin Pool
add xfail tests for stale locks
713
        """
5425.4.9 by Martin Pool
Defensively handle 'localhost' in detecting dead locks
714
        self.overrideAttr(lockdir, 'get_host_name',
715
            lambda: 'localhost')
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
716
        info = LockHeldInfo.for_this_process(None)
5425.4.9 by Martin Pool
Defensively handle 'localhost' in detecting dead locks
717
        info.info_dict['pid'] = '123123123'
718
        self.assertFalse(info.is_lock_holder_known_dead())
5425.4.1 by Martin Pool
add xfail tests for stale locks
719
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
720
721
class TestStaleLockDir(TestCaseWithTransport):
722
    """Can automatically break stale locks.
723
724
    :see: https://bugs.launchpad.net/bzr/+bug/220464
725
    """
5425.4.25 by Martin Pool
Support auto-stealing dead locks, but turn it off by default.
726
5425.4.1 by Martin Pool
add xfail tests for stale locks
727
    def test_auto_break_stale_lock(self):
728
        """Locks safely known to be stale are just cleaned up.
729
730
        This generates a warning but no other user interaction.
731
        """
6060.3.1 by Jelmer Vernooij
Fix lockdir tests when the hostname is set to 'localhost'.
732
        self.overrideAttr(lockdir, 'get_host_name',
733
            lambda: 'aproperhostname')
5425.4.25 by Martin Pool
Support auto-stealing dead locks, but turn it off by default.
734
        # This is off by default at present; see the discussion in the bug.
735
        # If you change the default, don't forget to update the docs.
736
        config.GlobalConfig().set_user_option('locks.steal_dead', True)
5425.4.10 by Martin Pool
Allow storing extra info into lockdir info files to aid testing
737
        # Create a lock pretending to come from a different nonexistent
738
        # process on the same machine.
739
        l1 = LockDir(self.get_transport(), 'a',
740
            extra_holder_info={'pid': '12312313'})
741
        token_1 = l1.attempt_lock()
742
        l2 = LockDir(self.get_transport(), 'a')
5425.4.13 by Martin Pool
Steal locks of dead local processes, with a user warning
743
        token_2 = l2.attempt_lock()
744
        # l1 will notice its lock was stolen.
745
        self.assertRaises(errors.LockBroken,
746
            l1.unlock)
747
        l2.unlock()
5425.4.1 by Martin Pool
add xfail tests for stale locks
748
749
    def test_auto_break_stale_lock_configured_off(self):
5425.4.15 by Martin Pool
Add steal_dead_locks option letting automatic lock-breaking be turned off
750
        """Automatic breaking can be turned off"""
751
        l1 = LockDir(self.get_transport(), 'a',
752
            extra_holder_info={'pid': '12312313'})
753
        token_1 = l1.attempt_lock()
754
        self.addCleanup(l1.unlock)
755
        l2 = LockDir(self.get_transport(), 'a')
5425.4.25 by Martin Pool
Support auto-stealing dead locks, but turn it off by default.
756
        # This fails now, because dead lock breaking is off by default.
5425.4.15 by Martin Pool
Add steal_dead_locks option letting automatic lock-breaking be turned off
757
        self.assertRaises(LockContention,
758
            l2.attempt_lock)
759
        # and it's in fact not broken
760
        l1.confirm()