/brz/remove-bazaar

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