/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Martin von Gagern
  • Date: 2010-04-20 08:47:38 UTC
  • mfrom: (5167 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5195.
  • Revision ID: martin.vgagern@gmx.net-20100420084738-ygymnqmdllzrhpfn
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
18
# TODO: Perhaps there should be an API to find out if bzr running under the
28
28
 
29
29
import atexit
30
30
import codecs
 
31
from copy import copy
31
32
from cStringIO import StringIO
32
33
import difflib
33
34
import doctest
34
35
import errno
35
36
import logging
 
37
import math
36
38
import os
37
39
from pprint import pformat
38
40
import random
39
41
import re
40
42
import shlex
41
43
import stat
42
 
from subprocess import Popen, PIPE
 
44
from subprocess import Popen, PIPE, STDOUT
43
45
import sys
44
46
import tempfile
45
47
import threading
46
48
import time
 
49
import traceback
47
50
import unittest
48
51
import warnings
49
52
 
 
53
import testtools
 
54
# nb: check this before importing anything else from within it
 
55
_testtools_version = getattr(testtools, '__version__', ())
 
56
if _testtools_version < (0, 9, 2):
 
57
    raise ImportError("need at least testtools 0.9.2: %s is %r"
 
58
        % (testtools.__file__, _testtools_version))
 
59
from testtools import content
50
60
 
51
61
from bzrlib import (
52
62
    branchbuilder,
53
63
    bzrdir,
 
64
    chk_map,
 
65
    config,
54
66
    debug,
55
67
    errors,
 
68
    hooks,
 
69
    lock as _mod_lock,
56
70
    memorytree,
57
71
    osutils,
58
72
    progress,
76
90
from bzrlib.merge import merge_inner
77
91
import bzrlib.merge3
78
92
import bzrlib.plugin
 
93
from bzrlib.smart import client, request, server
79
94
import bzrlib.store
80
95
from bzrlib import symbol_versioning
81
96
from bzrlib.symbol_versioning import (
82
97
    DEPRECATED_PARAMETER,
83
98
    deprecated_function,
 
99
    deprecated_in,
84
100
    deprecated_method,
85
101
    deprecated_passed,
86
102
    )
87
103
import bzrlib.trace
88
 
from bzrlib.transport import get_transport
 
104
from bzrlib.transport import (
 
105
    get_transport,
 
106
    memory,
 
107
    pathfilter,
 
108
    )
89
109
import bzrlib.transport
90
 
from bzrlib.transport.local import LocalURLServer
91
 
from bzrlib.transport.memory import MemoryServer
92
 
from bzrlib.transport.readonly import ReadonlyServer
93
110
from bzrlib.trace import mutter, note
94
 
from bzrlib.tests import TestUtil
 
111
from bzrlib.tests import (
 
112
    test_server,
 
113
    TestUtil,
 
114
    )
95
115
from bzrlib.tests.http_server import HttpServer
96
116
from bzrlib.tests.TestUtil import (
97
117
                          TestSuite,
98
118
                          TestLoader,
99
119
                          )
100
120
from bzrlib.tests.treeshape import build_tree_contents
 
121
from bzrlib.ui import NullProgressView
 
122
from bzrlib.ui.text import TextUIFactory
101
123
import bzrlib.version_info_formats.format_custom
102
124
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
103
125
 
106
128
# shown frame is the test code, not our assertXYZ.
107
129
__unittest = 1
108
130
 
109
 
default_transport = LocalURLServer
 
131
default_transport = test_server.LocalURLServer
 
132
 
 
133
 
 
134
_unitialized_attr = object()
 
135
"""A sentinel needed to act as a default value in a method signature."""
 
136
 
 
137
 
 
138
# Subunit result codes, defined here to prevent a hard dependency on subunit.
 
139
SUBUNIT_SEEK_SET = 0
 
140
SUBUNIT_SEEK_CUR = 1
110
141
 
111
142
 
112
143
class ExtendedTestResult(unittest._TextTestResult):
126
157
    """
127
158
 
128
159
    stop_early = False
129
 
    
 
160
 
130
161
    def __init__(self, stream, descriptions, verbosity,
131
162
                 bench_history=None,
132
 
                 num_tests=None,
 
163
                 strict=False,
133
164
                 ):
134
165
        """Construct new TestResult.
135
166
 
153
184
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
154
185
        self._bench_history = bench_history
155
186
        self.ui = ui.ui_factory
156
 
        self.num_tests = num_tests
 
187
        self.num_tests = 0
157
188
        self.error_count = 0
158
189
        self.failure_count = 0
159
190
        self.known_failure_count = 0
162
193
        self.unsupported = {}
163
194
        self.count = 0
164
195
        self._overall_start_time = time.time()
165
 
    
166
 
    def _extractBenchmarkTime(self, testCase):
 
196
        self._strict = strict
 
197
 
 
198
    def stopTestRun(self):
 
199
        run = self.testsRun
 
200
        actionTaken = "Ran"
 
201
        stopTime = time.time()
 
202
        timeTaken = stopTime - self.startTime
 
203
        self.printErrors()
 
204
        self.stream.writeln(self.separator2)
 
205
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
206
                            run, run != 1 and "s" or "", timeTaken))
 
207
        self.stream.writeln()
 
208
        if not self.wasSuccessful():
 
209
            self.stream.write("FAILED (")
 
210
            failed, errored = map(len, (self.failures, self.errors))
 
211
            if failed:
 
212
                self.stream.write("failures=%d" % failed)
 
213
            if errored:
 
214
                if failed: self.stream.write(", ")
 
215
                self.stream.write("errors=%d" % errored)
 
216
            if self.known_failure_count:
 
217
                if failed or errored: self.stream.write(", ")
 
218
                self.stream.write("known_failure_count=%d" %
 
219
                    self.known_failure_count)
 
220
            self.stream.writeln(")")
 
221
        else:
 
222
            if self.known_failure_count:
 
223
                self.stream.writeln("OK (known_failures=%d)" %
 
224
                    self.known_failure_count)
 
225
            else:
 
226
                self.stream.writeln("OK")
 
227
        if self.skip_count > 0:
 
228
            skipped = self.skip_count
 
229
            self.stream.writeln('%d test%s skipped' %
 
230
                                (skipped, skipped != 1 and "s" or ""))
 
231
        if self.unsupported:
 
232
            for feature, count in sorted(self.unsupported.items()):
 
233
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
234
                    (feature, count))
 
235
        if self._strict:
 
236
            ok = self.wasStrictlySuccessful()
 
237
        else:
 
238
            ok = self.wasSuccessful()
 
239
        if TestCase._first_thread_leaker_id:
 
240
            self.stream.write(
 
241
                '%s is leaking threads among %d leaking tests.\n' % (
 
242
                TestCase._first_thread_leaker_id,
 
243
                TestCase._leaking_threads_tests))
 
244
            # We don't report the main thread as an active one.
 
245
            self.stream.write(
 
246
                '%d non-main threads were left active in the end.\n'
 
247
                % (TestCase._active_threads - 1))
 
248
 
 
249
    def getDescription(self, test):
 
250
        return test.id()
 
251
 
 
252
    def _extractBenchmarkTime(self, testCase, details=None):
167
253
        """Add a benchmark time for the current test case."""
 
254
        if details and 'benchtime' in details:
 
255
            return float(''.join(details['benchtime'].iter_bytes()))
168
256
        return getattr(testCase, "_benchtime", None)
169
 
    
 
257
 
170
258
    def _elapsedTestTimeString(self):
171
259
        """Return a time string for the overall time the current test has taken."""
172
260
        return self._formatTime(time.time() - self._start_time)
174
262
    def _testTimeString(self, testCase):
175
263
        benchmark_time = self._extractBenchmarkTime(testCase)
176
264
        if benchmark_time is not None:
177
 
            return "%s/%s" % (
178
 
                self._formatTime(benchmark_time),
179
 
                self._elapsedTestTimeString())
 
265
            return self._formatTime(benchmark_time) + "*"
180
266
        else:
181
 
            return "           %s" % self._elapsedTestTimeString()
 
267
            return self._elapsedTestTimeString()
182
268
 
183
269
    def _formatTime(self, seconds):
184
270
        """Format seconds as milliseconds with leading spaces."""
193
279
 
194
280
    def startTest(self, test):
195
281
        unittest.TestResult.startTest(self, test)
 
282
        if self.count == 0:
 
283
            self.startTests()
196
284
        self.report_test_start(test)
197
285
        test.number = self.count
198
286
        self._recordTestStartTime()
199
287
 
 
288
    def startTests(self):
 
289
        import platform
 
290
        if getattr(sys, 'frozen', None) is None:
 
291
            bzr_path = osutils.realpath(sys.argv[0])
 
292
        else:
 
293
            bzr_path = sys.executable
 
294
        self.stream.write(
 
295
            'bzr selftest: %s\n' % (bzr_path,))
 
296
        self.stream.write(
 
297
            '   %s\n' % (
 
298
                    bzrlib.__path__[0],))
 
299
        self.stream.write(
 
300
            '   bzr-%s python-%s %s\n' % (
 
301
                    bzrlib.version_string,
 
302
                    bzrlib._format_version_tuple(sys.version_info),
 
303
                    platform.platform(aliased=1),
 
304
                    ))
 
305
        self.stream.write('\n')
 
306
 
200
307
    def _recordTestStartTime(self):
201
308
        """Record that a test has started."""
202
309
        self._start_time = time.time()
214
321
        Called from the TestCase run() method when the test
215
322
        fails with an unexpected error.
216
323
        """
217
 
        self._testConcluded(test)
218
 
        if isinstance(err[1], TestSkipped):
219
 
            return self._addSkipped(test, err)
220
 
        elif isinstance(err[1], UnavailableFeature):
221
 
            return self.addNotSupported(test, err[1].args[0])
222
 
        else:
223
 
            unittest.TestResult.addError(self, test, err)
224
 
            self.error_count += 1
225
 
            self.report_error(test, err)
226
 
            if self.stop_early:
227
 
                self.stop()
228
 
            self._cleanupLogFile(test)
 
324
        self._post_mortem()
 
325
        unittest.TestResult.addError(self, test, err)
 
326
        self.error_count += 1
 
327
        self.report_error(test, err)
 
328
        if self.stop_early:
 
329
            self.stop()
 
330
        self._cleanupLogFile(test)
229
331
 
230
332
    def addFailure(self, test, err):
231
333
        """Tell result that test failed.
233
335
        Called from the TestCase run() method when the test
234
336
        fails because e.g. an assert() method failed.
235
337
        """
236
 
        self._testConcluded(test)
237
 
        if isinstance(err[1], KnownFailure):
238
 
            return self._addKnownFailure(test, err)
239
 
        else:
240
 
            unittest.TestResult.addFailure(self, test, err)
241
 
            self.failure_count += 1
242
 
            self.report_failure(test, err)
243
 
            if self.stop_early:
244
 
                self.stop()
245
 
            self._cleanupLogFile(test)
 
338
        self._post_mortem()
 
339
        unittest.TestResult.addFailure(self, test, err)
 
340
        self.failure_count += 1
 
341
        self.report_failure(test, err)
 
342
        if self.stop_early:
 
343
            self.stop()
 
344
        self._cleanupLogFile(test)
246
345
 
247
 
    def addSuccess(self, test):
 
346
    def addSuccess(self, test, details=None):
248
347
        """Tell result that test completed successfully.
249
348
 
250
349
        Called from the TestCase run()
251
350
        """
252
 
        self._testConcluded(test)
253
351
        if self._bench_history is not None:
254
 
            benchmark_time = self._extractBenchmarkTime(test)
 
352
            benchmark_time = self._extractBenchmarkTime(test, details)
255
353
            if benchmark_time is not None:
256
354
                self._bench_history.write("%s %s\n" % (
257
355
                    self._formatTime(benchmark_time),
261
359
        unittest.TestResult.addSuccess(self, test)
262
360
        test._log_contents = ''
263
361
 
264
 
    def _testConcluded(self, test):
265
 
        """Common code when a test has finished.
266
 
 
267
 
        Called regardless of whether it succeded, failed, etc.
268
 
        """
269
 
        pass
270
 
 
271
 
    def _addKnownFailure(self, test, err):
 
362
    def addExpectedFailure(self, test, err):
272
363
        self.known_failure_count += 1
273
364
        self.report_known_failure(test, err)
274
365
 
276
367
        """The test will not be run because of a missing feature.
277
368
        """
278
369
        # this can be called in two different ways: it may be that the
279
 
        # test started running, and then raised (through addError) 
 
370
        # test started running, and then raised (through requireFeature)
280
371
        # UnavailableFeature.  Alternatively this method can be called
281
 
        # while probing for features before running the tests; in that
282
 
        # case we will see startTest and stopTest, but the test will never
283
 
        # actually run.
 
372
        # while probing for features before running the test code proper; in
 
373
        # that case we will see startTest and stopTest, but the test will
 
374
        # never actually run.
284
375
        self.unsupported.setdefault(str(feature), 0)
285
376
        self.unsupported[str(feature)] += 1
286
377
        self.report_unsupported(test, feature)
287
378
 
288
 
    def _addSkipped(self, test, skip_excinfo):
289
 
        if isinstance(skip_excinfo[1], TestNotApplicable):
290
 
            self.not_applicable_count += 1
291
 
            self.report_not_applicable(test, skip_excinfo)
292
 
        else:
293
 
            self.skip_count += 1
294
 
            self.report_skip(test, skip_excinfo)
295
 
        try:
296
 
            test.tearDown()
297
 
        except KeyboardInterrupt:
298
 
            raise
299
 
        except:
300
 
            self.addError(test, test._exc_info())
301
 
        else:
302
 
            # seems best to treat this as success from point-of-view of unittest
303
 
            # -- it actually does nothing so it barely matters :)
304
 
            unittest.TestResult.addSuccess(self, test)
305
 
            test._log_contents = ''
306
 
 
307
 
    def printErrorList(self, flavour, errors):
308
 
        for test, err in errors:
309
 
            self.stream.writeln(self.separator1)
310
 
            self.stream.write("%s: " % flavour)
311
 
            self.stream.writeln(self.getDescription(test))
312
 
            if getattr(test, '_get_log', None) is not None:
313
 
                self.stream.write('\n')
314
 
                self.stream.write(
315
 
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
316
 
                self.stream.write('\n')
317
 
                self.stream.write(test._get_log())
318
 
                self.stream.write('\n')
319
 
                self.stream.write(
320
 
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
321
 
                self.stream.write('\n')
322
 
            self.stream.writeln(self.separator2)
323
 
            self.stream.writeln("%s" % err)
324
 
 
325
 
    def finished(self):
326
 
        pass
 
379
    def addSkip(self, test, reason):
 
380
        """A test has not run for 'reason'."""
 
381
        self.skip_count += 1
 
382
        self.report_skip(test, reason)
 
383
 
 
384
    def addNotApplicable(self, test, reason):
 
385
        self.not_applicable_count += 1
 
386
        self.report_not_applicable(test, reason)
 
387
 
 
388
    def _post_mortem(self):
 
389
        """Start a PDB post mortem session."""
 
390
        if os.environ.get('BZR_TEST_PDB', None):
 
391
            import pdb;pdb.post_mortem()
 
392
 
 
393
    def progress(self, offset, whence):
 
394
        """The test is adjusting the count of tests to run."""
 
395
        if whence == SUBUNIT_SEEK_SET:
 
396
            self.num_tests = offset
 
397
        elif whence == SUBUNIT_SEEK_CUR:
 
398
            self.num_tests += offset
 
399
        else:
 
400
            raise errors.BzrError("Unknown whence %r" % whence)
327
401
 
328
402
    def report_cleaning_up(self):
329
403
        pass
330
404
 
 
405
    def startTestRun(self):
 
406
        self.startTime = time.time()
 
407
 
331
408
    def report_success(self, test):
332
409
        pass
333
410
 
342
419
 
343
420
    def __init__(self, stream, descriptions, verbosity,
344
421
                 bench_history=None,
345
 
                 num_tests=None,
346
422
                 pb=None,
 
423
                 strict=None,
347
424
                 ):
348
425
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
349
 
            bench_history, num_tests)
350
 
        if pb is None:
351
 
            self.pb = self.ui.nested_progress_bar()
352
 
            self._supplied_pb = False
353
 
        else:
354
 
            self.pb = pb
355
 
            self._supplied_pb = True
 
426
            bench_history, strict)
 
427
        # We no longer pass them around, but just rely on the UIFactory stack
 
428
        # for state
 
429
        if pb is not None:
 
430
            warnings.warn("Passing pb to TextTestResult is deprecated")
 
431
        self.pb = self.ui.nested_progress_bar()
356
432
        self.pb.show_pct = False
357
433
        self.pb.show_spinner = False
358
434
        self.pb.show_eta = False,
359
435
        self.pb.show_count = False
360
436
        self.pb.show_bar = False
361
 
 
362
 
    def report_starting(self):
363
 
        self.pb.update('[test 0/%d] starting...' % (self.num_tests))
 
437
        self.pb.update_latency = 0
 
438
        self.pb.show_transport_activity = False
 
439
 
 
440
    def stopTestRun(self):
 
441
        # called when the tests that are going to run have run
 
442
        self.pb.clear()
 
443
        self.pb.finished()
 
444
        super(TextTestResult, self).stopTestRun()
 
445
 
 
446
    def startTestRun(self):
 
447
        super(TextTestResult, self).startTestRun()
 
448
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
 
449
 
 
450
    def printErrors(self):
 
451
        # clear the pb to make room for the error listing
 
452
        self.pb.clear()
 
453
        super(TextTestResult, self).printErrors()
364
454
 
365
455
    def _progress_prefix_text(self):
366
456
        # the longer this text, the less space we have to show the test
372
462
        ##     a += ', %d skip' % self.skip_count
373
463
        ## if self.known_failure_count:
374
464
        ##     a += '+%dX' % self.known_failure_count
375
 
        if self.num_tests is not None:
 
465
        if self.num_tests:
376
466
            a +='/%d' % self.num_tests
377
467
        a += ' in '
378
468
        runtime = time.time() - self._overall_start_time
380
470
            a += '%dm%ds' % (runtime / 60, runtime % 60)
381
471
        else:
382
472
            a += '%ds' % runtime
383
 
        if self.error_count:
384
 
            a += ', %d err' % self.error_count
385
 
        if self.failure_count:
386
 
            a += ', %d fail' % self.failure_count
387
 
        if self.unsupported:
388
 
            a += ', %d missing' % len(self.unsupported)
 
473
        total_fail_count = self.error_count + self.failure_count
 
474
        if total_fail_count:
 
475
            a += ', %d failed' % total_fail_count
 
476
        # if self.unsupported:
 
477
        #     a += ', %d missing' % len(self.unsupported)
389
478
        a += ']'
390
479
        return a
391
480
 
393
482
        self.count += 1
394
483
        self.pb.update(
395
484
                self._progress_prefix_text()
396
 
                + ' ' 
 
485
                + ' '
397
486
                + self._shortened_test_description(test))
398
487
 
399
488
    def _test_description(self, test):
400
489
        return self._shortened_test_description(test)
401
490
 
402
491
    def report_error(self, test, err):
403
 
        self.pb.note('ERROR: %s\n    %s\n', 
 
492
        self.stream.write('ERROR: %s\n    %s\n' % (
404
493
            self._test_description(test),
405
494
            err[1],
406
 
            )
 
495
            ))
407
496
 
408
497
    def report_failure(self, test, err):
409
 
        self.pb.note('FAIL: %s\n    %s\n', 
 
498
        self.stream.write('FAIL: %s\n    %s\n' % (
410
499
            self._test_description(test),
411
500
            err[1],
412
 
            )
 
501
            ))
413
502
 
414
503
    def report_known_failure(self, test, err):
415
 
        self.pb.note('XFAIL: %s\n%s\n',
416
 
            self._test_description(test), err[1])
417
 
 
418
 
    def report_skip(self, test, skip_excinfo):
419
 
        pass
420
 
 
421
 
    def report_not_applicable(self, test, skip_excinfo):
 
504
        pass
 
505
 
 
506
    def report_skip(self, test, reason):
 
507
        pass
 
508
 
 
509
    def report_not_applicable(self, test, reason):
422
510
        pass
423
511
 
424
512
    def report_unsupported(self, test, feature):
425
513
        """test cannot be run because feature is missing."""
426
 
                  
 
514
 
427
515
    def report_cleaning_up(self):
428
 
        self.pb.update('cleaning up...')
429
 
 
430
 
    def finished(self):
431
 
        if not self._supplied_pb:
432
 
            self.pb.finished()
 
516
        self.pb.update('Cleaning up')
433
517
 
434
518
 
435
519
class VerboseTestResult(ExtendedTestResult):
443
527
            result = a_string
444
528
        return result.ljust(final_width)
445
529
 
446
 
    def report_starting(self):
 
530
    def startTestRun(self):
 
531
        super(VerboseTestResult, self).startTestRun()
447
532
        self.stream.write('running %d tests...\n' % self.num_tests)
448
533
 
449
534
    def report_test_start(self, test):
450
535
        self.count += 1
451
536
        name = self._shortened_test_description(test)
452
 
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
453
 
        # numbers, plus a trailing blank
454
 
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
455
 
        self.stream.write(self._ellipsize_to_right(name,
456
 
                          osutils.terminal_width()-30))
 
537
        width = osutils.terminal_width()
 
538
        if width is not None:
 
539
            # width needs space for 6 char status, plus 1 for slash, plus an
 
540
            # 11-char time string, plus a trailing blank
 
541
            # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on
 
542
            # space
 
543
            self.stream.write(self._ellipsize_to_right(name, width-18))
 
544
        else:
 
545
            self.stream.write(name)
457
546
        self.stream.flush()
458
547
 
459
548
    def _error_summary(self, err):
484
573
        # used to show the output in PQM.
485
574
        self.stream.flush()
486
575
 
487
 
    def report_skip(self, test, skip_excinfo):
 
576
    def report_skip(self, test, reason):
488
577
        self.stream.writeln(' SKIP %s\n%s'
489
 
                % (self._testTimeString(test),
490
 
                   self._error_summary(skip_excinfo)))
 
578
                % (self._testTimeString(test), reason))
491
579
 
492
 
    def report_not_applicable(self, test, skip_excinfo):
493
 
        self.stream.writeln('  N/A %s\n%s'
494
 
                % (self._testTimeString(test),
495
 
                   self._error_summary(skip_excinfo)))
 
580
    def report_not_applicable(self, test, reason):
 
581
        self.stream.writeln('  N/A %s\n    %s'
 
582
                % (self._testTimeString(test), reason))
496
583
 
497
584
    def report_unsupported(self, test, feature):
498
585
        """test cannot be run because feature is missing."""
508
595
                 descriptions=0,
509
596
                 verbosity=1,
510
597
                 bench_history=None,
511
 
                 list_only=False
 
598
                 strict=False,
 
599
                 result_decorators=None,
512
600
                 ):
 
601
        """Create a TextTestRunner.
 
602
 
 
603
        :param result_decorators: An optional list of decorators to apply
 
604
            to the result object being used by the runner. Decorators are
 
605
            applied left to right - the first element in the list is the 
 
606
            innermost decorator.
 
607
        """
 
608
        # stream may know claim to know to write unicode strings, but in older
 
609
        # pythons this goes sufficiently wrong that it is a bad idea. (
 
610
        # specifically a built in file with encoding 'UTF-8' will still try
 
611
        # to encode using ascii.
 
612
        new_encoding = osutils.get_terminal_encoding()
 
613
        codec = codecs.lookup(new_encoding)
 
614
        if type(codec) is tuple:
 
615
            # Python 2.4
 
616
            encode = codec[0]
 
617
        else:
 
618
            encode = codec.encode
 
619
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
620
        stream.encoding = new_encoding
513
621
        self.stream = unittest._WritelnDecorator(stream)
514
622
        self.descriptions = descriptions
515
623
        self.verbosity = verbosity
516
624
        self._bench_history = bench_history
517
 
        self.list_only = list_only
 
625
        self._strict = strict
 
626
        self._result_decorators = result_decorators or []
518
627
 
519
628
    def run(self, test):
520
629
        "Run the given test case or test suite."
521
 
        startTime = time.time()
522
630
        if self.verbosity == 1:
523
631
            result_class = TextTestResult
524
632
        elif self.verbosity >= 2:
525
633
            result_class = VerboseTestResult
526
 
        result = result_class(self.stream,
 
634
        original_result = result_class(self.stream,
527
635
                              self.descriptions,
528
636
                              self.verbosity,
529
637
                              bench_history=self._bench_history,
530
 
                              num_tests=test.countTestCases(),
 
638
                              strict=self._strict,
531
639
                              )
532
 
        result.stop_early = self.stop_on_failure
533
 
        result.report_starting()
534
 
        if self.list_only:
535
 
            if self.verbosity >= 2:
536
 
                self.stream.writeln("Listing tests only ...\n")
537
 
            run = 0
538
 
            for t in iter_suite_tests(test):
539
 
                self.stream.writeln("%s" % (t.id()))
540
 
                run += 1
541
 
            actionTaken = "Listed"
542
 
        else: 
 
640
        # Signal to result objects that look at stop early policy to stop,
 
641
        original_result.stop_early = self.stop_on_failure
 
642
        result = original_result
 
643
        for decorator in self._result_decorators:
 
644
            result = decorator(result)
 
645
            result.stop_early = self.stop_on_failure
 
646
        result.startTestRun()
 
647
        try:
543
648
            test.run(result)
544
 
            run = result.testsRun
545
 
            actionTaken = "Ran"
546
 
        stopTime = time.time()
547
 
        timeTaken = stopTime - startTime
548
 
        result.printErrors()
549
 
        self.stream.writeln(result.separator2)
550
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
551
 
                            run, run != 1 and "s" or "", timeTaken))
552
 
        self.stream.writeln()
553
 
        if not result.wasSuccessful():
554
 
            self.stream.write("FAILED (")
555
 
            failed, errored = map(len, (result.failures, result.errors))
556
 
            if failed:
557
 
                self.stream.write("failures=%d" % failed)
558
 
            if errored:
559
 
                if failed: self.stream.write(", ")
560
 
                self.stream.write("errors=%d" % errored)
561
 
            if result.known_failure_count:
562
 
                if failed or errored: self.stream.write(", ")
563
 
                self.stream.write("known_failure_count=%d" %
564
 
                    result.known_failure_count)
565
 
            self.stream.writeln(")")
566
 
        else:
567
 
            if result.known_failure_count:
568
 
                self.stream.writeln("OK (known_failures=%d)" %
569
 
                    result.known_failure_count)
570
 
            else:
571
 
                self.stream.writeln("OK")
572
 
        if result.skip_count > 0:
573
 
            skipped = result.skip_count
574
 
            self.stream.writeln('%d test%s skipped' %
575
 
                                (skipped, skipped != 1 and "s" or ""))
576
 
        if result.unsupported:
577
 
            for feature, count in sorted(result.unsupported.items()):
578
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
579
 
                    (feature, count))
580
 
        result.finished()
581
 
        return result
 
649
        finally:
 
650
            result.stopTestRun()
 
651
        # higher level code uses our extended protocol to determine
 
652
        # what exit code to give.
 
653
        return original_result
582
654
 
583
655
 
584
656
def iter_suite_tests(suite):
585
657
    """Return all tests in a suite, recursing through nested suites"""
586
 
    for item in suite._tests:
587
 
        if isinstance(item, unittest.TestCase):
588
 
            yield item
589
 
        elif isinstance(item, unittest.TestSuite):
 
658
    if isinstance(suite, unittest.TestCase):
 
659
        yield suite
 
660
    elif isinstance(suite, unittest.TestSuite):
 
661
        for item in suite:
590
662
            for r in iter_suite_tests(item):
591
663
                yield r
592
 
        else:
593
 
            raise Exception('unknown object %r inside test suite %r'
594
 
                            % (item, suite))
595
 
 
596
 
 
597
 
class TestSkipped(Exception):
598
 
    """Indicates that a test was intentionally skipped, rather than failing."""
 
664
    else:
 
665
        raise Exception('unknown type %r for object %r'
 
666
                        % (type(suite), suite))
 
667
 
 
668
 
 
669
TestSkipped = testtools.testcase.TestSkipped
599
670
 
600
671
 
601
672
class TestNotApplicable(TestSkipped):
602
673
    """A test is not applicable to the situation where it was run.
603
674
 
604
 
    This is only normally raised by parameterized tests, if they find that 
605
 
    the instance they're constructed upon does not support one aspect 
 
675
    This is only normally raised by parameterized tests, if they find that
 
676
    the instance they're constructed upon does not support one aspect
606
677
    of its interface.
607
678
    """
608
679
 
609
680
 
610
 
class KnownFailure(AssertionError):
611
 
    """Indicates that a test failed in a precisely expected manner.
612
 
 
613
 
    Such failures dont block the whole test suite from passing because they are
614
 
    indicators of partially completed code or of future work. We have an
615
 
    explicit error for them so that we can ensure that they are always visible:
616
 
    KnownFailures are always shown in the output of bzr selftest.
617
 
    """
 
681
# traceback._some_str fails to format exceptions that have the default
 
682
# __str__ which does an implicit ascii conversion. However, repr() on those
 
683
# objects works, for all that its not quite what the doctor may have ordered.
 
684
def _clever_some_str(value):
 
685
    try:
 
686
        return str(value)
 
687
    except:
 
688
        try:
 
689
            return repr(value).replace('\\n', '\n')
 
690
        except:
 
691
            return '<unprintable %s object>' % type(value).__name__
 
692
 
 
693
traceback._some_str = _clever_some_str
 
694
 
 
695
 
 
696
# deprecated - use self.knownFailure(), or self.expectFailure.
 
697
KnownFailure = testtools.testcase._ExpectedFailure
618
698
 
619
699
 
620
700
class UnavailableFeature(Exception):
621
701
    """A feature required for this test was not available.
622
702
 
 
703
    This can be considered a specialised form of SkippedTest.
 
704
 
623
705
    The feature should be used to construct the exception.
624
706
    """
625
707
 
626
708
 
627
 
class CommandFailed(Exception):
628
 
    pass
629
 
 
630
 
 
631
709
class StringIOWrapper(object):
632
710
    """A wrapper around cStringIO which just adds an encoding attribute.
633
 
    
 
711
 
634
712
    Internally we can check sys.stdout to see what the output encoding
635
713
    should be. However, cStringIO has no encoding attribute that we can
636
714
    set. So we wrap it instead.
654
732
            return setattr(self._cstring, name, val)
655
733
 
656
734
 
657
 
class TestUIFactory(ui.CLIUIFactory):
 
735
class TestUIFactory(TextUIFactory):
658
736
    """A UI Factory for testing.
659
737
 
660
738
    Hide the progress bar but emit note()s.
661
739
    Redirect stdin.
662
740
    Allows get_password to be tested without real tty attached.
 
741
 
 
742
    See also CannedInputUIFactory which lets you provide programmatic input in
 
743
    a structured way.
663
744
    """
 
745
    # TODO: Capture progress events at the model level and allow them to be
 
746
    # observed by tests that care.
 
747
    #
 
748
    # XXX: Should probably unify more with CannedInputUIFactory or a
 
749
    # particular configuration of TextUIFactory, or otherwise have a clearer
 
750
    # idea of how they're supposed to be different.
 
751
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
664
752
 
665
 
    def __init__(self,
666
 
                 stdout=None,
667
 
                 stderr=None,
668
 
                 stdin=None):
669
 
        super(TestUIFactory, self).__init__()
 
753
    def __init__(self, stdout=None, stderr=None, stdin=None):
670
754
        if stdin is not None:
671
755
            # We use a StringIOWrapper to be able to test various
672
756
            # encodings, but the user is still responsible to
673
757
            # encode the string and to set the encoding attribute
674
758
            # of StringIOWrapper.
675
 
            self.stdin = StringIOWrapper(stdin)
676
 
        if stdout is None:
677
 
            self.stdout = sys.stdout
678
 
        else:
679
 
            self.stdout = stdout
680
 
        if stderr is None:
681
 
            self.stderr = sys.stderr
682
 
        else:
683
 
            self.stderr = stderr
684
 
 
685
 
    def clear(self):
686
 
        """See progress.ProgressBar.clear()."""
687
 
 
688
 
    def clear_term(self):
689
 
        """See progress.ProgressBar.clear_term()."""
690
 
 
691
 
    def clear_term(self):
692
 
        """See progress.ProgressBar.clear_term()."""
693
 
 
694
 
    def finished(self):
695
 
        """See progress.ProgressBar.finished()."""
696
 
 
697
 
    def note(self, fmt_string, *args, **kwargs):
698
 
        """See progress.ProgressBar.note()."""
699
 
        self.stdout.write((fmt_string + "\n") % args)
700
 
 
701
 
    def progress_bar(self):
702
 
        return self
703
 
 
704
 
    def nested_progress_bar(self):
705
 
        return self
706
 
 
707
 
    def update(self, message, count=None, total=None):
708
 
        """See progress.ProgressBar.update()."""
709
 
 
710
 
    def get_non_echoed_password(self, prompt):
 
759
            stdin = StringIOWrapper(stdin)
 
760
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
 
761
 
 
762
    def get_non_echoed_password(self):
711
763
        """Get password from stdin without trying to handle the echo mode"""
712
 
        if prompt:
713
 
            self.stdout.write(prompt.encode(self.stdout.encoding, 'replace'))
714
764
        password = self.stdin.readline()
715
765
        if not password:
716
766
            raise EOFError
718
768
            password = password[:-1]
719
769
        return password
720
770
 
721
 
 
722
 
def _report_leaked_threads():
723
 
    bzrlib.trace.warning('%s is leaking threads among %d leaking tests',
724
 
                         TestCase._first_thread_leaker_id,
725
 
                         TestCase._leaking_threads_tests)
726
 
 
727
 
 
728
 
class TestCase(unittest.TestCase):
 
771
    def make_progress_view(self):
 
772
        return NullProgressView()
 
773
 
 
774
 
 
775
class TestCase(testtools.TestCase):
729
776
    """Base class for bzr unit tests.
730
 
    
731
 
    Tests that need access to disk resources should subclass 
 
777
 
 
778
    Tests that need access to disk resources should subclass
732
779
    TestCaseInTempDir not TestCase.
733
780
 
734
781
    Error and debug log messages are redirected from their usual
736
783
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
737
784
    so that it can also capture file IO.  When the test completes this file
738
785
    is read into memory and removed from disk.
739
 
       
 
786
 
740
787
    There are also convenience functions to invoke bzr's command-line
741
788
    routine, and to build and check bzr trees.
742
 
   
 
789
 
743
790
    In addition to the usual method of overriding tearDown(), this class also
744
791
    allows subclasses to register functions into the _cleanups list, which is
745
792
    run in order as the object is torn down.  It's less likely this will be
750
797
    _leaking_threads_tests = 0
751
798
    _first_thread_leaker_id = None
752
799
    _log_file_name = None
753
 
    _log_contents = ''
754
 
    _keep_log_file = False
755
800
    # record lsprof data when performing benchmark calls.
756
801
    _gather_lsprof_in_benchmarks = False
757
 
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
758
 
                     '_log_contents', '_log_file_name', '_benchtime',
759
 
                     '_TestCase__testMethodName')
760
802
 
761
803
    def __init__(self, methodName='testMethod'):
762
804
        super(TestCase, self).__init__(methodName)
763
805
        self._cleanups = []
 
806
        self._directory_isolation = True
 
807
        self.exception_handlers.insert(0,
 
808
            (UnavailableFeature, self._do_unsupported_or_skip))
 
809
        self.exception_handlers.insert(0,
 
810
            (TestNotApplicable, self._do_not_applicable))
764
811
 
765
812
    def setUp(self):
766
 
        unittest.TestCase.setUp(self)
 
813
        super(TestCase, self).setUp()
 
814
        for feature in getattr(self, '_test_needs_features', []):
 
815
            self.requireFeature(feature)
 
816
        self._log_contents = None
 
817
        self.addDetail("log", content.Content(content.ContentType("text",
 
818
            "plain", {"charset": "utf8"}),
 
819
            lambda:[self._get_log(keep_log_file=True)]))
767
820
        self._cleanEnvironment()
768
821
        self._silenceUI()
769
822
        self._startLogFile()
770
823
        self._benchcalls = []
771
824
        self._benchtime = None
772
825
        self._clear_hooks()
 
826
        self._track_transports()
 
827
        self._track_locks()
773
828
        self._clear_debug_flags()
774
829
        TestCase._active_threads = threading.activeCount()
775
830
        self.addCleanup(self._check_leaked_threads)
776
831
 
 
832
    def debug(self):
 
833
        # debug a frame up.
 
834
        import pdb
 
835
        pdb.Pdb().set_trace(sys._getframe().f_back)
 
836
 
777
837
    def _check_leaked_threads(self):
778
838
        active = threading.activeCount()
779
839
        leaked_threads = active - TestCase._active_threads
780
840
        TestCase._active_threads = active
781
 
        if leaked_threads:
 
841
        # If some tests make the number of threads *decrease*, we'll consider
 
842
        # that they are just observing old threads dieing, not agressively kill
 
843
        # random threads. So we don't report these tests as leaking. The risk
 
844
        # is that we have false positives that way (the test see 2 threads
 
845
        # going away but leak one) but it seems less likely than the actual
 
846
        # false positives (the test see threads going away and does not leak).
 
847
        if leaked_threads > 0:
782
848
            TestCase._leaking_threads_tests += 1
783
849
            if TestCase._first_thread_leaker_id is None:
784
850
                TestCase._first_thread_leaker_id = self.id()
785
 
                # we're not specifically told when all tests are finished.
786
 
                # This will do. We use a function to avoid keeping a reference
787
 
                # to a TestCase object.
788
 
                atexit.register(_report_leaked_threads)
789
851
 
790
852
    def _clear_debug_flags(self):
791
853
        """Prevent externally set debug flags affecting tests.
792
 
        
 
854
 
793
855
        Tests that want to use debug flags can just set them in the
794
856
        debug_flags set during setup/teardown.
795
857
        """
 
858
        # Start with a copy of the current debug flags we can safely modify.
 
859
        self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
796
860
        if 'allow_debug' not in selftest_debug_flags:
797
 
            self._preserved_debug_flags = set(debug.debug_flags)
798
861
            debug.debug_flags.clear()
799
 
            self.addCleanup(self._restore_debug_flags)
 
862
        if 'disable_lock_checks' not in selftest_debug_flags:
 
863
            debug.debug_flags.add('strict_locks')
800
864
 
801
865
    def _clear_hooks(self):
802
866
        # prevent hooks affecting tests
803
 
        import bzrlib.branch
804
 
        import bzrlib.smart.client
805
 
        import bzrlib.smart.server
806
 
        self._preserved_hooks = {
807
 
            bzrlib.branch.Branch: bzrlib.branch.Branch.hooks,
808
 
            bzrlib.mutabletree.MutableTree: bzrlib.mutabletree.MutableTree.hooks,
809
 
            bzrlib.smart.client._SmartClient: bzrlib.smart.client._SmartClient.hooks,
810
 
            bzrlib.smart.server.SmartTCPServer: bzrlib.smart.server.SmartTCPServer.hooks,
811
 
            }
 
867
        self._preserved_hooks = {}
 
868
        for key, factory in hooks.known_hooks.items():
 
869
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
870
            current_hooks = hooks.known_hooks_key_to_object(key)
 
871
            self._preserved_hooks[parent] = (name, current_hooks)
812
872
        self.addCleanup(self._restoreHooks)
813
 
        # reset all hooks to an empty instance of the appropriate type
814
 
        bzrlib.branch.Branch.hooks = bzrlib.branch.BranchHooks()
815
 
        bzrlib.smart.client._SmartClient.hooks = bzrlib.smart.client.SmartClientHooks()
816
 
        bzrlib.smart.server.SmartTCPServer.hooks = bzrlib.smart.server.SmartServerHooks()
 
873
        for key, factory in hooks.known_hooks.items():
 
874
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
875
            setattr(parent, name, factory())
 
876
        # this hook should always be installed
 
877
        request._install_hook()
 
878
 
 
879
    def disable_directory_isolation(self):
 
880
        """Turn off directory isolation checks."""
 
881
        self._directory_isolation = False
 
882
 
 
883
    def enable_directory_isolation(self):
 
884
        """Enable directory isolation checks."""
 
885
        self._directory_isolation = True
817
886
 
818
887
    def _silenceUI(self):
819
888
        """Turn off UI for duration of test"""
820
889
        # by default the UI is off; tests can turn it on if they want it.
821
 
        saved = ui.ui_factory
822
 
        def _restore():
823
 
            ui.ui_factory = saved
824
 
        ui.ui_factory = ui.SilentUIFactory()
825
 
        self.addCleanup(_restore)
 
890
        self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
 
891
 
 
892
    def _check_locks(self):
 
893
        """Check that all lock take/release actions have been paired."""
 
894
        # We always check for mismatched locks. If a mismatch is found, we
 
895
        # fail unless -Edisable_lock_checks is supplied to selftest, in which
 
896
        # case we just print a warning.
 
897
        # unhook:
 
898
        acquired_locks = [lock for action, lock in self._lock_actions
 
899
                          if action == 'acquired']
 
900
        released_locks = [lock for action, lock in self._lock_actions
 
901
                          if action == 'released']
 
902
        broken_locks = [lock for action, lock in self._lock_actions
 
903
                        if action == 'broken']
 
904
        # trivially, given the tests for lock acquistion and release, if we
 
905
        # have as many in each list, it should be ok. Some lock tests also
 
906
        # break some locks on purpose and should be taken into account by
 
907
        # considering that breaking a lock is just a dirty way of releasing it.
 
908
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
 
909
            message = ('Different number of acquired and '
 
910
                       'released or broken locks. (%s, %s + %s)' %
 
911
                       (acquired_locks, released_locks, broken_locks))
 
912
            if not self._lock_check_thorough:
 
913
                # Rather than fail, just warn
 
914
                print "Broken test %s: %s" % (self, message)
 
915
                return
 
916
            self.fail(message)
 
917
 
 
918
    def _track_locks(self):
 
919
        """Track lock activity during tests."""
 
920
        self._lock_actions = []
 
921
        if 'disable_lock_checks' in selftest_debug_flags:
 
922
            self._lock_check_thorough = False
 
923
        else:
 
924
            self._lock_check_thorough = True
 
925
 
 
926
        self.addCleanup(self._check_locks)
 
927
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
 
928
                                                self._lock_acquired, None)
 
929
        _mod_lock.Lock.hooks.install_named_hook('lock_released',
 
930
                                                self._lock_released, None)
 
931
        _mod_lock.Lock.hooks.install_named_hook('lock_broken',
 
932
                                                self._lock_broken, None)
 
933
 
 
934
    def _lock_acquired(self, result):
 
935
        self._lock_actions.append(('acquired', result))
 
936
 
 
937
    def _lock_released(self, result):
 
938
        self._lock_actions.append(('released', result))
 
939
 
 
940
    def _lock_broken(self, result):
 
941
        self._lock_actions.append(('broken', result))
 
942
 
 
943
    def permit_dir(self, name):
 
944
        """Permit a directory to be used by this test. See permit_url."""
 
945
        name_transport = get_transport(name)
 
946
        self.permit_url(name)
 
947
        self.permit_url(name_transport.base)
 
948
 
 
949
    def permit_url(self, url):
 
950
        """Declare that url is an ok url to use in this test.
 
951
        
 
952
        Do this for memory transports, temporary test directory etc.
 
953
        
 
954
        Do not do this for the current working directory, /tmp, or any other
 
955
        preexisting non isolated url.
 
956
        """
 
957
        if not url.endswith('/'):
 
958
            url += '/'
 
959
        self._bzr_selftest_roots.append(url)
 
960
 
 
961
    def permit_source_tree_branch_repo(self):
 
962
        """Permit the source tree bzr is running from to be opened.
 
963
 
 
964
        Some code such as bzrlib.version attempts to read from the bzr branch
 
965
        that bzr is executing from (if any). This method permits that directory
 
966
        to be used in the test suite.
 
967
        """
 
968
        path = self.get_source_path()
 
969
        self.record_directory_isolation()
 
970
        try:
 
971
            try:
 
972
                workingtree.WorkingTree.open(path)
 
973
            except (errors.NotBranchError, errors.NoWorkingTree):
 
974
                return
 
975
        finally:
 
976
            self.enable_directory_isolation()
 
977
 
 
978
    def _preopen_isolate_transport(self, transport):
 
979
        """Check that all transport openings are done in the test work area."""
 
980
        while isinstance(transport, pathfilter.PathFilteringTransport):
 
981
            # Unwrap pathfiltered transports
 
982
            transport = transport.server.backing_transport.clone(
 
983
                transport._filter('.'))
 
984
        url = transport.base
 
985
        # ReadonlySmartTCPServer_for_testing decorates the backing transport
 
986
        # urls it is given by prepending readonly+. This is appropriate as the
 
987
        # client shouldn't know that the server is readonly (or not readonly).
 
988
        # We could register all servers twice, with readonly+ prepending, but
 
989
        # that makes for a long list; this is about the same but easier to
 
990
        # read.
 
991
        if url.startswith('readonly+'):
 
992
            url = url[len('readonly+'):]
 
993
        self._preopen_isolate_url(url)
 
994
 
 
995
    def _preopen_isolate_url(self, url):
 
996
        if not self._directory_isolation:
 
997
            return
 
998
        if self._directory_isolation == 'record':
 
999
            self._bzr_selftest_roots.append(url)
 
1000
            return
 
1001
        # This prevents all transports, including e.g. sftp ones backed on disk
 
1002
        # from working unless they are explicitly granted permission. We then
 
1003
        # depend on the code that sets up test transports to check that they are
 
1004
        # appropriately isolated and enable their use by calling
 
1005
        # self.permit_transport()
 
1006
        if not osutils.is_inside_any(self._bzr_selftest_roots, url):
 
1007
            raise errors.BzrError("Attempt to escape test isolation: %r %r"
 
1008
                % (url, self._bzr_selftest_roots))
 
1009
 
 
1010
    def record_directory_isolation(self):
 
1011
        """Gather accessed directories to permit later access.
 
1012
        
 
1013
        This is used for tests that access the branch bzr is running from.
 
1014
        """
 
1015
        self._directory_isolation = "record"
 
1016
 
 
1017
    def start_server(self, transport_server, backing_server=None):
 
1018
        """Start transport_server for this test.
 
1019
 
 
1020
        This starts the server, registers a cleanup for it and permits the
 
1021
        server's urls to be used.
 
1022
        """
 
1023
        if backing_server is None:
 
1024
            transport_server.start_server()
 
1025
        else:
 
1026
            transport_server.start_server(backing_server)
 
1027
        self.addCleanup(transport_server.stop_server)
 
1028
        # Obtain a real transport because if the server supplies a password, it
 
1029
        # will be hidden from the base on the client side.
 
1030
        t = get_transport(transport_server.get_url())
 
1031
        # Some transport servers effectively chroot the backing transport;
 
1032
        # others like SFTPServer don't - users of the transport can walk up the
 
1033
        # transport to read the entire backing transport. This wouldn't matter
 
1034
        # except that the workdir tests are given - and that they expect the
 
1035
        # server's url to point at - is one directory under the safety net. So
 
1036
        # Branch operations into the transport will attempt to walk up one
 
1037
        # directory. Chrooting all servers would avoid this but also mean that
 
1038
        # we wouldn't be testing directly against non-root urls. Alternatively
 
1039
        # getting the test framework to start the server with a backing server
 
1040
        # at the actual safety net directory would work too, but this then
 
1041
        # means that the self.get_url/self.get_transport methods would need
 
1042
        # to transform all their results. On balance its cleaner to handle it
 
1043
        # here, and permit a higher url when we have one of these transports.
 
1044
        if t.base.endswith('/work/'):
 
1045
            # we have safety net/test root/work
 
1046
            t = t.clone('../..')
 
1047
        elif isinstance(transport_server,
 
1048
                        test_server.SmartTCPServer_for_testing):
 
1049
            # The smart server adds a path similar to work, which is traversed
 
1050
            # up from by the client. But the server is chrooted - the actual
 
1051
            # backing transport is not escaped from, and VFS requests to the
 
1052
            # root will error (because they try to escape the chroot).
 
1053
            t2 = t.clone('..')
 
1054
            while t2.base != t.base:
 
1055
                t = t2
 
1056
                t2 = t.clone('..')
 
1057
        self.permit_url(t.base)
 
1058
 
 
1059
    def _track_transports(self):
 
1060
        """Install checks for transport usage."""
 
1061
        # TestCase has no safe place it can write to.
 
1062
        self._bzr_selftest_roots = []
 
1063
        # Currently the easiest way to be sure that nothing is going on is to
 
1064
        # hook into bzr dir opening. This leaves a small window of error for
 
1065
        # transport tests, but they are well known, and we can improve on this
 
1066
        # step.
 
1067
        bzrdir.BzrDir.hooks.install_named_hook("pre_open",
 
1068
            self._preopen_isolate_transport, "Check bzr directories are safe.")
826
1069
 
827
1070
    def _ndiff_strings(self, a, b):
828
1071
        """Return ndiff between two strings containing lines.
829
 
        
 
1072
 
830
1073
        A trailing newline is added if missing to make the strings
831
1074
        print properly."""
832
1075
        if b and b[-1] != '\n':
857
1100
 
858
1101
    def assertEqualDiff(self, a, b, message=None):
859
1102
        """Assert two texts are equal, if not raise an exception.
860
 
        
861
 
        This is intended for use with multi-line strings where it can 
 
1103
 
 
1104
        This is intended for use with multi-line strings where it can
862
1105
        be hard to find the differences by eye.
863
1106
        """
864
1107
        # TODO: perhaps override assertEquals to call this for strings?
866
1109
            return
867
1110
        if message is None:
868
1111
            message = "texts not equal:\n"
 
1112
        if a + '\n' == b:
 
1113
            message = 'first string is missing a final newline.\n'
869
1114
        if a == b + '\n':
870
 
            message = 'first string is missing a final newline.\n'
871
 
        if a + '\n' == b:
872
1115
            message = 'second string is missing a final newline.\n'
873
1116
        raise AssertionError(message +
874
1117
                             self._ndiff_strings(a, b))
875
 
        
 
1118
 
876
1119
    def assertEqualMode(self, mode, mode_test):
877
1120
        self.assertEqual(mode, mode_test,
878
1121
                         'mode mismatch %o != %o' % (mode, mode_test))
885
1128
        :raises AssertionError: If the expected and actual stat values differ
886
1129
            other than by atime.
887
1130
        """
888
 
        self.assertEqual(expected.st_size, actual.st_size)
889
 
        self.assertEqual(expected.st_mtime, actual.st_mtime)
890
 
        self.assertEqual(expected.st_ctime, actual.st_ctime)
891
 
        self.assertEqual(expected.st_dev, actual.st_dev)
892
 
        self.assertEqual(expected.st_ino, actual.st_ino)
893
 
        self.assertEqual(expected.st_mode, actual.st_mode)
 
1131
        self.assertEqual(expected.st_size, actual.st_size,
 
1132
                         'st_size did not match')
 
1133
        self.assertEqual(expected.st_mtime, actual.st_mtime,
 
1134
                         'st_mtime did not match')
 
1135
        self.assertEqual(expected.st_ctime, actual.st_ctime,
 
1136
                         'st_ctime did not match')
 
1137
        if sys.platform != 'win32':
 
1138
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
 
1139
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
 
1140
            # odd. Regardless we shouldn't actually try to assert anything
 
1141
            # about their values
 
1142
            self.assertEqual(expected.st_dev, actual.st_dev,
 
1143
                             'st_dev did not match')
 
1144
            self.assertEqual(expected.st_ino, actual.st_ino,
 
1145
                             'st_ino did not match')
 
1146
        self.assertEqual(expected.st_mode, actual.st_mode,
 
1147
                         'st_mode did not match')
 
1148
 
 
1149
    def assertLength(self, length, obj_with_len):
 
1150
        """Assert that obj_with_len is of length length."""
 
1151
        if len(obj_with_len) != length:
 
1152
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
 
1153
                length, len(obj_with_len), obj_with_len))
 
1154
 
 
1155
    def assertLogsError(self, exception_class, func, *args, **kwargs):
 
1156
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1157
        """
 
1158
        from bzrlib import trace
 
1159
        captured = []
 
1160
        orig_log_exception_quietly = trace.log_exception_quietly
 
1161
        try:
 
1162
            def capture():
 
1163
                orig_log_exception_quietly()
 
1164
                captured.append(sys.exc_info())
 
1165
            trace.log_exception_quietly = capture
 
1166
            func(*args, **kwargs)
 
1167
        finally:
 
1168
            trace.log_exception_quietly = orig_log_exception_quietly
 
1169
        self.assertLength(1, captured)
 
1170
        err = captured[0][1]
 
1171
        self.assertIsInstance(err, exception_class)
 
1172
        return err
894
1173
 
895
1174
    def assertPositive(self, val):
896
1175
        """Assert that val is greater than 0."""
909
1188
        if not s.endswith(suffix):
910
1189
            raise AssertionError('string %r does not end with %r' % (s, suffix))
911
1190
 
912
 
    def assertContainsRe(self, haystack, needle_re):
 
1191
    def assertContainsRe(self, haystack, needle_re, flags=0):
913
1192
        """Assert that a contains something matching a regular expression."""
914
 
        if not re.search(needle_re, haystack):
 
1193
        if not re.search(needle_re, haystack, flags):
915
1194
            if '\n' in haystack or len(haystack) > 60:
916
1195
                # a long string, format it in a more readable way
917
1196
                raise AssertionError(
921
1200
                raise AssertionError('pattern "%s" not found in "%s"'
922
1201
                        % (needle_re, haystack))
923
1202
 
924
 
    def assertNotContainsRe(self, haystack, needle_re):
 
1203
    def assertNotContainsRe(self, haystack, needle_re, flags=0):
925
1204
        """Assert that a does not match a regular expression"""
926
 
        if re.search(needle_re, haystack):
 
1205
        if re.search(needle_re, haystack, flags):
927
1206
            raise AssertionError('pattern "%s" found in "%s"'
928
1207
                    % (needle_re, haystack))
929
1208
 
 
1209
    def assertContainsString(self, haystack, needle):
 
1210
        if haystack.find(needle) == -1:
 
1211
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
 
1212
 
930
1213
    def assertSubset(self, sublist, superlist):
931
1214
        """Assert that every entry in sublist is present in superlist."""
932
1215
        missing = set(sublist) - set(superlist)
936
1219
 
937
1220
    def assertListRaises(self, excClass, func, *args, **kwargs):
938
1221
        """Fail unless excClass is raised when the iterator from func is used.
939
 
        
 
1222
 
940
1223
        Many functions can return generators this makes sure
941
1224
        to wrap them in a list() call to make sure the whole generator
942
1225
        is run, and that the proper exception is raised.
989
1272
                raise AssertionError("%r is %r." % (left, right))
990
1273
 
991
1274
    def assertTransportMode(self, transport, path, mode):
992
 
        """Fail if a path does not have mode mode.
993
 
        
 
1275
        """Fail if a path does not have mode "mode".
 
1276
 
994
1277
        If modes are not supported on this transport, the assertion is ignored.
995
1278
        """
996
1279
        if not transport._can_roundtrip_unix_modebits():
998
1281
        path_stat = transport.stat(path)
999
1282
        actual_mode = stat.S_IMODE(path_stat.st_mode)
1000
1283
        self.assertEqual(mode, actual_mode,
1001
 
            'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
 
1284
                         'mode of %r incorrect (%s != %s)'
 
1285
                         % (path, oct(mode), oct(actual_mode)))
1002
1286
 
1003
1287
    def assertIsSameRealPath(self, path1, path2):
1004
1288
        """Fail if path1 and path2 points to different files"""
1006
1290
                         osutils.realpath(path2),
1007
1291
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1008
1292
 
1009
 
    def assertIsInstance(self, obj, kls):
1010
 
        """Fail if obj is not an instance of kls"""
 
1293
    def assertIsInstance(self, obj, kls, msg=None):
 
1294
        """Fail if obj is not an instance of kls
 
1295
        
 
1296
        :param msg: Supplementary message to show if the assertion fails.
 
1297
        """
1011
1298
        if not isinstance(obj, kls):
1012
 
            self.fail("%r is an instance of %s rather than %s" % (
1013
 
                obj, obj.__class__, kls))
1014
 
 
1015
 
    def expectFailure(self, reason, assertion, *args, **kwargs):
1016
 
        """Invoke a test, expecting it to fail for the given reason.
1017
 
 
1018
 
        This is for assertions that ought to succeed, but currently fail.
1019
 
        (The failure is *expected* but not *wanted*.)  Please be very precise
1020
 
        about the failure you're expecting.  If a new bug is introduced,
1021
 
        AssertionError should be raised, not KnownFailure.
1022
 
 
1023
 
        Frequently, expectFailure should be followed by an opposite assertion.
1024
 
        See example below.
1025
 
 
1026
 
        Intended to be used with a callable that raises AssertionError as the
1027
 
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
1028
 
 
1029
 
        Raises KnownFailure if the test fails.  Raises AssertionError if the
1030
 
        test succeeds.
1031
 
 
1032
 
        example usage::
1033
 
 
1034
 
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
1035
 
                             dynamic_val)
1036
 
          self.assertEqual(42, dynamic_val)
1037
 
 
1038
 
          This means that a dynamic_val of 54 will cause the test to raise
1039
 
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
1040
 
          only a dynamic_val of 42 will allow the test to pass.  Anything other
1041
 
          than 54 or 42 will cause an AssertionError.
1042
 
        """
1043
 
        try:
1044
 
            assertion(*args, **kwargs)
1045
 
        except AssertionError:
1046
 
            raise KnownFailure(reason)
1047
 
        else:
1048
 
            self.fail('Unexpected success.  Should have failed: %s' % reason)
 
1299
            m = "%r is an instance of %s rather than %s" % (
 
1300
                obj, obj.__class__, kls)
 
1301
            if msg:
 
1302
                m += ": " + msg
 
1303
            self.fail(m)
1049
1304
 
1050
1305
    def assertFileEqual(self, content, path):
1051
1306
        """Fail if path does not contain 'content'."""
1167
1422
    def callDeprecated(self, expected, callable, *args, **kwargs):
1168
1423
        """Assert that a callable is deprecated in a particular way.
1169
1424
 
1170
 
        This is a very precise test for unusual requirements. The 
 
1425
        This is a very precise test for unusual requirements. The
1171
1426
        applyDeprecated helper function is probably more suited for most tests
1172
1427
        as it allows you to simply specify the deprecation format being used
1173
1428
        and will ensure that that is issued for the function being called.
1202
1457
 
1203
1458
        Close the file and delete it, unless setKeepLogfile was called.
1204
1459
        """
1205
 
        if self._log_file is None:
1206
 
            return
 
1460
        if bzrlib.trace._trace_file:
 
1461
            # flush the log file, to get all content
 
1462
            bzrlib.trace._trace_file.flush()
1207
1463
        bzrlib.trace.pop_log_file(self._log_memento)
1208
 
        self._log_file.close()
1209
 
        self._log_file = None
1210
 
        if not self._keep_log_file:
1211
 
            os.remove(self._log_file_name)
1212
 
            self._log_file_name = None
1213
 
 
1214
 
    def setKeepLogfile(self):
1215
 
        """Make the logfile not be deleted when _finishLogFile is called."""
1216
 
        self._keep_log_file = True
 
1464
        # Cache the log result and delete the file on disk
 
1465
        self._get_log(False)
 
1466
 
 
1467
    def thisFailsStrictLockCheck(self):
 
1468
        """It is known that this test would fail with -Dstrict_locks.
 
1469
 
 
1470
        By default, all tests are run with strict lock checking unless
 
1471
        -Edisable_lock_checks is supplied. However there are some tests which
 
1472
        we know fail strict locks at this point that have not been fixed.
 
1473
        They should call this function to disable the strict checking.
 
1474
 
 
1475
        This should be used sparingly, it is much better to fix the locking
 
1476
        issues rather than papering over the problem by calling this function.
 
1477
        """
 
1478
        debug.debug_flags.discard('strict_locks')
1217
1479
 
1218
1480
    def addCleanup(self, callable, *args, **kwargs):
1219
1481
        """Arrange to run a callable when this case is torn down.
1220
1482
 
1221
 
        Callables are run in the reverse of the order they are registered, 
 
1483
        Callables are run in the reverse of the order they are registered,
1222
1484
        ie last-in first-out.
1223
1485
        """
1224
1486
        self._cleanups.append((callable, args, kwargs))
1225
1487
 
 
1488
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
 
1489
        """Overrides an object attribute restoring it after the test.
 
1490
 
 
1491
        :param obj: The object that will be mutated.
 
1492
 
 
1493
        :param attr_name: The attribute name we want to preserve/override in
 
1494
            the object.
 
1495
 
 
1496
        :param new: The optional value we want to set the attribute to.
 
1497
 
 
1498
        :returns: The actual attr value.
 
1499
        """
 
1500
        value = getattr(obj, attr_name)
 
1501
        # The actual value is captured by the call below
 
1502
        self.addCleanup(setattr, obj, attr_name, value)
 
1503
        if new is not _unitialized_attr:
 
1504
            setattr(obj, attr_name, new)
 
1505
        return value
 
1506
 
1226
1507
    def _cleanEnvironment(self):
1227
1508
        new_env = {
1228
1509
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1230
1511
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1231
1512
            # tests do check our impls match APPDATA
1232
1513
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
1514
            'VISUAL': None,
 
1515
            'EDITOR': None,
1233
1516
            'BZR_EMAIL': None,
1234
1517
            'BZREMAIL': None, # may still be present in the environment
1235
1518
            'EMAIL': None,
1236
1519
            'BZR_PROGRESS_BAR': None,
1237
1520
            'BZR_LOG': None,
 
1521
            'BZR_PLUGIN_PATH': None,
 
1522
            'BZR_DISABLE_PLUGINS': None,
 
1523
            'BZR_PLUGINS_AT': None,
 
1524
            'BZR_CONCURRENCY': None,
 
1525
            # Make sure that any text ui tests are consistent regardless of
 
1526
            # the environment the test case is run in; you may want tests that
 
1527
            # test other combinations.  'dumb' is a reasonable guess for tests
 
1528
            # going to a pipe or a StringIO.
 
1529
            'TERM': 'dumb',
 
1530
            'LINES': '25',
 
1531
            'COLUMNS': '80',
 
1532
            'BZR_COLUMNS': '80',
1238
1533
            # SSH Agent
1239
1534
            'SSH_AUTH_SOCK': None,
1240
1535
            # Proxies
1246
1541
            'NO_PROXY': None,
1247
1542
            'all_proxy': None,
1248
1543
            'ALL_PROXY': None,
1249
 
            # Nobody cares about these ones AFAIK. So far at
 
1544
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1250
1545
            # least. If you do (care), please update this comment
1251
 
            # -- vila 20061212
 
1546
            # -- vila 20080401
1252
1547
            'ftp_proxy': None,
1253
1548
            'FTP_PROXY': None,
1254
1549
            'BZR_REMOTE_PATH': None,
 
1550
            # Generally speaking, we don't want apport reporting on crashes in
 
1551
            # the test envirnoment unless we're specifically testing apport,
 
1552
            # so that it doesn't leak into the real system environment.  We
 
1553
            # use an env var so it propagates to subprocesses.
 
1554
            'APPORT_DISABLE': '1',
1255
1555
        }
1256
 
        self.__old_env = {}
 
1556
        self._old_env = {}
1257
1557
        self.addCleanup(self._restoreEnvironment)
1258
1558
        for name, value in new_env.iteritems():
1259
1559
            self._captureVar(name, value)
1260
1560
 
1261
1561
    def _captureVar(self, name, newvalue):
1262
1562
        """Set an environment variable, and reset it when finished."""
1263
 
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1264
 
 
1265
 
    def _restore_debug_flags(self):
1266
 
        debug.debug_flags.clear()
1267
 
        debug.debug_flags.update(self._preserved_debug_flags)
 
1563
        self._old_env[name] = osutils.set_or_unset_env(name, newvalue)
1268
1564
 
1269
1565
    def _restoreEnvironment(self):
1270
 
        for name, value in self.__old_env.iteritems():
 
1566
        for name, value in self._old_env.iteritems():
1271
1567
            osutils.set_or_unset_env(name, value)
1272
1568
 
1273
1569
    def _restoreHooks(self):
1274
 
        for klass, hooks in self._preserved_hooks.items():
1275
 
            setattr(klass, 'hooks', hooks)
 
1570
        for klass, (name, hooks) in self._preserved_hooks.items():
 
1571
            setattr(klass, name, hooks)
1276
1572
 
1277
1573
    def knownFailure(self, reason):
1278
1574
        """This test has failed for some known reason."""
1279
1575
        raise KnownFailure(reason)
1280
1576
 
1281
 
    def run(self, result=None):
1282
 
        if result is None: result = self.defaultTestResult()
1283
 
        for feature in getattr(self, '_test_needs_features', []):
1284
 
            if not feature.available():
1285
 
                result.startTest(self)
1286
 
                if getattr(result, 'addNotSupported', None):
1287
 
                    result.addNotSupported(self, feature)
1288
 
                else:
1289
 
                    result.addSuccess(self)
1290
 
                result.stopTest(self)
1291
 
                return
1292
 
        try:
1293
 
            return unittest.TestCase.run(self, result)
1294
 
        finally:
1295
 
            saved_attrs = {}
1296
 
            absent_attr = object()
1297
 
            for attr_name in self.attrs_to_keep:
1298
 
                attr = getattr(self, attr_name, absent_attr)
1299
 
                if attr is not absent_attr:
1300
 
                    saved_attrs[attr_name] = attr
1301
 
            self.__dict__ = saved_attrs
1302
 
 
1303
 
    def tearDown(self):
1304
 
        self._runCleanups()
1305
 
        unittest.TestCase.tearDown(self)
 
1577
    def _do_skip(self, result, reason):
 
1578
        addSkip = getattr(result, 'addSkip', None)
 
1579
        if not callable(addSkip):
 
1580
            result.addSuccess(result)
 
1581
        else:
 
1582
            addSkip(self, reason)
 
1583
 
 
1584
    @staticmethod
 
1585
    def _do_known_failure(self, result, e):
 
1586
        err = sys.exc_info()
 
1587
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
 
1588
        if addExpectedFailure is not None:
 
1589
            addExpectedFailure(self, err)
 
1590
        else:
 
1591
            result.addSuccess(self)
 
1592
 
 
1593
    @staticmethod
 
1594
    def _do_not_applicable(self, result, e):
 
1595
        if not e.args:
 
1596
            reason = 'No reason given'
 
1597
        else:
 
1598
            reason = e.args[0]
 
1599
        addNotApplicable = getattr(result, 'addNotApplicable', None)
 
1600
        if addNotApplicable is not None:
 
1601
            result.addNotApplicable(self, reason)
 
1602
        else:
 
1603
            self._do_skip(result, reason)
 
1604
 
 
1605
    @staticmethod
 
1606
    def _do_unsupported_or_skip(self, result, e):
 
1607
        reason = e.args[0]
 
1608
        addNotSupported = getattr(result, 'addNotSupported', None)
 
1609
        if addNotSupported is not None:
 
1610
            result.addNotSupported(self, reason)
 
1611
        else:
 
1612
            self._do_skip(result, reason)
1306
1613
 
1307
1614
    def time(self, callable, *args, **kwargs):
1308
1615
        """Run callable and accrue the time it takes to the benchmark time.
1309
 
        
 
1616
 
1310
1617
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1311
1618
        this will cause lsprofile statistics to be gathered and stored in
1312
1619
        self._benchcalls.
1313
1620
        """
1314
1621
        if self._benchtime is None:
 
1622
            self.addDetail('benchtime', content.Content(content.ContentType(
 
1623
                "text", "plain"), lambda:[str(self._benchtime)]))
1315
1624
            self._benchtime = 0
1316
1625
        start = time.time()
1317
1626
        try:
1326
1635
        finally:
1327
1636
            self._benchtime += time.time() - start
1328
1637
 
1329
 
    def _runCleanups(self):
1330
 
        """Run registered cleanup functions. 
1331
 
 
1332
 
        This should only be called from TestCase.tearDown.
1333
 
        """
1334
 
        # TODO: Perhaps this should keep running cleanups even if 
1335
 
        # one of them fails?
1336
 
 
1337
 
        # Actually pop the cleanups from the list so tearDown running
1338
 
        # twice is safe (this happens for skipped tests).
1339
 
        while self._cleanups:
1340
 
            cleanup, args, kwargs = self._cleanups.pop()
1341
 
            cleanup(*args, **kwargs)
1342
 
 
1343
1638
    def log(self, *args):
1344
1639
        mutter(*args)
1345
1640
 
1346
1641
    def _get_log(self, keep_log_file=False):
1347
 
        """Get the log from bzrlib.trace calls from this test.
 
1642
        """Internal helper to get the log from bzrlib.trace for this test.
 
1643
 
 
1644
        Please use self.getDetails, or self.get_log to access this in test case
 
1645
        code.
1348
1646
 
1349
1647
        :param keep_log_file: When True, if the log is still a file on disk
1350
1648
            leave it as a file on disk. When False, if the log is still a file
1352
1650
            self._log_contents.
1353
1651
        :return: A string containing the log.
1354
1652
        """
1355
 
        # flush the log file, to get all content
 
1653
        if self._log_contents is not None:
 
1654
            try:
 
1655
                self._log_contents.decode('utf8')
 
1656
            except UnicodeDecodeError:
 
1657
                unicodestr = self._log_contents.decode('utf8', 'replace')
 
1658
                self._log_contents = unicodestr.encode('utf8')
 
1659
            return self._log_contents
1356
1660
        import bzrlib.trace
1357
 
        bzrlib.trace._trace_file.flush()
1358
 
        if self._log_contents:
1359
 
            # XXX: this can hardly contain the content flushed above --vila
1360
 
            # 20080128
1361
 
            return self._log_contents
 
1661
        if bzrlib.trace._trace_file:
 
1662
            # flush the log file, to get all content
 
1663
            bzrlib.trace._trace_file.flush()
1362
1664
        if self._log_file_name is not None:
1363
1665
            logfile = open(self._log_file_name)
1364
1666
            try:
1365
1667
                log_contents = logfile.read()
1366
1668
            finally:
1367
1669
                logfile.close()
 
1670
            try:
 
1671
                log_contents.decode('utf8')
 
1672
            except UnicodeDecodeError:
 
1673
                unicodestr = log_contents.decode('utf8', 'replace')
 
1674
                log_contents = unicodestr.encode('utf8')
1368
1675
            if not keep_log_file:
 
1676
                close_attempts = 0
 
1677
                max_close_attempts = 100
 
1678
                first_close_error = None
 
1679
                while close_attempts < max_close_attempts:
 
1680
                    close_attempts += 1
 
1681
                    try:
 
1682
                        self._log_file.close()
 
1683
                    except IOError, ioe:
 
1684
                        if ioe.errno is None:
 
1685
                            # No errno implies 'close() called during
 
1686
                            # concurrent operation on the same file object', so
 
1687
                            # retry.  Probably a thread is trying to write to
 
1688
                            # the log file.
 
1689
                            if first_close_error is None:
 
1690
                                first_close_error = ioe
 
1691
                            continue
 
1692
                        raise
 
1693
                    else:
 
1694
                        break
 
1695
                if close_attempts > 1:
 
1696
                    sys.stderr.write(
 
1697
                        'Unable to close log file on first attempt, '
 
1698
                        'will retry: %s\n' % (first_close_error,))
 
1699
                    if close_attempts == max_close_attempts:
 
1700
                        sys.stderr.write(
 
1701
                            'Unable to close log file after %d attempts.\n'
 
1702
                            % (max_close_attempts,))
 
1703
                self._log_file = None
 
1704
                # Permit multiple calls to get_log until we clean it up in
 
1705
                # finishLogFile
1369
1706
                self._log_contents = log_contents
1370
1707
                try:
1371
1708
                    os.remove(self._log_file_name)
1375
1712
                                             ' %r\n' % self._log_file_name))
1376
1713
                    else:
1377
1714
                        raise
 
1715
                self._log_file_name = None
1378
1716
            return log_contents
1379
1717
        else:
1380
 
            return "DELETED log file to reduce memory footprint"
 
1718
            return "No log file content and no log file name."
 
1719
 
 
1720
    def get_log(self):
 
1721
        """Get a unicode string containing the log from bzrlib.trace.
 
1722
 
 
1723
        Undecodable characters are replaced.
 
1724
        """
 
1725
        return u"".join(self.getDetails()['log'].iter_text())
1381
1726
 
1382
1727
    def requireFeature(self, feature):
1383
1728
        """This test requires a specific feature is available.
1400
1745
 
1401
1746
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1402
1747
            working_dir):
 
1748
        # Clear chk_map page cache, because the contents are likely to mask
 
1749
        # locking errors.
 
1750
        chk_map.clear_cache()
1403
1751
        if encoding is None:
1404
 
            encoding = bzrlib.user_encoding
 
1752
            encoding = osutils.get_user_encoding()
1405
1753
        stdout = StringIOWrapper()
1406
1754
        stderr = StringIOWrapper()
1407
1755
        stdout.encoding = encoding
1422
1770
            os.chdir(working_dir)
1423
1771
 
1424
1772
        try:
1425
 
            result = self.apply_redirected(ui.ui_factory.stdin,
1426
 
                stdout, stderr,
1427
 
                bzrlib.commands.run_bzr_catch_user_errors,
1428
 
                args)
 
1773
            try:
 
1774
                result = self.apply_redirected(ui.ui_factory.stdin,
 
1775
                    stdout, stderr,
 
1776
                    bzrlib.commands.run_bzr_catch_user_errors,
 
1777
                    args)
 
1778
            except KeyboardInterrupt:
 
1779
                # Reraise KeyboardInterrupt with contents of redirected stdout
 
1780
                # and stderr as arguments, for tests which are interested in
 
1781
                # stdout and stderr and are expecting the exception.
 
1782
                out = stdout.getvalue()
 
1783
                err = stderr.getvalue()
 
1784
                if out:
 
1785
                    self.log('output:\n%r', out)
 
1786
                if err:
 
1787
                    self.log('errors:\n%r', err)
 
1788
                raise KeyboardInterrupt(out, err)
1429
1789
        finally:
1430
1790
            logger.removeHandler(handler)
1431
1791
            ui.ui_factory = old_ui_factory
1441
1801
        if retcode is not None:
1442
1802
            self.assertEquals(retcode, result,
1443
1803
                              message='Unexpected return code')
1444
 
        return out, err
 
1804
        return result, out, err
1445
1805
 
1446
1806
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1447
1807
                working_dir=None, error_regexes=[], output_encoding=None):
1452
1812
        passed in three ways:
1453
1813
 
1454
1814
        1- A list of strings, eg ["commit", "a"].  This is recommended
1455
 
        when the command contains whitespace or metacharacters, or 
 
1815
        when the command contains whitespace or metacharacters, or
1456
1816
        is built up at run time.
1457
1817
 
1458
 
        2- A single string, eg "add a".  This is the most convenient 
 
1818
        2- A single string, eg "add a".  This is the most convenient
1459
1819
        for hardcoded commands.
1460
1820
 
1461
1821
        This runs bzr through the interface that catches and reports
1476
1836
        :keyword error_regexes: A list of expected error messages.  If
1477
1837
            specified they must be seen in the error output of the command.
1478
1838
        """
1479
 
        out, err = self._run_bzr_autosplit(
 
1839
        retcode, out, err = self._run_bzr_autosplit(
1480
1840
            args=args,
1481
1841
            retcode=retcode,
1482
1842
            encoding=encoding,
1483
1843
            stdin=stdin,
1484
1844
            working_dir=working_dir,
1485
1845
            )
 
1846
        self.assertIsInstance(error_regexes, (list, tuple))
1486
1847
        for regex in error_regexes:
1487
1848
            self.assertContainsRe(err, regex)
1488
1849
        return out, err
1520
1881
    def run_bzr_subprocess(self, *args, **kwargs):
1521
1882
        """Run bzr in a subprocess for testing.
1522
1883
 
1523
 
        This starts a new Python interpreter and runs bzr in there. 
 
1884
        This starts a new Python interpreter and runs bzr in there.
1524
1885
        This should only be used for tests that have a justifiable need for
1525
1886
        this isolation: e.g. they are testing startup time, or signal
1526
 
        handling, or early startup code, etc.  Subprocess code can't be 
 
1887
        handling, or early startup code, etc.  Subprocess code can't be
1527
1888
        profiled or debugged so easily.
1528
1889
 
1529
1890
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
1632
1993
        """
1633
1994
        return Popen(*args, **kwargs)
1634
1995
 
 
1996
    def get_source_path(self):
 
1997
        """Return the path of the directory containing bzrlib."""
 
1998
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
 
1999
 
1635
2000
    def get_bzr_path(self):
1636
2001
        """Return the path of the 'bzr' executable for this test suite."""
1637
 
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
2002
        bzr_path = self.get_source_path()+'/bzr'
1638
2003
        if not os.path.isfile(bzr_path):
1639
2004
            # We are probably installed. Assume sys.argv is the right file
1640
2005
            bzr_path = sys.argv[0]
1726
2091
 
1727
2092
        Tests that expect to provoke LockContention errors should call this.
1728
2093
        """
1729
 
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
1730
 
        def resetTimeout():
1731
 
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
1732
 
        self.addCleanup(resetTimeout)
1733
 
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
2094
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
1734
2095
 
1735
2096
    def make_utf8_encoded_stringio(self, encoding_type=None):
1736
2097
        """Return a StringIOWrapper instance, that will encode Unicode
1744
2105
        sio.encoding = output_encoding
1745
2106
        return sio
1746
2107
 
 
2108
    def disable_verb(self, verb):
 
2109
        """Disable a smart server verb for one test."""
 
2110
        from bzrlib.smart import request
 
2111
        request_handlers = request.request_handlers
 
2112
        orig_method = request_handlers.get(verb)
 
2113
        request_handlers.remove(verb)
 
2114
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2115
 
 
2116
 
 
2117
class CapturedCall(object):
 
2118
    """A helper for capturing smart server calls for easy debug analysis."""
 
2119
 
 
2120
    def __init__(self, params, prefix_length):
 
2121
        """Capture the call with params and skip prefix_length stack frames."""
 
2122
        self.call = params
 
2123
        import traceback
 
2124
        # The last 5 frames are the __init__, the hook frame, and 3 smart
 
2125
        # client frames. Beyond this we could get more clever, but this is good
 
2126
        # enough for now.
 
2127
        stack = traceback.extract_stack()[prefix_length:-5]
 
2128
        self.stack = ''.join(traceback.format_list(stack))
 
2129
 
 
2130
    def __str__(self):
 
2131
        return self.call.method
 
2132
 
 
2133
    def __repr__(self):
 
2134
        return self.call.method
 
2135
 
 
2136
    def stack(self):
 
2137
        return self.stack
 
2138
 
1747
2139
 
1748
2140
class TestCaseWithMemoryTransport(TestCase):
1749
2141
    """Common test class for tests that do not need disk resources.
1769
2161
 
1770
2162
    def __init__(self, methodName='runTest'):
1771
2163
        # allow test parameterization after test construction and before test
1772
 
        # execution. Variables that the parameterizer sets need to be 
 
2164
        # execution. Variables that the parameterizer sets need to be
1773
2165
        # ones that are not set by setUp, or setUp will trash them.
1774
2166
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
1775
2167
        self.vfs_transport_factory = default_transport
1782
2174
 
1783
2175
        This transport is for the test scratch space relative to
1784
2176
        "self._test_root"
1785
 
        
 
2177
 
1786
2178
        :param relpath: a path relative to the base url.
1787
2179
        """
1788
2180
        t = get_transport(self.get_url(relpath))
1791
2183
 
1792
2184
    def get_readonly_transport(self, relpath=None):
1793
2185
        """Return a readonly transport for the test scratch space
1794
 
        
 
2186
 
1795
2187
        This can be used to test that operations which should only need
1796
2188
        readonly access in fact do not try to write.
1797
2189
 
1816
2208
        if self.__readonly_server is None:
1817
2209
            if self.transport_readonly_server is None:
1818
2210
                # readonly decorator requested
1819
 
                # bring up the server
1820
 
                self.__readonly_server = ReadonlyServer()
1821
 
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
2211
                self.__readonly_server = test_server.ReadonlyServer()
1822
2212
            else:
 
2213
                # explicit readonly transport.
1823
2214
                self.__readonly_server = self.create_transport_readonly_server()
1824
 
                self.__readonly_server.setUp(self.get_vfs_only_server())
1825
 
            self.addCleanup(self.__readonly_server.tearDown)
 
2215
            self.start_server(self.__readonly_server,
 
2216
                self.get_vfs_only_server())
1826
2217
        return self.__readonly_server
1827
2218
 
1828
2219
    def get_readonly_url(self, relpath=None):
1829
2220
        """Get a URL for the readonly transport.
1830
2221
 
1831
 
        This will either be backed by '.' or a decorator to the transport 
 
2222
        This will either be backed by '.' or a decorator to the transport
1832
2223
        used by self.get_url()
1833
2224
        relpath provides for clients to get a path relative to the base url.
1834
2225
        These should only be downwards relative, not upwards.
1846
2237
        is no means to override it.
1847
2238
        """
1848
2239
        if self.__vfs_server is None:
1849
 
            self.__vfs_server = MemoryServer()
1850
 
            self.__vfs_server.setUp()
1851
 
            self.addCleanup(self.__vfs_server.tearDown)
 
2240
            self.__vfs_server = memory.MemoryServer()
 
2241
            self.start_server(self.__vfs_server)
1852
2242
        return self.__vfs_server
1853
2243
 
1854
2244
    def get_server(self):
1861
2251
        then the self.get_vfs_server is returned.
1862
2252
        """
1863
2253
        if self.__server is None:
1864
 
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
1865
 
                return self.get_vfs_only_server()
 
2254
            if (self.transport_server is None or self.transport_server is
 
2255
                self.vfs_transport_factory):
 
2256
                self.__server = self.get_vfs_only_server()
1866
2257
            else:
1867
2258
                # bring up a decorated means of access to the vfs only server.
1868
2259
                self.__server = self.transport_server()
1869
 
                try:
1870
 
                    self.__server.setUp(self.get_vfs_only_server())
1871
 
                except TypeError, e:
1872
 
                    # This should never happen; the try:Except here is to assist
1873
 
                    # developers having to update code rather than seeing an
1874
 
                    # uninformative TypeError.
1875
 
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
1876
 
            self.addCleanup(self.__server.tearDown)
 
2260
                self.start_server(self.__server, self.get_vfs_only_server())
1877
2261
        return self.__server
1878
2262
 
1879
2263
    def _adjust_url(self, base, relpath):
1941
2325
        propagating. This method ensures than a test did not leaked.
1942
2326
        """
1943
2327
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
2328
        self.permit_url(get_transport(root).base)
1944
2329
        wt = workingtree.WorkingTree.open(root)
1945
2330
        last_rev = wt.last_revision()
1946
2331
        if last_rev != 'null:':
1948
2333
            # recreate a new one or all the followng tests will fail.
1949
2334
            # If you need to inspect its content uncomment the following line
1950
2335
            # import pdb; pdb.set_trace()
1951
 
            _rmtree_temp_dir(root + '/.bzr')
 
2336
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
1952
2337
            self._create_safety_net()
1953
2338
            raise AssertionError('%s/.bzr should not be modified' % root)
1954
2339
 
1955
2340
    def _make_test_root(self):
1956
2341
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
1957
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
2342
            # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
2343
            root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
 
2344
                                                    suffix='.tmp'))
1958
2345
            TestCaseWithMemoryTransport.TEST_ROOT = root
1959
2346
 
1960
2347
            self._create_safety_net()
1963
2350
            # specifically told when all tests are finished.  This will do.
1964
2351
            atexit.register(_rmtree_temp_dir, root)
1965
2352
 
 
2353
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
1966
2354
        self.addCleanup(self._check_safety_net)
1967
2355
 
1968
2356
    def makeAndChdirToTestDir(self):
1969
2357
        """Create a temporary directories for this one test.
1970
 
        
 
2358
 
1971
2359
        This must set self.test_home_dir and self.test_dir and chdir to
1972
2360
        self.test_dir.
1973
 
        
 
2361
 
1974
2362
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
1975
2363
        """
1976
2364
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
1977
2365
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
1978
2366
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
1979
 
        
 
2367
        self.permit_dir(self.test_dir)
 
2368
 
1980
2369
    def make_branch(self, relpath, format=None):
1981
2370
        """Create a branch on the transport at relpath."""
1982
2371
        repo = self.make_repository(relpath, format=format)
2000
2389
 
2001
2390
    def make_repository(self, relpath, shared=False, format=None):
2002
2391
        """Create a repository on our default transport at relpath.
2003
 
        
 
2392
 
2004
2393
        Note that relpath must be a relative path, not a full url.
2005
2394
        """
2006
2395
        # FIXME: If you create a remoterepository this returns the underlying
2007
 
        # real format, which is incorrect.  Actually we should make sure that 
 
2396
        # real format, which is incorrect.  Actually we should make sure that
2008
2397
        # RemoteBzrDir returns a RemoteRepository.
2009
2398
        # maybe  mbp 20070410
2010
2399
        made_control = self.make_bzrdir(relpath, format=format)
2011
2400
        return made_control.create_repository(shared=shared)
2012
2401
 
 
2402
    def make_smart_server(self, path):
 
2403
        smart_server = test_server.SmartTCPServer_for_testing()
 
2404
        self.start_server(smart_server, self.get_server())
 
2405
        remote_transport = get_transport(smart_server.get_url()).clone(path)
 
2406
        return remote_transport
 
2407
 
2013
2408
    def make_branch_and_memory_tree(self, relpath, format=None):
2014
2409
        """Create a branch on the default transport and a MemoryTree for it."""
2015
2410
        b = self.make_branch(relpath, format=format)
2016
2411
        return memorytree.MemoryTree.create_on_branch(b)
2017
2412
 
2018
2413
    def make_branch_builder(self, relpath, format=None):
2019
 
        url = self.get_url(relpath)
2020
 
        tran = get_transport(url)
2021
 
        return branchbuilder.BranchBuilder(get_transport(url), format=format)
 
2414
        branch = self.make_branch(relpath, format=format)
 
2415
        return branchbuilder.BranchBuilder(branch=branch)
2022
2416
 
2023
2417
    def overrideEnvironmentForTesting(self):
2024
 
        os.environ['HOME'] = self.test_home_dir
2025
 
        os.environ['BZR_HOME'] = self.test_home_dir
2026
 
        
 
2418
        test_home_dir = self.test_home_dir
 
2419
        if isinstance(test_home_dir, unicode):
 
2420
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
 
2421
        os.environ['HOME'] = test_home_dir
 
2422
        os.environ['BZR_HOME'] = test_home_dir
 
2423
 
2027
2424
    def setUp(self):
2028
2425
        super(TestCaseWithMemoryTransport, self).setUp()
2029
2426
        self._make_test_root()
2030
 
        _currentdir = os.getcwdu()
2031
 
        def _leaveDirectory():
2032
 
            os.chdir(_currentdir)
2033
 
        self.addCleanup(_leaveDirectory)
 
2427
        self.addCleanup(os.chdir, os.getcwdu())
2034
2428
        self.makeAndChdirToTestDir()
2035
2429
        self.overrideEnvironmentForTesting()
2036
2430
        self.__readonly_server = None
2037
2431
        self.__server = None
2038
2432
        self.reduceLockdirTimeout()
2039
2433
 
2040
 
     
 
2434
    def setup_smart_server_with_call_log(self):
 
2435
        """Sets up a smart server as the transport server with a call log."""
 
2436
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2437
        self.hpss_calls = []
 
2438
        import traceback
 
2439
        # Skip the current stack down to the caller of
 
2440
        # setup_smart_server_with_call_log
 
2441
        prefix_length = len(traceback.extract_stack()) - 2
 
2442
        def capture_hpss_call(params):
 
2443
            self.hpss_calls.append(
 
2444
                CapturedCall(params, prefix_length))
 
2445
        client._SmartClient.hooks.install_named_hook(
 
2446
            'call', capture_hpss_call, None)
 
2447
 
 
2448
    def reset_smart_call_log(self):
 
2449
        self.hpss_calls = []
 
2450
 
 
2451
 
2041
2452
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2042
2453
    """Derived class that runs a test within a temporary directory.
2043
2454
 
2048
2459
    All test cases create their own directory within that.  If the
2049
2460
    tests complete successfully, the directory is removed.
2050
2461
 
2051
 
    :ivar test_base_dir: The path of the top-level directory for this 
 
2462
    :ivar test_base_dir: The path of the top-level directory for this
2052
2463
    test, which contains a home directory and a work directory.
2053
2464
 
2054
2465
    :ivar test_home_dir: An initially empty directory under test_base_dir
2070
2481
 
2071
2482
    def _getTestDirPrefix(self):
2072
2483
        # create a directory within the top level test directory
2073
 
        if sys.platform == 'win32':
 
2484
        if sys.platform in ('win32', 'cygwin'):
2074
2485
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2075
2486
            # windows is likely to have path-length limits so use a short name
2076
2487
            name_prefix = name_prefix[-30:]
2080
2491
 
2081
2492
    def makeAndChdirToTestDir(self):
2082
2493
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2083
 
        
 
2494
 
2084
2495
        For TestCaseInTempDir we create a temporary directory based on the test
2085
2496
        name and then create two subdirs - test and home under it.
2086
2497
        """
2087
 
        name_prefix = osutils.pathjoin(self.TEST_ROOT, self._getTestDirPrefix())
 
2498
        name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
 
2499
            self._getTestDirPrefix())
2088
2500
        name = name_prefix
2089
2501
        for i in range(100):
2090
2502
            if os.path.exists(name):
2091
2503
                name = name_prefix + '_' + str(i)
2092
2504
            else:
2093
 
                os.mkdir(name)
 
2505
                # now create test and home directories within this dir
 
2506
                self.test_base_dir = name
 
2507
                self.addCleanup(self.deleteTestDir)
 
2508
                os.mkdir(self.test_base_dir)
2094
2509
                break
2095
 
        # now create test and home directories within this dir
2096
 
        self.test_base_dir = name
 
2510
        self.permit_dir(self.test_base_dir)
 
2511
        # 'sprouting' and 'init' of a branch both walk up the tree to find
 
2512
        # stacking policy to honour; create a bzr dir with an unshared
 
2513
        # repository (but not a branch - our code would be trying to escape
 
2514
        # then!) to stop them, and permit it to be read.
 
2515
        # control = bzrdir.BzrDir.create(self.test_base_dir)
 
2516
        # control.create_repository()
2097
2517
        self.test_home_dir = self.test_base_dir + '/home'
2098
2518
        os.mkdir(self.test_home_dir)
2099
2519
        self.test_dir = self.test_base_dir + '/work'
2105
2525
            f.write(self.id())
2106
2526
        finally:
2107
2527
            f.close()
2108
 
        self.addCleanup(self.deleteTestDir)
2109
2528
 
2110
2529
    def deleteTestDir(self):
2111
 
        os.chdir(self.TEST_ROOT)
2112
 
        _rmtree_temp_dir(self.test_base_dir)
 
2530
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
 
2531
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
2113
2532
 
2114
2533
    def build_tree(self, shape, line_endings='binary', transport=None):
2115
2534
        """Build a test tree according to a pattern.
2136
2555
        if transport is None or transport.is_readonly():
2137
2556
            transport = get_transport(".")
2138
2557
        for name in shape:
2139
 
            self.assert_(isinstance(name, basestring))
 
2558
            self.assertIsInstance(name, basestring)
2140
2559
            if name[-1] == '/':
2141
2560
                transport.mkdir(urlutils.escape(name[:-1]))
2142
2561
            else:
2185
2604
    ReadonlyTransportDecorator is used instead which allows the use of non disk
2186
2605
    based read write transports.
2187
2606
 
2188
 
    If an explicit class is provided for readonly access, that server and the 
 
2607
    If an explicit class is provided for readonly access, that server and the
2189
2608
    readwrite one must both define get_url() as resolving to os.getcwd().
2190
2609
    """
2191
2610
 
2197
2616
        """
2198
2617
        if self.__vfs_server is None:
2199
2618
            self.__vfs_server = self.vfs_transport_factory()
2200
 
            self.__vfs_server.setUp()
2201
 
            self.addCleanup(self.__vfs_server.tearDown)
 
2619
            self.start_server(self.__vfs_server)
2202
2620
        return self.__vfs_server
2203
2621
 
2204
2622
    def make_branch_and_tree(self, relpath, format=None):
2211
2629
        repository will also be accessed locally. Otherwise a lightweight
2212
2630
        checkout is created and returned.
2213
2631
 
 
2632
        We do this because we can't physically create a tree in the local
 
2633
        path, with a branch reference to the transport_factory url, and
 
2634
        a branch + repository in the vfs_transport, unless the vfs_transport
 
2635
        namespace is distinct from the local disk - the two branch objects
 
2636
        would collide. While we could construct a tree with its branch object
 
2637
        pointing at the transport_factory transport in memory, reopening it
 
2638
        would behaving unexpectedly, and has in the past caused testing bugs
 
2639
        when we tried to do it that way.
 
2640
 
2214
2641
        :param format: The BzrDirFormat.
2215
2642
        :returns: the WorkingTree.
2216
2643
        """
2225
2652
            # We can only make working trees locally at the moment.  If the
2226
2653
            # transport can't support them, then we keep the non-disk-backed
2227
2654
            # branch and create a local checkout.
2228
 
            if self.vfs_transport_factory is LocalURLServer:
 
2655
            if self.vfs_transport_factory is test_server.LocalURLServer:
2229
2656
                # the branch is colocated on disk, we cannot create a checkout.
2230
2657
                # hopefully callers will expect this.
2231
2658
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2268
2695
        super(TestCaseWithTransport, self).setUp()
2269
2696
        self.__vfs_server = None
2270
2697
 
 
2698
    def disable_missing_extensions_warning(self):
 
2699
        """Some tests expect a precise stderr content.
 
2700
 
 
2701
        There is no point in forcing them to duplicate the extension related
 
2702
        warning.
 
2703
        """
 
2704
        config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
 
2705
 
2271
2706
 
2272
2707
class ChrootedTestCase(TestCaseWithTransport):
2273
2708
    """A support class that provides readonly urls outside the local namespace.
2277
2712
    for readonly urls.
2278
2713
 
2279
2714
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
2280
 
                       be used without needed to redo it when a different 
 
2715
                       be used without needed to redo it when a different
2281
2716
                       subclass is in use ?
2282
2717
    """
2283
2718
 
2284
2719
    def setUp(self):
2285
2720
        super(ChrootedTestCase, self).setUp()
2286
 
        if not self.vfs_transport_factory == MemoryServer:
 
2721
        if not self.vfs_transport_factory == memory.MemoryServer:
2287
2722
            self.transport_readonly_server = HttpServer
2288
2723
 
2289
2724
 
2290
2725
def condition_id_re(pattern):
2291
2726
    """Create a condition filter which performs a re check on a test's id.
2292
 
    
 
2727
 
2293
2728
    :param pattern: A regular expression string.
2294
2729
    :return: A callable that returns True if the re matches.
2295
2730
    """
2296
 
    filter_re = re.compile(pattern)
 
2731
    filter_re = osutils.re_compile_checked(pattern, 0,
 
2732
        'test filter')
2297
2733
    def condition(test):
2298
2734
        test_id = test.id()
2299
2735
        return filter_re.search(test_id)
2302
2738
 
2303
2739
def condition_isinstance(klass_or_klass_list):
2304
2740
    """Create a condition filter which returns isinstance(param, klass).
2305
 
    
 
2741
 
2306
2742
    :return: A callable which when called with one parameter obj return the
2307
2743
        result of isinstance(obj, klass_or_klass_list).
2308
2744
    """
2313
2749
 
2314
2750
def condition_id_in_list(id_list):
2315
2751
    """Create a condition filter which verify that test's id in a list.
2316
 
    
 
2752
 
2317
2753
    :param id_list: A TestIdList object.
2318
2754
    :return: A callable that returns True if the test's id appears in the list.
2319
2755
    """
2324
2760
 
2325
2761
def condition_id_startswith(starts):
2326
2762
    """Create a condition filter verifying that test's id starts with a string.
2327
 
    
 
2763
 
2328
2764
    :param starts: A list of string.
2329
 
    :return: A callable that returns True if the test's id starts with one of 
 
2765
    :return: A callable that returns True if the test's id starts with one of
2330
2766
        the given strings.
2331
2767
    """
2332
2768
    def condition(test):
2355
2791
 
2356
2792
def filter_suite_by_condition(suite, condition):
2357
2793
    """Create a test suite by filtering another one.
2358
 
    
 
2794
 
2359
2795
    :param suite: The source suite.
2360
2796
    :param condition: A callable whose result evaluates True when called with a
2361
2797
        test case which should be included in the result.
2371
2807
 
2372
2808
def filter_suite_by_re(suite, pattern):
2373
2809
    """Create a test suite by filtering another one.
2374
 
    
 
2810
 
2375
2811
    :param suite:           the source suite
2376
2812
    :param pattern:         pattern that names must match
2377
2813
    :returns: the newly created suite
2429
2865
 
2430
2866
def randomize_suite(suite):
2431
2867
    """Return a new TestSuite with suite's tests in random order.
2432
 
    
 
2868
 
2433
2869
    The tests in the input suite are flattened into a single suite in order to
2434
2870
    accomplish this. Any nested TestSuites are removed to provide global
2435
2871
    randomness.
2441
2877
 
2442
2878
def split_suite_by_condition(suite, condition):
2443
2879
    """Split a test suite into two by a condition.
2444
 
    
 
2880
 
2445
2881
    :param suite: The suite to split.
2446
2882
    :param condition: The condition to match on. Tests that match this
2447
2883
        condition are returned in the first test suite, ones that do not match
2463
2899
 
2464
2900
def split_suite_by_re(suite, pattern):
2465
2901
    """Split a test suite into two by a regular expression.
2466
 
    
 
2902
 
2467
2903
    :param suite: The suite to split.
2468
2904
    :param pattern: A regular expression string. Test ids that match this
2469
2905
        pattern will be in the first test suite returned, and the others in the
2483
2919
              list_only=False,
2484
2920
              random_seed=None,
2485
2921
              exclude_pattern=None,
2486
 
              strict=False):
 
2922
              strict=False,
 
2923
              runner_class=None,
 
2924
              suite_decorators=None,
 
2925
              stream=None,
 
2926
              result_decorators=None,
 
2927
              ):
 
2928
    """Run a test suite for bzr selftest.
 
2929
 
 
2930
    :param runner_class: The class of runner to use. Must support the
 
2931
        constructor arguments passed by run_suite which are more than standard
 
2932
        python uses.
 
2933
    :return: A boolean indicating success.
 
2934
    """
2487
2935
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
2488
2936
    if verbose:
2489
2937
        verbosity = 2
2490
2938
    else:
2491
2939
        verbosity = 1
2492
 
    runner = TextTestRunner(stream=sys.stdout,
 
2940
    if runner_class is None:
 
2941
        runner_class = TextTestRunner
 
2942
    if stream is None:
 
2943
        stream = sys.stdout
 
2944
    runner = runner_class(stream=stream,
2493
2945
                            descriptions=0,
2494
2946
                            verbosity=verbosity,
2495
2947
                            bench_history=bench_history,
2496
 
                            list_only=list_only,
 
2948
                            strict=strict,
 
2949
                            result_decorators=result_decorators,
2497
2950
                            )
2498
2951
    runner.stop_on_failure=stop_on_failure
2499
 
    # Initialise the random number generator and display the seed used.
2500
 
    # We convert the seed to a long to make it reuseable across invocations.
2501
 
    random_order = False
2502
 
    if random_seed is not None:
2503
 
        random_order = True
2504
 
        if random_seed == "now":
2505
 
            random_seed = long(time.time())
 
2952
    # built in decorator factories:
 
2953
    decorators = [
 
2954
        random_order(random_seed, runner),
 
2955
        exclude_tests(exclude_pattern),
 
2956
        ]
 
2957
    if matching_tests_first:
 
2958
        decorators.append(tests_first(pattern))
 
2959
    else:
 
2960
        decorators.append(filter_tests(pattern))
 
2961
    if suite_decorators:
 
2962
        decorators.extend(suite_decorators)
 
2963
    # tell the result object how many tests will be running: (except if
 
2964
    # --parallel=fork is being used. Robert said he will provide a better
 
2965
    # progress design later -- vila 20090817)
 
2966
    if fork_decorator not in decorators:
 
2967
        decorators.append(CountingDecorator)
 
2968
    for decorator in decorators:
 
2969
        suite = decorator(suite)
 
2970
    if list_only:
 
2971
        # Done after test suite decoration to allow randomisation etc
 
2972
        # to take effect, though that is of marginal benefit.
 
2973
        if verbosity >= 2:
 
2974
            stream.write("Listing tests only ...\n")
 
2975
        for t in iter_suite_tests(suite):
 
2976
            stream.write("%s\n" % (t.id()))
 
2977
        return True
 
2978
    result = runner.run(suite)
 
2979
    if strict:
 
2980
        return result.wasStrictlySuccessful()
 
2981
    else:
 
2982
        return result.wasSuccessful()
 
2983
 
 
2984
 
 
2985
# A registry where get() returns a suite decorator.
 
2986
parallel_registry = registry.Registry()
 
2987
 
 
2988
 
 
2989
def fork_decorator(suite):
 
2990
    concurrency = osutils.local_concurrency()
 
2991
    if concurrency == 1:
 
2992
        return suite
 
2993
    from testtools import ConcurrentTestSuite
 
2994
    return ConcurrentTestSuite(suite, fork_for_tests)
 
2995
parallel_registry.register('fork', fork_decorator)
 
2996
 
 
2997
 
 
2998
def subprocess_decorator(suite):
 
2999
    concurrency = osutils.local_concurrency()
 
3000
    if concurrency == 1:
 
3001
        return suite
 
3002
    from testtools import ConcurrentTestSuite
 
3003
    return ConcurrentTestSuite(suite, reinvoke_for_tests)
 
3004
parallel_registry.register('subprocess', subprocess_decorator)
 
3005
 
 
3006
 
 
3007
def exclude_tests(exclude_pattern):
 
3008
    """Return a test suite decorator that excludes tests."""
 
3009
    if exclude_pattern is None:
 
3010
        return identity_decorator
 
3011
    def decorator(suite):
 
3012
        return ExcludeDecorator(suite, exclude_pattern)
 
3013
    return decorator
 
3014
 
 
3015
 
 
3016
def filter_tests(pattern):
 
3017
    if pattern == '.*':
 
3018
        return identity_decorator
 
3019
    def decorator(suite):
 
3020
        return FilterTestsDecorator(suite, pattern)
 
3021
    return decorator
 
3022
 
 
3023
 
 
3024
def random_order(random_seed, runner):
 
3025
    """Return a test suite decorator factory for randomising tests order.
 
3026
    
 
3027
    :param random_seed: now, a string which casts to a long, or a long.
 
3028
    :param runner: A test runner with a stream attribute to report on.
 
3029
    """
 
3030
    if random_seed is None:
 
3031
        return identity_decorator
 
3032
    def decorator(suite):
 
3033
        return RandomDecorator(suite, random_seed, runner.stream)
 
3034
    return decorator
 
3035
 
 
3036
 
 
3037
def tests_first(pattern):
 
3038
    if pattern == '.*':
 
3039
        return identity_decorator
 
3040
    def decorator(suite):
 
3041
        return TestFirstDecorator(suite, pattern)
 
3042
    return decorator
 
3043
 
 
3044
 
 
3045
def identity_decorator(suite):
 
3046
    """Return suite."""
 
3047
    return suite
 
3048
 
 
3049
 
 
3050
class TestDecorator(TestSuite):
 
3051
    """A decorator for TestCase/TestSuite objects.
 
3052
    
 
3053
    Usually, subclasses should override __iter__(used when flattening test
 
3054
    suites), which we do to filter, reorder, parallelise and so on, run() and
 
3055
    debug().
 
3056
    """
 
3057
 
 
3058
    def __init__(self, suite):
 
3059
        TestSuite.__init__(self)
 
3060
        self.addTest(suite)
 
3061
 
 
3062
    def countTestCases(self):
 
3063
        cases = 0
 
3064
        for test in self:
 
3065
            cases += test.countTestCases()
 
3066
        return cases
 
3067
 
 
3068
    def debug(self):
 
3069
        for test in self:
 
3070
            test.debug()
 
3071
 
 
3072
    def run(self, result):
 
3073
        # Use iteration on self, not self._tests, to allow subclasses to hook
 
3074
        # into __iter__.
 
3075
        for test in self:
 
3076
            if result.shouldStop:
 
3077
                break
 
3078
            test.run(result)
 
3079
        return result
 
3080
 
 
3081
 
 
3082
class CountingDecorator(TestDecorator):
 
3083
    """A decorator which calls result.progress(self.countTestCases)."""
 
3084
 
 
3085
    def run(self, result):
 
3086
        progress_method = getattr(result, 'progress', None)
 
3087
        if callable(progress_method):
 
3088
            progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
 
3089
        return super(CountingDecorator, self).run(result)
 
3090
 
 
3091
 
 
3092
class ExcludeDecorator(TestDecorator):
 
3093
    """A decorator which excludes test matching an exclude pattern."""
 
3094
 
 
3095
    def __init__(self, suite, exclude_pattern):
 
3096
        TestDecorator.__init__(self, suite)
 
3097
        self.exclude_pattern = exclude_pattern
 
3098
        self.excluded = False
 
3099
 
 
3100
    def __iter__(self):
 
3101
        if self.excluded:
 
3102
            return iter(self._tests)
 
3103
        self.excluded = True
 
3104
        suite = exclude_tests_by_re(self, self.exclude_pattern)
 
3105
        del self._tests[:]
 
3106
        self.addTests(suite)
 
3107
        return iter(self._tests)
 
3108
 
 
3109
 
 
3110
class FilterTestsDecorator(TestDecorator):
 
3111
    """A decorator which filters tests to those matching a pattern."""
 
3112
 
 
3113
    def __init__(self, suite, pattern):
 
3114
        TestDecorator.__init__(self, suite)
 
3115
        self.pattern = pattern
 
3116
        self.filtered = False
 
3117
 
 
3118
    def __iter__(self):
 
3119
        if self.filtered:
 
3120
            return iter(self._tests)
 
3121
        self.filtered = True
 
3122
        suite = filter_suite_by_re(self, self.pattern)
 
3123
        del self._tests[:]
 
3124
        self.addTests(suite)
 
3125
        return iter(self._tests)
 
3126
 
 
3127
 
 
3128
class RandomDecorator(TestDecorator):
 
3129
    """A decorator which randomises the order of its tests."""
 
3130
 
 
3131
    def __init__(self, suite, random_seed, stream):
 
3132
        TestDecorator.__init__(self, suite)
 
3133
        self.random_seed = random_seed
 
3134
        self.randomised = False
 
3135
        self.stream = stream
 
3136
 
 
3137
    def __iter__(self):
 
3138
        if self.randomised:
 
3139
            return iter(self._tests)
 
3140
        self.randomised = True
 
3141
        self.stream.write("Randomizing test order using seed %s\n\n" %
 
3142
            (self.actual_seed()))
 
3143
        # Initialise the random number generator.
 
3144
        random.seed(self.actual_seed())
 
3145
        suite = randomize_suite(self)
 
3146
        del self._tests[:]
 
3147
        self.addTests(suite)
 
3148
        return iter(self._tests)
 
3149
 
 
3150
    def actual_seed(self):
 
3151
        if self.random_seed == "now":
 
3152
            # We convert the seed to a long to make it reuseable across
 
3153
            # invocations (because the user can reenter it).
 
3154
            self.random_seed = long(time.time())
2506
3155
        else:
2507
3156
            # Convert the seed to a long if we can
2508
3157
            try:
2509
 
                random_seed = long(random_seed)
 
3158
                self.random_seed = long(self.random_seed)
2510
3159
            except:
2511
3160
                pass
2512
 
        runner.stream.writeln("Randomizing test order using seed %s\n" %
2513
 
            (random_seed))
2514
 
        random.seed(random_seed)
2515
 
    # Customise the list of tests if requested
2516
 
    if exclude_pattern is not None:
2517
 
        suite = exclude_tests_by_re(suite, exclude_pattern)
2518
 
    if random_order:
2519
 
        order_changer = randomize_suite
2520
 
    else:
2521
 
        order_changer = preserve_input
2522
 
    if pattern != '.*' or random_order:
2523
 
        if matching_tests_first:
2524
 
            suites = map(order_changer, split_suite_by_re(suite, pattern))
2525
 
            suite = TestUtil.TestSuite(suites)
 
3161
        return self.random_seed
 
3162
 
 
3163
 
 
3164
class TestFirstDecorator(TestDecorator):
 
3165
    """A decorator which moves named tests to the front."""
 
3166
 
 
3167
    def __init__(self, suite, pattern):
 
3168
        TestDecorator.__init__(self, suite)
 
3169
        self.pattern = pattern
 
3170
        self.filtered = False
 
3171
 
 
3172
    def __iter__(self):
 
3173
        if self.filtered:
 
3174
            return iter(self._tests)
 
3175
        self.filtered = True
 
3176
        suites = split_suite_by_re(self, self.pattern)
 
3177
        del self._tests[:]
 
3178
        self.addTests(suites)
 
3179
        return iter(self._tests)
 
3180
 
 
3181
 
 
3182
def partition_tests(suite, count):
 
3183
    """Partition suite into count lists of tests."""
 
3184
    result = []
 
3185
    tests = list(iter_suite_tests(suite))
 
3186
    tests_per_process = int(math.ceil(float(len(tests)) / count))
 
3187
    for block in range(count):
 
3188
        low_test = block * tests_per_process
 
3189
        high_test = low_test + tests_per_process
 
3190
        process_tests = tests[low_test:high_test]
 
3191
        result.append(process_tests)
 
3192
    return result
 
3193
 
 
3194
 
 
3195
def fork_for_tests(suite):
 
3196
    """Take suite and start up one runner per CPU by forking()
 
3197
 
 
3198
    :return: An iterable of TestCase-like objects which can each have
 
3199
        run(result) called on them to feed tests to result.
 
3200
    """
 
3201
    concurrency = osutils.local_concurrency()
 
3202
    result = []
 
3203
    from subunit import TestProtocolClient, ProtocolTestCase
 
3204
    from subunit.test_results import AutoTimingTestResultDecorator
 
3205
    class TestInOtherProcess(ProtocolTestCase):
 
3206
        # Should be in subunit, I think. RBC.
 
3207
        def __init__(self, stream, pid):
 
3208
            ProtocolTestCase.__init__(self, stream)
 
3209
            self.pid = pid
 
3210
 
 
3211
        def run(self, result):
 
3212
            try:
 
3213
                ProtocolTestCase.run(self, result)
 
3214
            finally:
 
3215
                os.waitpid(self.pid, os.WNOHANG)
 
3216
 
 
3217
    test_blocks = partition_tests(suite, concurrency)
 
3218
    for process_tests in test_blocks:
 
3219
        process_suite = TestSuite()
 
3220
        process_suite.addTests(process_tests)
 
3221
        c2pread, c2pwrite = os.pipe()
 
3222
        pid = os.fork()
 
3223
        if pid == 0:
 
3224
            try:
 
3225
                os.close(c2pread)
 
3226
                # Leave stderr and stdout open so we can see test noise
 
3227
                # Close stdin so that the child goes away if it decides to
 
3228
                # read from stdin (otherwise its a roulette to see what
 
3229
                # child actually gets keystrokes for pdb etc).
 
3230
                sys.stdin.close()
 
3231
                sys.stdin = None
 
3232
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3233
                subunit_result = AutoTimingTestResultDecorator(
 
3234
                    TestProtocolClient(stream))
 
3235
                process_suite.run(subunit_result)
 
3236
            finally:
 
3237
                os._exit(0)
2526
3238
        else:
2527
 
            suite = order_changer(filter_suite_by_re(suite, pattern))
2528
 
 
2529
 
    result = runner.run(suite)
2530
 
 
2531
 
    if strict:
2532
 
        return result.wasStrictlySuccessful()
2533
 
 
2534
 
    return result.wasSuccessful()
 
3239
            os.close(c2pwrite)
 
3240
            stream = os.fdopen(c2pread, 'rb', 1)
 
3241
            test = TestInOtherProcess(stream, pid)
 
3242
            result.append(test)
 
3243
    return result
 
3244
 
 
3245
 
 
3246
def reinvoke_for_tests(suite):
 
3247
    """Take suite and start up one runner per CPU using subprocess().
 
3248
 
 
3249
    :return: An iterable of TestCase-like objects which can each have
 
3250
        run(result) called on them to feed tests to result.
 
3251
    """
 
3252
    concurrency = osutils.local_concurrency()
 
3253
    result = []
 
3254
    from subunit import ProtocolTestCase
 
3255
    class TestInSubprocess(ProtocolTestCase):
 
3256
        def __init__(self, process, name):
 
3257
            ProtocolTestCase.__init__(self, process.stdout)
 
3258
            self.process = process
 
3259
            self.process.stdin.close()
 
3260
            self.name = name
 
3261
 
 
3262
        def run(self, result):
 
3263
            try:
 
3264
                ProtocolTestCase.run(self, result)
 
3265
            finally:
 
3266
                self.process.wait()
 
3267
                os.unlink(self.name)
 
3268
            # print "pid %d finished" % finished_process
 
3269
    test_blocks = partition_tests(suite, concurrency)
 
3270
    for process_tests in test_blocks:
 
3271
        # ugly; currently reimplement rather than reuses TestCase methods.
 
3272
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
3273
        if not os.path.isfile(bzr_path):
 
3274
            # We are probably installed. Assume sys.argv is the right file
 
3275
            bzr_path = sys.argv[0]
 
3276
        bzr_path = [bzr_path]
 
3277
        if sys.platform == "win32":
 
3278
            # if we're on windows, we can't execute the bzr script directly
 
3279
            bzr_path = [sys.executable] + bzr_path
 
3280
        fd, test_list_file_name = tempfile.mkstemp()
 
3281
        test_list_file = os.fdopen(fd, 'wb', 1)
 
3282
        for test in process_tests:
 
3283
            test_list_file.write(test.id() + '\n')
 
3284
        test_list_file.close()
 
3285
        try:
 
3286
            argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
 
3287
                '--subunit']
 
3288
            if '--no-plugins' in sys.argv:
 
3289
                argv.append('--no-plugins')
 
3290
            # stderr=STDOUT would be ideal, but until we prevent noise on
 
3291
            # stderr it can interrupt the subunit protocol.
 
3292
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
 
3293
                bufsize=1)
 
3294
            test = TestInSubprocess(process, test_list_file_name)
 
3295
            result.append(test)
 
3296
        except:
 
3297
            os.unlink(test_list_file_name)
 
3298
            raise
 
3299
    return result
 
3300
 
 
3301
 
 
3302
class ForwardingResult(unittest.TestResult):
 
3303
 
 
3304
    def __init__(self, target):
 
3305
        unittest.TestResult.__init__(self)
 
3306
        self.result = target
 
3307
 
 
3308
    def startTest(self, test):
 
3309
        self.result.startTest(test)
 
3310
 
 
3311
    def stopTest(self, test):
 
3312
        self.result.stopTest(test)
 
3313
 
 
3314
    def startTestRun(self):
 
3315
        self.result.startTestRun()
 
3316
 
 
3317
    def stopTestRun(self):
 
3318
        self.result.stopTestRun()
 
3319
 
 
3320
    def addSkip(self, test, reason):
 
3321
        self.result.addSkip(test, reason)
 
3322
 
 
3323
    def addSuccess(self, test):
 
3324
        self.result.addSuccess(test)
 
3325
 
 
3326
    def addError(self, test, err):
 
3327
        self.result.addError(test, err)
 
3328
 
 
3329
    def addFailure(self, test, err):
 
3330
        self.result.addFailure(test, err)
 
3331
ForwardingResult = testtools.ExtendedToOriginalDecorator
 
3332
 
 
3333
 
 
3334
class ProfileResult(ForwardingResult):
 
3335
    """Generate profiling data for all activity between start and success.
 
3336
    
 
3337
    The profile data is appended to the test's _benchcalls attribute and can
 
3338
    be accessed by the forwarded-to TestResult.
 
3339
 
 
3340
    While it might be cleaner do accumulate this in stopTest, addSuccess is
 
3341
    where our existing output support for lsprof is, and this class aims to
 
3342
    fit in with that: while it could be moved it's not necessary to accomplish
 
3343
    test profiling, nor would it be dramatically cleaner.
 
3344
    """
 
3345
 
 
3346
    def startTest(self, test):
 
3347
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3348
        self.profiler.start()
 
3349
        ForwardingResult.startTest(self, test)
 
3350
 
 
3351
    def addSuccess(self, test):
 
3352
        stats = self.profiler.stop()
 
3353
        try:
 
3354
            calls = test._benchcalls
 
3355
        except AttributeError:
 
3356
            test._benchcalls = []
 
3357
            calls = test._benchcalls
 
3358
        calls.append(((test.id(), "", ""), stats))
 
3359
        ForwardingResult.addSuccess(self, test)
 
3360
 
 
3361
    def stopTest(self, test):
 
3362
        ForwardingResult.stopTest(self, test)
 
3363
        self.profiler = None
2535
3364
 
2536
3365
 
2537
3366
# Controlled by "bzr selftest -E=..." option
 
3367
# Currently supported:
 
3368
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
 
3369
#                           preserves any flags supplied at the command line.
 
3370
#   -Edisable_lock_checks   Turns errors in mismatched locks into simple prints
 
3371
#                           rather than failing tests. And no longer raise
 
3372
#                           LockContention when fctnl locks are not being used
 
3373
#                           with proper exclusion rules.
2538
3374
selftest_debug_flags = set()
2539
3375
 
2540
3376
 
2551
3387
             load_list=None,
2552
3388
             debug_flags=None,
2553
3389
             starting_with=None,
 
3390
             runner_class=None,
 
3391
             suite_decorators=None,
 
3392
             stream=None,
 
3393
             lsprof_tests=False,
2554
3394
             ):
2555
3395
    """Run the whole test suite under the enhanced runner"""
2556
3396
    # XXX: Very ugly way to do this...
2573
3413
            keep_only = None
2574
3414
        else:
2575
3415
            keep_only = load_test_id_list(load_list)
 
3416
        if starting_with:
 
3417
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
 
3418
                             for start in starting_with]
2576
3419
        if test_suite_factory is None:
 
3420
            # Reduce loading time by loading modules based on the starting_with
 
3421
            # patterns.
2577
3422
            suite = test_suite(keep_only, starting_with)
2578
3423
        else:
2579
3424
            suite = test_suite_factory()
 
3425
        if starting_with:
 
3426
            # But always filter as requested.
 
3427
            suite = filter_suite_by_id_startswith(suite, starting_with)
 
3428
        result_decorators = []
 
3429
        if lsprof_tests:
 
3430
            result_decorators.append(ProfileResult)
2580
3431
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
2581
3432
                     stop_on_failure=stop_on_failure,
2582
3433
                     transport=transport,
2586
3437
                     list_only=list_only,
2587
3438
                     random_seed=random_seed,
2588
3439
                     exclude_pattern=exclude_pattern,
2589
 
                     strict=strict)
 
3440
                     strict=strict,
 
3441
                     runner_class=runner_class,
 
3442
                     suite_decorators=suite_decorators,
 
3443
                     stream=stream,
 
3444
                     result_decorators=result_decorators,
 
3445
                     )
2590
3446
    finally:
2591
3447
        default_transport = old_transport
2592
3448
        selftest_debug_flags = old_debug_flags
2619
3475
    """Warns about tests not appearing or appearing more than once.
2620
3476
 
2621
3477
    :param test_suite: A TestSuite object.
2622
 
    :param test_id_list: The list of test ids that should be found in 
 
3478
    :param test_id_list: The list of test ids that should be found in
2623
3479
         test_suite.
2624
3480
 
2625
3481
    :return: (absents, duplicates) absents is a list containing the test found
2739
3595
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
2740
3596
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
2741
3597
 
2742
 
# Obvious higest levels prefixes, feel free to add your own via a plugin
 
3598
# Obvious highest levels prefixes, feel free to add your own via a plugin
2743
3599
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
2744
3600
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
2745
3601
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
2747
3603
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
2748
3604
 
2749
3605
 
 
3606
def _test_suite_testmod_names():
 
3607
    """Return the standard list of test module names to test."""
 
3608
    return [
 
3609
        'bzrlib.doc',
 
3610
        'bzrlib.tests.blackbox',
 
3611
        'bzrlib.tests.commands',
 
3612
        'bzrlib.tests.per_branch',
 
3613
        'bzrlib.tests.per_bzrdir',
 
3614
        'bzrlib.tests.per_bzrdir_colo',
 
3615
        'bzrlib.tests.per_foreign_vcs',
 
3616
        'bzrlib.tests.per_interrepository',
 
3617
        'bzrlib.tests.per_intertree',
 
3618
        'bzrlib.tests.per_inventory',
 
3619
        'bzrlib.tests.per_interbranch',
 
3620
        'bzrlib.tests.per_lock',
 
3621
        'bzrlib.tests.per_merger',
 
3622
        'bzrlib.tests.per_transport',
 
3623
        'bzrlib.tests.per_tree',
 
3624
        'bzrlib.tests.per_pack_repository',
 
3625
        'bzrlib.tests.per_repository',
 
3626
        'bzrlib.tests.per_repository_chk',
 
3627
        'bzrlib.tests.per_repository_reference',
 
3628
        'bzrlib.tests.per_uifactory',
 
3629
        'bzrlib.tests.per_versionedfile',
 
3630
        'bzrlib.tests.per_workingtree',
 
3631
        'bzrlib.tests.test__annotator',
 
3632
        'bzrlib.tests.test__bencode',
 
3633
        'bzrlib.tests.test__chk_map',
 
3634
        'bzrlib.tests.test__dirstate_helpers',
 
3635
        'bzrlib.tests.test__groupcompress',
 
3636
        'bzrlib.tests.test__known_graph',
 
3637
        'bzrlib.tests.test__rio',
 
3638
        'bzrlib.tests.test__simple_set',
 
3639
        'bzrlib.tests.test__static_tuple',
 
3640
        'bzrlib.tests.test__walkdirs_win32',
 
3641
        'bzrlib.tests.test_ancestry',
 
3642
        'bzrlib.tests.test_annotate',
 
3643
        'bzrlib.tests.test_api',
 
3644
        'bzrlib.tests.test_atomicfile',
 
3645
        'bzrlib.tests.test_bad_files',
 
3646
        'bzrlib.tests.test_bisect_multi',
 
3647
        'bzrlib.tests.test_branch',
 
3648
        'bzrlib.tests.test_branchbuilder',
 
3649
        'bzrlib.tests.test_btree_index',
 
3650
        'bzrlib.tests.test_bugtracker',
 
3651
        'bzrlib.tests.test_bundle',
 
3652
        'bzrlib.tests.test_bzrdir',
 
3653
        'bzrlib.tests.test__chunks_to_lines',
 
3654
        'bzrlib.tests.test_cache_utf8',
 
3655
        'bzrlib.tests.test_chk_map',
 
3656
        'bzrlib.tests.test_chk_serializer',
 
3657
        'bzrlib.tests.test_chunk_writer',
 
3658
        'bzrlib.tests.test_clean_tree',
 
3659
        'bzrlib.tests.test_cleanup',
 
3660
        'bzrlib.tests.test_cmdline',
 
3661
        'bzrlib.tests.test_commands',
 
3662
        'bzrlib.tests.test_commit',
 
3663
        'bzrlib.tests.test_commit_merge',
 
3664
        'bzrlib.tests.test_config',
 
3665
        'bzrlib.tests.test_conflicts',
 
3666
        'bzrlib.tests.test_counted_lock',
 
3667
        'bzrlib.tests.test_crash',
 
3668
        'bzrlib.tests.test_decorators',
 
3669
        'bzrlib.tests.test_delta',
 
3670
        'bzrlib.tests.test_debug',
 
3671
        'bzrlib.tests.test_deprecated_graph',
 
3672
        'bzrlib.tests.test_diff',
 
3673
        'bzrlib.tests.test_directory_service',
 
3674
        'bzrlib.tests.test_dirstate',
 
3675
        'bzrlib.tests.test_email_message',
 
3676
        'bzrlib.tests.test_eol_filters',
 
3677
        'bzrlib.tests.test_errors',
 
3678
        'bzrlib.tests.test_export',
 
3679
        'bzrlib.tests.test_extract',
 
3680
        'bzrlib.tests.test_fetch',
 
3681
        'bzrlib.tests.test_fifo_cache',
 
3682
        'bzrlib.tests.test_filters',
 
3683
        'bzrlib.tests.test_ftp_transport',
 
3684
        'bzrlib.tests.test_foreign',
 
3685
        'bzrlib.tests.test_generate_docs',
 
3686
        'bzrlib.tests.test_generate_ids',
 
3687
        'bzrlib.tests.test_globbing',
 
3688
        'bzrlib.tests.test_gpg',
 
3689
        'bzrlib.tests.test_graph',
 
3690
        'bzrlib.tests.test_groupcompress',
 
3691
        'bzrlib.tests.test_hashcache',
 
3692
        'bzrlib.tests.test_help',
 
3693
        'bzrlib.tests.test_hooks',
 
3694
        'bzrlib.tests.test_http',
 
3695
        'bzrlib.tests.test_http_response',
 
3696
        'bzrlib.tests.test_https_ca_bundle',
 
3697
        'bzrlib.tests.test_identitymap',
 
3698
        'bzrlib.tests.test_ignores',
 
3699
        'bzrlib.tests.test_index',
 
3700
        'bzrlib.tests.test_import_tariff',
 
3701
        'bzrlib.tests.test_info',
 
3702
        'bzrlib.tests.test_inv',
 
3703
        'bzrlib.tests.test_inventory_delta',
 
3704
        'bzrlib.tests.test_knit',
 
3705
        'bzrlib.tests.test_lazy_import',
 
3706
        'bzrlib.tests.test_lazy_regex',
 
3707
        'bzrlib.tests.test_lock',
 
3708
        'bzrlib.tests.test_lockable_files',
 
3709
        'bzrlib.tests.test_lockdir',
 
3710
        'bzrlib.tests.test_log',
 
3711
        'bzrlib.tests.test_lru_cache',
 
3712
        'bzrlib.tests.test_lsprof',
 
3713
        'bzrlib.tests.test_mail_client',
 
3714
        'bzrlib.tests.test_memorytree',
 
3715
        'bzrlib.tests.test_merge',
 
3716
        'bzrlib.tests.test_merge3',
 
3717
        'bzrlib.tests.test_merge_core',
 
3718
        'bzrlib.tests.test_merge_directive',
 
3719
        'bzrlib.tests.test_missing',
 
3720
        'bzrlib.tests.test_msgeditor',
 
3721
        'bzrlib.tests.test_multiparent',
 
3722
        'bzrlib.tests.test_mutabletree',
 
3723
        'bzrlib.tests.test_nonascii',
 
3724
        'bzrlib.tests.test_options',
 
3725
        'bzrlib.tests.test_osutils',
 
3726
        'bzrlib.tests.test_osutils_encodings',
 
3727
        'bzrlib.tests.test_pack',
 
3728
        'bzrlib.tests.test_patch',
 
3729
        'bzrlib.tests.test_patches',
 
3730
        'bzrlib.tests.test_permissions',
 
3731
        'bzrlib.tests.test_plugins',
 
3732
        'bzrlib.tests.test_progress',
 
3733
        'bzrlib.tests.test_read_bundle',
 
3734
        'bzrlib.tests.test_reconcile',
 
3735
        'bzrlib.tests.test_reconfigure',
 
3736
        'bzrlib.tests.test_registry',
 
3737
        'bzrlib.tests.test_remote',
 
3738
        'bzrlib.tests.test_rename_map',
 
3739
        'bzrlib.tests.test_repository',
 
3740
        'bzrlib.tests.test_revert',
 
3741
        'bzrlib.tests.test_revision',
 
3742
        'bzrlib.tests.test_revisionspec',
 
3743
        'bzrlib.tests.test_revisiontree',
 
3744
        'bzrlib.tests.test_rio',
 
3745
        'bzrlib.tests.test_rules',
 
3746
        'bzrlib.tests.test_sampler',
 
3747
        'bzrlib.tests.test_script',
 
3748
        'bzrlib.tests.test_selftest',
 
3749
        'bzrlib.tests.test_serializer',
 
3750
        'bzrlib.tests.test_setup',
 
3751
        'bzrlib.tests.test_sftp_transport',
 
3752
        'bzrlib.tests.test_shelf',
 
3753
        'bzrlib.tests.test_shelf_ui',
 
3754
        'bzrlib.tests.test_smart',
 
3755
        'bzrlib.tests.test_smart_add',
 
3756
        'bzrlib.tests.test_smart_request',
 
3757
        'bzrlib.tests.test_smart_transport',
 
3758
        'bzrlib.tests.test_smtp_connection',
 
3759
        'bzrlib.tests.test_source',
 
3760
        'bzrlib.tests.test_ssh_transport',
 
3761
        'bzrlib.tests.test_status',
 
3762
        'bzrlib.tests.test_store',
 
3763
        'bzrlib.tests.test_strace',
 
3764
        'bzrlib.tests.test_subsume',
 
3765
        'bzrlib.tests.test_switch',
 
3766
        'bzrlib.tests.test_symbol_versioning',
 
3767
        'bzrlib.tests.test_tag',
 
3768
        'bzrlib.tests.test_testament',
 
3769
        'bzrlib.tests.test_textfile',
 
3770
        'bzrlib.tests.test_textmerge',
 
3771
        'bzrlib.tests.test_timestamp',
 
3772
        'bzrlib.tests.test_trace',
 
3773
        'bzrlib.tests.test_transactions',
 
3774
        'bzrlib.tests.test_transform',
 
3775
        'bzrlib.tests.test_transport',
 
3776
        'bzrlib.tests.test_transport_log',
 
3777
        'bzrlib.tests.test_tree',
 
3778
        'bzrlib.tests.test_treebuilder',
 
3779
        'bzrlib.tests.test_tsort',
 
3780
        'bzrlib.tests.test_tuned_gzip',
 
3781
        'bzrlib.tests.test_ui',
 
3782
        'bzrlib.tests.test_uncommit',
 
3783
        'bzrlib.tests.test_upgrade',
 
3784
        'bzrlib.tests.test_upgrade_stacked',
 
3785
        'bzrlib.tests.test_urlutils',
 
3786
        'bzrlib.tests.test_version',
 
3787
        'bzrlib.tests.test_version_info',
 
3788
        'bzrlib.tests.test_weave',
 
3789
        'bzrlib.tests.test_whitebox',
 
3790
        'bzrlib.tests.test_win32utils',
 
3791
        'bzrlib.tests.test_workingtree',
 
3792
        'bzrlib.tests.test_workingtree_4',
 
3793
        'bzrlib.tests.test_wsgi',
 
3794
        'bzrlib.tests.test_xml',
 
3795
        ]
 
3796
 
 
3797
 
 
3798
def _test_suite_modules_to_doctest():
 
3799
    """Return the list of modules to doctest."""   
 
3800
    return [
 
3801
        'bzrlib',
 
3802
        'bzrlib.branchbuilder',
 
3803
        'bzrlib.decorators',
 
3804
        'bzrlib.export',
 
3805
        'bzrlib.inventory',
 
3806
        'bzrlib.iterablefile',
 
3807
        'bzrlib.lockdir',
 
3808
        'bzrlib.merge3',
 
3809
        'bzrlib.option',
 
3810
        'bzrlib.symbol_versioning',
 
3811
        'bzrlib.tests',
 
3812
        'bzrlib.timestamp',
 
3813
        'bzrlib.version_info_formats.format_custom',
 
3814
        ]
 
3815
 
 
3816
 
2750
3817
def test_suite(keep_only=None, starting_with=None):
2751
3818
    """Build and return TestSuite for the whole of bzrlib.
2752
3819
 
2758
3825
    This function can be replaced if you need to change the default test
2759
3826
    suite on a global basis, but it is not encouraged.
2760
3827
    """
2761
 
    testmod_names = [
2762
 
                   'bzrlib.doc',
2763
 
                   'bzrlib.util.tests.test_bencode',
2764
 
                   'bzrlib.tests.blackbox',
2765
 
                   'bzrlib.tests.branch_implementations',
2766
 
                   'bzrlib.tests.bzrdir_implementations',
2767
 
                   'bzrlib.tests.commands',
2768
 
                   'bzrlib.tests.inventory_implementations',
2769
 
                   'bzrlib.tests.interrepository_implementations',
2770
 
                   'bzrlib.tests.intertree_implementations',
2771
 
                   'bzrlib.tests.per_lock',
2772
 
                   'bzrlib.tests.per_repository',
2773
 
                   'bzrlib.tests.test__dirstate_helpers',
2774
 
                   'bzrlib.tests.test_ancestry',
2775
 
                   'bzrlib.tests.test_annotate',
2776
 
                   'bzrlib.tests.test_api',
2777
 
                   'bzrlib.tests.test_atomicfile',
2778
 
                   'bzrlib.tests.test_bad_files',
2779
 
                   'bzrlib.tests.test_bisect_multi',
2780
 
                   'bzrlib.tests.test_branch',
2781
 
                   'bzrlib.tests.test_branchbuilder',
2782
 
                   'bzrlib.tests.test_btree_index',
2783
 
                   'bzrlib.tests.test_bugtracker',
2784
 
                   'bzrlib.tests.test_bundle',
2785
 
                   'bzrlib.tests.test_bzrdir',
2786
 
                   'bzrlib.tests.test_cache_utf8',
2787
 
                   'bzrlib.tests.test_chunk_writer',
2788
 
                   'bzrlib.tests.test_commands',
2789
 
                   'bzrlib.tests.test_commit',
2790
 
                   'bzrlib.tests.test_commit_merge',
2791
 
                   'bzrlib.tests.test_config',
2792
 
                   'bzrlib.tests.test_conflicts',
2793
 
                   'bzrlib.tests.test_counted_lock',
2794
 
                   'bzrlib.tests.test_decorators',
2795
 
                   'bzrlib.tests.test_delta',
2796
 
                   'bzrlib.tests.test_deprecated_graph',
2797
 
                   'bzrlib.tests.test_diff',
2798
 
                   'bzrlib.tests.test_dirstate',
2799
 
                   'bzrlib.tests.test_directory_service',
2800
 
                   'bzrlib.tests.test_email_message',
2801
 
                   'bzrlib.tests.test_errors',
2802
 
                   'bzrlib.tests.test_extract',
2803
 
                   'bzrlib.tests.test_fetch',
2804
 
                   'bzrlib.tests.test_ftp_transport',
2805
 
                   'bzrlib.tests.test_generate_docs',
2806
 
                   'bzrlib.tests.test_generate_ids',
2807
 
                   'bzrlib.tests.test_globbing',
2808
 
                   'bzrlib.tests.test_gpg',
2809
 
                   'bzrlib.tests.test_graph',
2810
 
                   'bzrlib.tests.test_hashcache',
2811
 
                   'bzrlib.tests.test_help',
2812
 
                   'bzrlib.tests.test_hooks',
2813
 
                   'bzrlib.tests.test_http',
2814
 
                   'bzrlib.tests.test_http_implementations',
2815
 
                   'bzrlib.tests.test_http_response',
2816
 
                   'bzrlib.tests.test_https_ca_bundle',
2817
 
                   'bzrlib.tests.test_identitymap',
2818
 
                   'bzrlib.tests.test_ignores',
2819
 
                   'bzrlib.tests.test_index',
2820
 
                   'bzrlib.tests.test_info',
2821
 
                   'bzrlib.tests.test_inv',
2822
 
                   'bzrlib.tests.test_knit',
2823
 
                   'bzrlib.tests.test_lazy_import',
2824
 
                   'bzrlib.tests.test_lazy_regex',
2825
 
                   'bzrlib.tests.test_lockdir',
2826
 
                   'bzrlib.tests.test_lockable_files',
2827
 
                   'bzrlib.tests.test_log',
2828
 
                   'bzrlib.tests.test_lsprof',
2829
 
                   'bzrlib.tests.test_lru_cache',
2830
 
                   'bzrlib.tests.test_mail_client',
2831
 
                   'bzrlib.tests.test_memorytree',
2832
 
                   'bzrlib.tests.test_merge',
2833
 
                   'bzrlib.tests.test_merge3',
2834
 
                   'bzrlib.tests.test_merge_core',
2835
 
                   'bzrlib.tests.test_merge_directive',
2836
 
                   'bzrlib.tests.test_missing',
2837
 
                   'bzrlib.tests.test_msgeditor',
2838
 
                   'bzrlib.tests.test_multiparent',
2839
 
                   'bzrlib.tests.test_mutabletree',
2840
 
                   'bzrlib.tests.test_nonascii',
2841
 
                   'bzrlib.tests.test_options',
2842
 
                   'bzrlib.tests.test_osutils',
2843
 
                   'bzrlib.tests.test_osutils_encodings',
2844
 
                   'bzrlib.tests.test_pack',
2845
 
                   'bzrlib.tests.test_pack_repository',
2846
 
                   'bzrlib.tests.test_patch',
2847
 
                   'bzrlib.tests.test_patches',
2848
 
                   'bzrlib.tests.test_permissions',
2849
 
                   'bzrlib.tests.test_plugins',
2850
 
                   'bzrlib.tests.test_progress',
2851
 
                   'bzrlib.tests.test_read_bundle',
2852
 
                   'bzrlib.tests.test_reconfigure',
2853
 
                   'bzrlib.tests.test_reconcile',
2854
 
                   'bzrlib.tests.test_registry',
2855
 
                   'bzrlib.tests.test_remote',
2856
 
                   'bzrlib.tests.test_repository',
2857
 
                   'bzrlib.tests.per_repository_reference',
2858
 
                   'bzrlib.tests.test_revert',
2859
 
                   'bzrlib.tests.test_revision',
2860
 
                   'bzrlib.tests.test_revisionspec',
2861
 
                   'bzrlib.tests.test_revisiontree',
2862
 
                   'bzrlib.tests.test_rio',
2863
 
                   'bzrlib.tests.test_rules',
2864
 
                   'bzrlib.tests.test_sampler',
2865
 
                   'bzrlib.tests.test_selftest',
2866
 
                   'bzrlib.tests.test_setup',
2867
 
                   'bzrlib.tests.test_sftp_transport',
2868
 
                   'bzrlib.tests.test_smart',
2869
 
                   'bzrlib.tests.test_smart_add',
2870
 
                   'bzrlib.tests.test_smart_transport',
2871
 
                   'bzrlib.tests.test_smtp_connection',
2872
 
                   'bzrlib.tests.test_source',
2873
 
                   'bzrlib.tests.test_ssh_transport',
2874
 
                   'bzrlib.tests.test_status',
2875
 
                   'bzrlib.tests.test_store',
2876
 
                   'bzrlib.tests.test_strace',
2877
 
                   'bzrlib.tests.test_subsume',
2878
 
                   'bzrlib.tests.test_switch',
2879
 
                   'bzrlib.tests.test_symbol_versioning',
2880
 
                   'bzrlib.tests.test_tag',
2881
 
                   'bzrlib.tests.test_testament',
2882
 
                   'bzrlib.tests.test_textfile',
2883
 
                   'bzrlib.tests.test_textmerge',
2884
 
                   'bzrlib.tests.test_timestamp',
2885
 
                   'bzrlib.tests.test_trace',
2886
 
                   'bzrlib.tests.test_transactions',
2887
 
                   'bzrlib.tests.test_transform',
2888
 
                   'bzrlib.tests.test_transport',
2889
 
                   'bzrlib.tests.test_transport_implementations',
2890
 
                   'bzrlib.tests.test_transport_log',
2891
 
                   'bzrlib.tests.test_tree',
2892
 
                   'bzrlib.tests.test_treebuilder',
2893
 
                   'bzrlib.tests.test_tsort',
2894
 
                   'bzrlib.tests.test_tuned_gzip',
2895
 
                   'bzrlib.tests.test_ui',
2896
 
                   'bzrlib.tests.test_uncommit',
2897
 
                   'bzrlib.tests.test_upgrade',
2898
 
                   'bzrlib.tests.test_upgrade_stacked',
2899
 
                   'bzrlib.tests.test_urlutils',
2900
 
                   'bzrlib.tests.test_versionedfile',
2901
 
                   'bzrlib.tests.test_version',
2902
 
                   'bzrlib.tests.test_version_info',
2903
 
                   'bzrlib.tests.test__walkdirs_win32',
2904
 
                   'bzrlib.tests.test_weave',
2905
 
                   'bzrlib.tests.test_whitebox',
2906
 
                   'bzrlib.tests.test_win32utils',
2907
 
                   'bzrlib.tests.test_workingtree',
2908
 
                   'bzrlib.tests.test_workingtree_4',
2909
 
                   'bzrlib.tests.test_wsgi',
2910
 
                   'bzrlib.tests.test_xml',
2911
 
                   'bzrlib.tests.tree_implementations',
2912
 
                   'bzrlib.tests.workingtree_implementations',
2913
 
                   ]
2914
3828
 
2915
3829
    loader = TestUtil.TestLoader()
2916
3830
 
 
3831
    if keep_only is not None:
 
3832
        id_filter = TestIdList(keep_only)
2917
3833
    if starting_with:
2918
 
        starting_with = [test_prefix_alias_registry.resolve_alias(start)
2919
 
                         for start in starting_with]
2920
3834
        # We take precedence over keep_only because *at loading time* using
2921
3835
        # both options means we will load less tests for the same final result.
2922
3836
        def interesting_module(name):
2932
3846
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
2933
3847
 
2934
3848
    elif keep_only is not None:
2935
 
        id_filter = TestIdList(keep_only)
2936
3849
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2937
3850
        def interesting_module(name):
2938
3851
            return id_filter.refers_to(name)
2946
3859
    suite = loader.suiteClass()
2947
3860
 
2948
3861
    # modules building their suite with loadTestsFromModuleNames
2949
 
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
2950
 
 
2951
 
    modules_to_doctest = [
2952
 
        'bzrlib',
2953
 
        'bzrlib.errors',
2954
 
        'bzrlib.export',
2955
 
        'bzrlib.inventory',
2956
 
        'bzrlib.iterablefile',
2957
 
        'bzrlib.lockdir',
2958
 
        'bzrlib.merge3',
2959
 
        'bzrlib.option',
2960
 
        'bzrlib.store',
2961
 
        'bzrlib.symbol_versioning',
2962
 
        'bzrlib.tests',
2963
 
        'bzrlib.timestamp',
2964
 
        'bzrlib.version_info_formats.format_custom',
2965
 
        ]
2966
 
 
2967
 
    for mod in modules_to_doctest:
 
3862
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
 
3863
 
 
3864
    for mod in _test_suite_modules_to_doctest():
2968
3865
        if not interesting_module(mod):
2969
3866
            # No tests to keep here, move along
2970
3867
            continue
2971
3868
        try:
2972
 
            doc_suite = doctest.DocTestSuite(mod)
 
3869
            # note that this really does mean "report only" -- doctest
 
3870
            # still runs the rest of the examples
 
3871
            doc_suite = doctest.DocTestSuite(mod,
 
3872
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
2973
3873
        except ValueError, e:
2974
3874
            print '**failed to get doctest for: %s\n%s' % (mod, e)
2975
3875
            raise
 
3876
        if len(doc_suite._tests) == 0:
 
3877
            raise errors.BzrError("no doctests found in %s" % (mod,))
2976
3878
        suite.addTest(doc_suite)
2977
3879
 
2978
3880
    default_encoding = sys.getdefaultencoding()
2994
3896
            reload(sys)
2995
3897
            sys.setdefaultencoding(default_encoding)
2996
3898
 
2997
 
    if starting_with:
2998
 
        suite = filter_suite_by_id_startswith(suite, starting_with)
2999
 
 
3000
3899
    if keep_only is not None:
3001
3900
        # Now that the referred modules have loaded their tests, keep only the
3002
3901
        # requested ones.
3019
3918
    return suite
3020
3919
 
3021
3920
 
3022
 
def multiply_tests_from_modules(module_name_list, scenario_iter, loader=None):
3023
 
    """Adapt all tests in some given modules to given scenarios.
3024
 
 
3025
 
    This is the recommended public interface for test parameterization.
3026
 
    Typically the test_suite() method for a per-implementation test
3027
 
    suite will call multiply_tests_from_modules and return the 
3028
 
    result.
3029
 
 
3030
 
    :param module_name_list: List of fully-qualified names of test
3031
 
        modules.
3032
 
    :param scenario_iter: Iterable of pairs of (scenario_name, 
3033
 
        scenario_param_dict).
3034
 
    :param loader: If provided, will be used instead of a new 
3035
 
        bzrlib.tests.TestLoader() instance.
3036
 
 
3037
 
    This returns a new TestSuite containing the cross product of
3038
 
    all the tests in all the modules, each repeated for each scenario.
3039
 
    Each test is adapted by adding the scenario name at the end 
3040
 
    of its name, and updating the test object's __dict__ with the
3041
 
    scenario_param_dict.
3042
 
 
3043
 
    >>> r = multiply_tests_from_modules(
3044
 
    ...     ['bzrlib.tests.test_sampler'],
3045
 
    ...     [('one', dict(param=1)), 
3046
 
    ...      ('two', dict(param=2))])
3047
 
    >>> tests = list(iter_suite_tests(r))
3048
 
    >>> len(tests)
3049
 
    2
3050
 
    >>> tests[0].id()
3051
 
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
3052
 
    >>> tests[0].param
3053
 
    1
3054
 
    >>> tests[1].param
3055
 
    2
3056
 
    """
3057
 
    # XXX: Isn't load_tests() a better way to provide the same functionality
3058
 
    # without forcing a predefined TestScenarioApplier ? --vila 080215
3059
 
    if loader is None:
3060
 
        loader = TestUtil.TestLoader()
3061
 
 
3062
 
    suite = loader.suiteClass()
3063
 
 
3064
 
    adapter = TestScenarioApplier()
3065
 
    adapter.scenarios = list(scenario_iter)
3066
 
    adapt_modules(module_name_list, adapter, loader, suite)
3067
 
    return suite
3068
 
 
3069
 
 
3070
3921
def multiply_scenarios(scenarios_left, scenarios_right):
3071
3922
    """Multiply two sets of scenarios.
3072
3923
 
3081
3932
        for right_name, right_dict in scenarios_right]
3082
3933
 
3083
3934
 
3084
 
 
3085
 
def adapt_modules(mods_list, adapter, loader, suite):
3086
 
    """Adapt the modules in mods_list using adapter and add to suite."""
3087
 
    tests = loader.loadTestsFromModuleNames(mods_list)
3088
 
    adapt_tests(tests, adapter, suite)
3089
 
 
3090
 
 
3091
 
def adapt_tests(tests_list, adapter, suite):
3092
 
    """Adapt the tests in tests_list using adapter and add to suite."""
3093
 
    for test in iter_suite_tests(tests_list):
3094
 
        suite.addTests(adapter.adapt(test))
3095
 
 
3096
 
 
3097
 
def _rmtree_temp_dir(dirname):
 
3935
def multiply_tests(tests, scenarios, result):
 
3936
    """Multiply tests_list by scenarios into result.
 
3937
 
 
3938
    This is the core workhorse for test parameterisation.
 
3939
 
 
3940
    Typically the load_tests() method for a per-implementation test suite will
 
3941
    call multiply_tests and return the result.
 
3942
 
 
3943
    :param tests: The tests to parameterise.
 
3944
    :param scenarios: The scenarios to apply: pairs of (scenario_name,
 
3945
        scenario_param_dict).
 
3946
    :param result: A TestSuite to add created tests to.
 
3947
 
 
3948
    This returns the passed in result TestSuite with the cross product of all
 
3949
    the tests repeated once for each scenario.  Each test is adapted by adding
 
3950
    the scenario name at the end of its id(), and updating the test object's
 
3951
    __dict__ with the scenario_param_dict.
 
3952
 
 
3953
    >>> import bzrlib.tests.test_sampler
 
3954
    >>> r = multiply_tests(
 
3955
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
 
3956
    ...     [('one', dict(param=1)),
 
3957
    ...      ('two', dict(param=2))],
 
3958
    ...     TestSuite())
 
3959
    >>> tests = list(iter_suite_tests(r))
 
3960
    >>> len(tests)
 
3961
    2
 
3962
    >>> tests[0].id()
 
3963
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
3964
    >>> tests[0].param
 
3965
    1
 
3966
    >>> tests[1].param
 
3967
    2
 
3968
    """
 
3969
    for test in iter_suite_tests(tests):
 
3970
        apply_scenarios(test, scenarios, result)
 
3971
    return result
 
3972
 
 
3973
 
 
3974
def apply_scenarios(test, scenarios, result):
 
3975
    """Apply the scenarios in scenarios to test and add to result.
 
3976
 
 
3977
    :param test: The test to apply scenarios to.
 
3978
    :param scenarios: An iterable of scenarios to apply to test.
 
3979
    :return: result
 
3980
    :seealso: apply_scenario
 
3981
    """
 
3982
    for scenario in scenarios:
 
3983
        result.addTest(apply_scenario(test, scenario))
 
3984
    return result
 
3985
 
 
3986
 
 
3987
def apply_scenario(test, scenario):
 
3988
    """Copy test and apply scenario to it.
 
3989
 
 
3990
    :param test: A test to adapt.
 
3991
    :param scenario: A tuple describing the scenarion.
 
3992
        The first element of the tuple is the new test id.
 
3993
        The second element is a dict containing attributes to set on the
 
3994
        test.
 
3995
    :return: The adapted test.
 
3996
    """
 
3997
    new_id = "%s(%s)" % (test.id(), scenario[0])
 
3998
    new_test = clone_test(test, new_id)
 
3999
    for name, value in scenario[1].items():
 
4000
        setattr(new_test, name, value)
 
4001
    return new_test
 
4002
 
 
4003
 
 
4004
def clone_test(test, new_id):
 
4005
    """Clone a test giving it a new id.
 
4006
 
 
4007
    :param test: The test to clone.
 
4008
    :param new_id: The id to assign to it.
 
4009
    :return: The new test.
 
4010
    """
 
4011
    new_test = copy(test)
 
4012
    new_test.id = lambda: new_id
 
4013
    return new_test
 
4014
 
 
4015
 
 
4016
def permute_tests_for_extension(standard_tests, loader, py_module_name,
 
4017
                                ext_module_name):
 
4018
    """Helper for permutating tests against an extension module.
 
4019
 
 
4020
    This is meant to be used inside a modules 'load_tests()' function. It will
 
4021
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
 
4022
    against both implementations. Setting 'test.module' to the appropriate
 
4023
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
 
4024
 
 
4025
    :param standard_tests: A test suite to permute
 
4026
    :param loader: A TestLoader
 
4027
    :param py_module_name: The python path to a python module that can always
 
4028
        be loaded, and will be considered the 'python' implementation. (eg
 
4029
        'bzrlib._chk_map_py')
 
4030
    :param ext_module_name: The python path to an extension module. If the
 
4031
        module cannot be loaded, a single test will be added, which notes that
 
4032
        the module is not available. If it can be loaded, all standard_tests
 
4033
        will be run against that module.
 
4034
    :return: (suite, feature) suite is a test-suite that has all the permuted
 
4035
        tests. feature is the Feature object that can be used to determine if
 
4036
        the module is available.
 
4037
    """
 
4038
 
 
4039
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4040
    scenarios = [
 
4041
        ('python', {'module': py_module}),
 
4042
    ]
 
4043
    suite = loader.suiteClass()
 
4044
    feature = ModuleAvailableFeature(ext_module_name)
 
4045
    if feature.available():
 
4046
        scenarios.append(('C', {'module': feature.module}))
 
4047
    else:
 
4048
        # the compiled module isn't available, so we add a failing test
 
4049
        class FailWithoutFeature(TestCase):
 
4050
            def test_fail(self):
 
4051
                self.requireFeature(feature)
 
4052
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
 
4053
    result = multiply_tests(standard_tests, scenarios, suite)
 
4054
    return result, feature
 
4055
 
 
4056
 
 
4057
def _rmtree_temp_dir(dirname, test_id=None):
3098
4058
    # If LANG=C we probably have created some bogus paths
3099
4059
    # which rmtree(unicode) will fail to delete
3100
4060
    # so make sure we are using rmtree(str) to delete everything
3109
4069
    try:
3110
4070
        osutils.rmtree(dirname)
3111
4071
    except OSError, e:
3112
 
        if sys.platform == 'win32' and e.errno == errno.EACCES:
3113
 
            sys.stderr.write(('Permission denied: '
3114
 
                                 'unable to remove testing dir '
3115
 
                                 '%s\n' % os.path.basename(dirname)))
3116
 
        else:
3117
 
            raise
 
4072
        # We don't want to fail here because some useful display will be lost
 
4073
        # otherwise. Polluting the tmp dir is bad, but not giving all the
 
4074
        # possible info to the test runner is even worse.
 
4075
        if test_id != None:
 
4076
            ui.ui_factory.clear_term()
 
4077
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4078
        sys.stderr.write('Unable to remove testing dir %s\n%s'
 
4079
                         % (os.path.basename(dirname), e))
3118
4080
 
3119
4081
 
3120
4082
class Feature(object):
3202
4164
UnicodeFilenameFeature = _UnicodeFilenameFeature()
3203
4165
 
3204
4166
 
3205
 
class TestScenarioApplier(object):
3206
 
    """A tool to apply scenarios to tests."""
3207
 
 
3208
 
    def adapt(self, test):
3209
 
        """Return a TestSuite containing a copy of test for each scenario."""
3210
 
        result = unittest.TestSuite()
3211
 
        for scenario in self.scenarios:
3212
 
            result.addTest(self.adapt_test_to_scenario(test, scenario))
3213
 
        return result
3214
 
 
3215
 
    def adapt_test_to_scenario(self, test, scenario):
3216
 
        """Copy test and apply scenario to it.
3217
 
 
3218
 
        :param test: A test to adapt.
3219
 
        :param scenario: A tuple describing the scenarion.
3220
 
            The first element of the tuple is the new test id.
3221
 
            The second element is a dict containing attributes to set on the
3222
 
            test.
3223
 
        :return: The adapted test.
3224
 
        """
3225
 
        from copy import deepcopy
3226
 
        new_test = deepcopy(test)
3227
 
        for name, value in scenario[1].items():
3228
 
            setattr(new_test, name, value)
3229
 
        new_id = "%s(%s)" % (new_test.id(), scenario[0])
3230
 
        new_test.id = lambda: new_id
3231
 
        return new_test
 
4167
class _CompatabilityThunkFeature(Feature):
 
4168
    """This feature is just a thunk to another feature.
 
4169
 
 
4170
    It issues a deprecation warning if it is accessed, to let you know that you
 
4171
    should really use a different feature.
 
4172
    """
 
4173
 
 
4174
    def __init__(self, dep_version, module, name,
 
4175
                 replacement_name, replacement_module=None):
 
4176
        super(_CompatabilityThunkFeature, self).__init__()
 
4177
        self._module = module
 
4178
        if replacement_module is None:
 
4179
            replacement_module = module
 
4180
        self._replacement_module = replacement_module
 
4181
        self._name = name
 
4182
        self._replacement_name = replacement_name
 
4183
        self._dep_version = dep_version
 
4184
        self._feature = None
 
4185
 
 
4186
    def _ensure(self):
 
4187
        if self._feature is None:
 
4188
            depr_msg = self._dep_version % ('%s.%s'
 
4189
                                            % (self._module, self._name))
 
4190
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
 
4191
                                               self._replacement_name)
 
4192
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
 
4193
            # Import the new feature and use it as a replacement for the
 
4194
            # deprecated one.
 
4195
            mod = __import__(self._replacement_module, {}, {},
 
4196
                             [self._replacement_name])
 
4197
            self._feature = getattr(mod, self._replacement_name)
 
4198
 
 
4199
    def _probe(self):
 
4200
        self._ensure()
 
4201
        return self._feature._probe()
 
4202
 
 
4203
 
 
4204
class ModuleAvailableFeature(Feature):
 
4205
    """This is a feature than describes a module we want to be available.
 
4206
 
 
4207
    Declare the name of the module in __init__(), and then after probing, the
 
4208
    module will be available as 'self.module'.
 
4209
 
 
4210
    :ivar module: The module if it is available, else None.
 
4211
    """
 
4212
 
 
4213
    def __init__(self, module_name):
 
4214
        super(ModuleAvailableFeature, self).__init__()
 
4215
        self.module_name = module_name
 
4216
 
 
4217
    def _probe(self):
 
4218
        try:
 
4219
            self._module = __import__(self.module_name, {}, {}, [''])
 
4220
            return True
 
4221
        except ImportError:
 
4222
            return False
 
4223
 
 
4224
    @property
 
4225
    def module(self):
 
4226
        if self.available(): # Make sure the probe has been done
 
4227
            return self._module
 
4228
        return None
 
4229
 
 
4230
    def feature_name(self):
 
4231
        return self.module_name
 
4232
 
 
4233
 
 
4234
# This is kept here for compatibility, it is recommended to use
 
4235
# 'bzrlib.tests.feature.paramiko' instead
 
4236
ParamikoFeature = _CompatabilityThunkFeature(
 
4237
    deprecated_in((2,1,0)),
 
4238
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
3232
4239
 
3233
4240
 
3234
4241
def probe_unicode_in_user_encoding():
3240
4247
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
3241
4248
    for uni_val in possible_vals:
3242
4249
        try:
3243
 
            str_val = uni_val.encode(bzrlib.user_encoding)
 
4250
            str_val = uni_val.encode(osutils.get_user_encoding())
3244
4251
        except UnicodeEncodeError:
3245
4252
            # Try a different character
3246
4253
            pass
3264
4271
    return None
3265
4272
 
3266
4273
 
3267
 
class _FTPServerFeature(Feature):
3268
 
    """Some tests want an FTP Server, check if one is available.
 
4274
class _HTTPSServerFeature(Feature):
 
4275
    """Some tests want an https Server, check if one is available.
3269
4276
 
3270
 
    Right now, the only way this is available is if 'medusa' is installed.
3271
 
    http://www.amk.ca/python/code/medusa.html
 
4277
    Right now, the only way this is available is under python2.6 which provides
 
4278
    an ssl module.
3272
4279
    """
3273
4280
 
3274
4281
    def _probe(self):
3275
4282
        try:
3276
 
            import bzrlib.tests.ftp_server
 
4283
            import ssl
3277
4284
            return True
3278
4285
        except ImportError:
3279
4286
            return False
3280
4287
 
3281
4288
    def feature_name(self):
3282
 
        return 'FTPServer'
3283
 
 
3284
 
FTPServerFeature = _FTPServerFeature()
 
4289
        return 'HTTPSServer'
 
4290
 
 
4291
 
 
4292
HTTPSServerFeature = _HTTPSServerFeature()
3285
4293
 
3286
4294
 
3287
4295
class _UnicodeFilename(Feature):
3315
4323
UTF8Filesystem = _UTF8Filesystem()
3316
4324
 
3317
4325
 
 
4326
class _BreakinFeature(Feature):
 
4327
    """Does this platform support the breakin feature?"""
 
4328
 
 
4329
    def _probe(self):
 
4330
        from bzrlib import breakin
 
4331
        if breakin.determine_signal() is None:
 
4332
            return False
 
4333
        if sys.platform == 'win32':
 
4334
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
 
4335
            # We trigger SIGBREAK via a Console api so we need ctypes to
 
4336
            # access the function
 
4337
            try:
 
4338
                import ctypes
 
4339
            except OSError:
 
4340
                return False
 
4341
        return True
 
4342
 
 
4343
    def feature_name(self):
 
4344
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
 
4345
 
 
4346
 
 
4347
BreakinFeature = _BreakinFeature()
 
4348
 
 
4349
 
 
4350
class _CaseInsCasePresFilenameFeature(Feature):
 
4351
    """Is the file-system case insensitive, but case-preserving?"""
 
4352
 
 
4353
    def _probe(self):
 
4354
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
 
4355
        try:
 
4356
            # first check truly case-preserving for created files, then check
 
4357
            # case insensitive when opening existing files.
 
4358
            name = osutils.normpath(name)
 
4359
            base, rel = osutils.split(name)
 
4360
            found_rel = osutils.canonical_relpath(base, name)
 
4361
            return (found_rel == rel
 
4362
                    and os.path.isfile(name.upper())
 
4363
                    and os.path.isfile(name.lower()))
 
4364
        finally:
 
4365
            os.close(fileno)
 
4366
            os.remove(name)
 
4367
 
 
4368
    def feature_name(self):
 
4369
        return "case-insensitive case-preserving filesystem"
 
4370
 
 
4371
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
 
4372
 
 
4373
 
3318
4374
class _CaseInsensitiveFilesystemFeature(Feature):
3319
 
    """Check if underlying filesystem is case-insensitive
3320
 
    (e.g. on Windows, Cygwin, MacOS)
 
4375
    """Check if underlying filesystem is case-insensitive but *not* case
 
4376
    preserving.
3321
4377
    """
 
4378
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
 
4379
    # more likely to be case preserving, so this case is rare.
3322
4380
 
3323
4381
    def _probe(self):
 
4382
        if CaseInsCasePresFilenameFeature.available():
 
4383
            return False
 
4384
 
3324
4385
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
3325
4386
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
3326
4387
            TestCaseWithMemoryTransport.TEST_ROOT = root
3339
4400
        return 'case-insensitive filesystem'
3340
4401
 
3341
4402
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
 
4403
 
 
4404
 
 
4405
class _CaseSensitiveFilesystemFeature(Feature):
 
4406
 
 
4407
    def _probe(self):
 
4408
        if CaseInsCasePresFilenameFeature.available():
 
4409
            return False
 
4410
        elif CaseInsensitiveFilesystemFeature.available():
 
4411
            return False
 
4412
        else:
 
4413
            return True
 
4414
 
 
4415
    def feature_name(self):
 
4416
        return 'case-sensitive filesystem'
 
4417
 
 
4418
# new coding style is for feature instances to be lowercase
 
4419
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
 
4420
 
 
4421
 
 
4422
# Kept for compatibility, use bzrlib.tests.features.subunit instead
 
4423
SubUnitFeature = _CompatabilityThunkFeature(
 
4424
    deprecated_in((2,1,0)),
 
4425
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
 
4426
# Only define SubUnitBzrRunner if subunit is available.
 
4427
try:
 
4428
    from subunit import TestProtocolClient
 
4429
    from subunit.test_results import AutoTimingTestResultDecorator
 
4430
    class SubUnitBzrRunner(TextTestRunner):
 
4431
        def run(self, test):
 
4432
            result = AutoTimingTestResultDecorator(
 
4433
                TestProtocolClient(self.stream))
 
4434
            test.run(result)
 
4435
            return result
 
4436
except ImportError:
 
4437
    pass
 
4438
 
 
4439
class _PosixPermissionsFeature(Feature):
 
4440
 
 
4441
    def _probe(self):
 
4442
        def has_perms():
 
4443
            # create temporary file and check if specified perms are maintained.
 
4444
            import tempfile
 
4445
 
 
4446
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
 
4447
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
 
4448
            fd, name = f
 
4449
            os.close(fd)
 
4450
            os.chmod(name, write_perms)
 
4451
 
 
4452
            read_perms = os.stat(name).st_mode & 0777
 
4453
            os.unlink(name)
 
4454
            return (write_perms == read_perms)
 
4455
 
 
4456
        return (os.name == 'posix') and has_perms()
 
4457
 
 
4458
    def feature_name(self):
 
4459
        return 'POSIX permissions support'
 
4460
 
 
4461
posix_permissions_feature = _PosixPermissionsFeature()