~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
"""Testing framework extensions"""
17
18
 
18
19
# TODO: Perhaps there should be an API to find out if bzr running under the
19
20
# test suite -- some plugins might want to avoid making intrusive changes if
28
29
 
29
30
import atexit
30
31
import codecs
 
32
import copy
31
33
from cStringIO import StringIO
32
34
import difflib
33
35
import doctest
35
37
import logging
36
38
import math
37
39
import os
38
 
from pprint import pformat
 
40
import pprint
39
41
import random
40
42
import re
41
43
import shlex
42
44
import stat
43
 
from subprocess import Popen, PIPE, STDOUT
 
45
import subprocess
44
46
import sys
45
47
import tempfile
46
48
import threading
47
49
import time
 
50
import traceback
48
51
import unittest
49
52
import warnings
50
53
 
 
54
import testtools
 
55
# nb: check this before importing anything else from within it
 
56
_testtools_version = getattr(testtools, '__version__', ())
 
57
if _testtools_version < (0, 9, 2):
 
58
    raise ImportError("need at least testtools 0.9.2: %s is %r"
 
59
        % (testtools.__file__, _testtools_version))
 
60
from testtools import content
51
61
 
52
62
from bzrlib import (
53
63
    branchbuilder,
54
64
    bzrdir,
 
65
    chk_map,
 
66
    config,
55
67
    debug,
56
68
    errors,
57
69
    hooks,
 
70
    lock as _mod_lock,
58
71
    memorytree,
59
72
    osutils,
60
73
    progress,
61
74
    ui,
62
75
    urlutils,
63
76
    registry,
 
77
    transport as _mod_transport,
64
78
    workingtree,
65
79
    )
66
80
import bzrlib.branch
84
98
from bzrlib.symbol_versioning import (
85
99
    DEPRECATED_PARAMETER,
86
100
    deprecated_function,
 
101
    deprecated_in,
87
102
    deprecated_method,
88
103
    deprecated_passed,
89
104
    )
90
105
import bzrlib.trace
91
 
from bzrlib.transport import get_transport
92
 
import bzrlib.transport
93
 
from bzrlib.transport.local import LocalURLServer
94
 
from bzrlib.transport.memory import MemoryServer
95
 
from bzrlib.transport.readonly import ReadonlyServer
 
106
from bzrlib.transport import (
 
107
    memory,
 
108
    pathfilter,
 
109
    )
96
110
from bzrlib.trace import mutter, note
97
 
from bzrlib.tests import TestUtil
 
111
from bzrlib.tests import (
 
112
    test_server,
 
113
    TestUtil,
 
114
    treeshape,
 
115
    )
98
116
from bzrlib.tests.http_server import HttpServer
99
117
from bzrlib.tests.TestUtil import (
100
118
                          TestSuite,
101
119
                          TestLoader,
102
120
                          )
103
 
from bzrlib.tests.treeshape import build_tree_contents
 
121
from bzrlib.ui import NullProgressView
 
122
from bzrlib.ui.text import TextUIFactory
104
123
import bzrlib.version_info_formats.format_custom
105
124
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
106
125
 
109
128
# shown frame is the test code, not our assertXYZ.
110
129
__unittest = 1
111
130
 
112
 
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
113
141
 
114
142
 
115
143
class ExtendedTestResult(unittest._TextTestResult):
132
160
 
133
161
    def __init__(self, stream, descriptions, verbosity,
134
162
                 bench_history=None,
135
 
                 num_tests=None,
136
163
                 strict=False,
137
164
                 ):
138
165
        """Construct new TestResult.
157
184
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
158
185
        self._bench_history = bench_history
159
186
        self.ui = ui.ui_factory
160
 
        self.num_tests = num_tests
 
187
        self.num_tests = 0
161
188
        self.error_count = 0
162
189
        self.failure_count = 0
163
190
        self.known_failure_count = 0
168
195
        self._overall_start_time = time.time()
169
196
        self._strict = strict
170
197
 
171
 
    def done(self):
 
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))
172
235
        if self._strict:
173
236
            ok = self.wasStrictlySuccessful()
174
237
        else:
175
238
            ok = self.wasSuccessful()
176
 
        if ok:
177
 
            self.stream.write('tests passed\n')
178
 
        else:
179
 
            self.stream.write('tests failed\n')
180
239
        if TestCase._first_thread_leaker_id:
181
240
            self.stream.write(
182
241
                '%s is leaking threads among %d leaking tests.\n' % (
183
242
                TestCase._first_thread_leaker_id,
184
243
                TestCase._leaking_threads_tests))
185
 
 
186
 
    def _extractBenchmarkTime(self, testCase):
 
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):
187
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()))
188
256
        return getattr(testCase, "_benchtime", None)
189
257
 
190
258
    def _elapsedTestTimeString(self):
194
262
    def _testTimeString(self, testCase):
195
263
        benchmark_time = self._extractBenchmarkTime(testCase)
196
264
        if benchmark_time is not None:
197
 
            return "%s/%s" % (
198
 
                self._formatTime(benchmark_time),
199
 
                self._elapsedTestTimeString())
 
265
            return self._formatTime(benchmark_time) + "*"
200
266
        else:
201
 
            return "           %s" % self._elapsedTestTimeString()
 
267
            return self._elapsedTestTimeString()
202
268
 
203
269
    def _formatTime(self, seconds):
204
270
        """Format seconds as milliseconds with leading spaces."""
220
286
        self._recordTestStartTime()
221
287
 
222
288
    def startTests(self):
223
 
        self.stream.write(
224
 
            'testing: %s\n' % (osutils.realpath(sys.argv[0]),))
225
 
        self.stream.write(
226
 
            '   %s (%s python%s)\n' % (
227
 
                    bzrlib.__path__[0],
 
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' % (
228
301
                    bzrlib.version_string,
229
302
                    bzrlib._format_version_tuple(sys.version_info),
 
303
                    platform.platform(aliased=1),
230
304
                    ))
231
305
        self.stream.write('\n')
232
306
 
247
321
        Called from the TestCase run() method when the test
248
322
        fails with an unexpected error.
249
323
        """
250
 
        self._testConcluded(test)
251
 
        if isinstance(err[1], TestNotApplicable):
252
 
            return self._addNotApplicable(test, err)
253
 
        elif isinstance(err[1], UnavailableFeature):
254
 
            return self.addNotSupported(test, err[1].args[0])
255
 
        else:
256
 
            unittest.TestResult.addError(self, test, err)
257
 
            self.error_count += 1
258
 
            self.report_error(test, err)
259
 
            if self.stop_early:
260
 
                self.stop()
261
 
            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)
262
331
 
263
332
    def addFailure(self, test, err):
264
333
        """Tell result that test failed.
266
335
        Called from the TestCase run() method when the test
267
336
        fails because e.g. an assert() method failed.
268
337
        """
269
 
        self._testConcluded(test)
270
 
        if isinstance(err[1], KnownFailure):
271
 
            return self._addKnownFailure(test, err)
272
 
        else:
273
 
            unittest.TestResult.addFailure(self, test, err)
274
 
            self.failure_count += 1
275
 
            self.report_failure(test, err)
276
 
            if self.stop_early:
277
 
                self.stop()
278
 
            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)
279
345
 
280
 
    def addSuccess(self, test):
 
346
    def addSuccess(self, test, details=None):
281
347
        """Tell result that test completed successfully.
282
348
 
283
349
        Called from the TestCase run()
284
350
        """
285
 
        self._testConcluded(test)
286
351
        if self._bench_history is not None:
287
 
            benchmark_time = self._extractBenchmarkTime(test)
 
352
            benchmark_time = self._extractBenchmarkTime(test, details)
288
353
            if benchmark_time is not None:
289
354
                self._bench_history.write("%s %s\n" % (
290
355
                    self._formatTime(benchmark_time),
294
359
        unittest.TestResult.addSuccess(self, test)
295
360
        test._log_contents = ''
296
361
 
297
 
    def _testConcluded(self, test):
298
 
        """Common code when a test has finished.
299
 
 
300
 
        Called regardless of whether it succeded, failed, etc.
301
 
        """
302
 
        pass
303
 
 
304
 
    def _addKnownFailure(self, test, err):
 
362
    def addExpectedFailure(self, test, err):
305
363
        self.known_failure_count += 1
306
364
        self.report_known_failure(test, err)
307
365
 
309
367
        """The test will not be run because of a missing feature.
310
368
        """
311
369
        # this can be called in two different ways: it may be that the
312
 
        # test started running, and then raised (through addError)
 
370
        # test started running, and then raised (through requireFeature)
313
371
        # UnavailableFeature.  Alternatively this method can be called
314
 
        # while probing for features before running the tests; in that
315
 
        # case we will see startTest and stopTest, but the test will never
316
 
        # 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.
317
375
        self.unsupported.setdefault(str(feature), 0)
318
376
        self.unsupported[str(feature)] += 1
319
377
        self.report_unsupported(test, feature)
323
381
        self.skip_count += 1
324
382
        self.report_skip(test, reason)
325
383
 
326
 
    def _addNotApplicable(self, test, skip_excinfo):
327
 
        if isinstance(skip_excinfo[1], TestNotApplicable):
328
 
            self.not_applicable_count += 1
329
 
            self.report_not_applicable(test, skip_excinfo)
330
 
        try:
331
 
            test.tearDown()
332
 
        except KeyboardInterrupt:
333
 
            raise
334
 
        except:
335
 
            self.addError(test, test.exc_info())
 
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
336
399
        else:
337
 
            # seems best to treat this as success from point-of-view of unittest
338
 
            # -- it actually does nothing so it barely matters :)
339
 
            unittest.TestResult.addSuccess(self, test)
340
 
            test._log_contents = ''
341
 
 
342
 
    def printErrorList(self, flavour, errors):
343
 
        for test, err in errors:
344
 
            self.stream.writeln(self.separator1)
345
 
            self.stream.write("%s: " % flavour)
346
 
            self.stream.writeln(self.getDescription(test))
347
 
            if getattr(test, '_get_log', None) is not None:
348
 
                self.stream.write('\n')
349
 
                self.stream.write(
350
 
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
351
 
                self.stream.write('\n')
352
 
                self.stream.write(test._get_log())
353
 
                self.stream.write('\n')
354
 
                self.stream.write(
355
 
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
356
 
                self.stream.write('\n')
357
 
            self.stream.writeln(self.separator2)
358
 
            self.stream.writeln("%s" % err)
359
 
 
360
 
    def finished(self):
361
 
        pass
 
400
            raise errors.BzrError("Unknown whence %r" % whence)
362
401
 
363
402
    def report_cleaning_up(self):
364
403
        pass
365
404
 
 
405
    def startTestRun(self):
 
406
        self.startTime = time.time()
 
407
 
366
408
    def report_success(self, test):
367
409
        pass
368
410
 
377
419
 
378
420
    def __init__(self, stream, descriptions, verbosity,
379
421
                 bench_history=None,
380
 
                 num_tests=None,
381
422
                 pb=None,
382
423
                 strict=None,
383
424
                 ):
384
425
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
385
 
            bench_history, num_tests, strict)
386
 
        if pb is None:
387
 
            self.pb = self.ui.nested_progress_bar()
388
 
            self._supplied_pb = False
389
 
        else:
390
 
            self.pb = pb
391
 
            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()
392
432
        self.pb.show_pct = False
393
433
        self.pb.show_spinner = False
394
434
        self.pb.show_eta = False,
395
435
        self.pb.show_count = False
396
436
        self.pb.show_bar = False
397
 
 
398
 
    def report_starting(self):
 
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()
399
448
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
400
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()
 
454
 
401
455
    def _progress_prefix_text(self):
402
456
        # the longer this text, the less space we have to show the test
403
457
        # name...
408
462
        ##     a += ', %d skip' % self.skip_count
409
463
        ## if self.known_failure_count:
410
464
        ##     a += '+%dX' % self.known_failure_count
411
 
        if self.num_tests is not None:
 
465
        if self.num_tests:
412
466
            a +='/%d' % self.num_tests
413
467
        a += ' in '
414
468
        runtime = time.time() - self._overall_start_time
416
470
            a += '%dm%ds' % (runtime / 60, runtime % 60)
417
471
        else:
418
472
            a += '%ds' % runtime
419
 
        if self.error_count:
420
 
            a += ', %d err' % self.error_count
421
 
        if self.failure_count:
422
 
            a += ', %d fail' % self.failure_count
423
 
        if self.unsupported:
424
 
            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)
425
478
        a += ']'
426
479
        return a
427
480
 
436
489
        return self._shortened_test_description(test)
437
490
 
438
491
    def report_error(self, test, err):
439
 
        self.pb.note('ERROR: %s\n    %s\n',
 
492
        self.stream.write('ERROR: %s\n    %s\n' % (
440
493
            self._test_description(test),
441
494
            err[1],
442
 
            )
 
495
            ))
443
496
 
444
497
    def report_failure(self, test, err):
445
 
        self.pb.note('FAIL: %s\n    %s\n',
 
498
        self.stream.write('FAIL: %s\n    %s\n' % (
446
499
            self._test_description(test),
447
500
            err[1],
448
 
            )
 
501
            ))
449
502
 
450
503
    def report_known_failure(self, test, err):
451
 
        self.pb.note('XFAIL: %s\n%s\n',
452
 
            self._test_description(test), err[1])
 
504
        pass
453
505
 
454
506
    def report_skip(self, test, reason):
455
507
        pass
456
508
 
457
 
    def report_not_applicable(self, test, skip_excinfo):
 
509
    def report_not_applicable(self, test, reason):
458
510
        pass
459
511
 
460
512
    def report_unsupported(self, test, feature):
463
515
    def report_cleaning_up(self):
464
516
        self.pb.update('Cleaning up')
465
517
 
466
 
    def finished(self):
467
 
        if not self._supplied_pb:
468
 
            self.pb.finished()
469
 
 
470
518
 
471
519
class VerboseTestResult(ExtendedTestResult):
472
520
    """Produce long output, with one line per test run plus times"""
479
527
            result = a_string
480
528
        return result.ljust(final_width)
481
529
 
482
 
    def report_starting(self):
 
530
    def startTestRun(self):
 
531
        super(VerboseTestResult, self).startTestRun()
483
532
        self.stream.write('running %d tests...\n' % self.num_tests)
484
533
 
485
534
    def report_test_start(self, test):
486
535
        self.count += 1
487
536
        name = self._shortened_test_description(test)
488
 
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
489
 
        # numbers, plus a trailing blank
490
 
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
491
 
        self.stream.write(self._ellipsize_to_right(name,
492
 
                          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)
493
546
        self.stream.flush()
494
547
 
495
548
    def _error_summary(self, err):
524
577
        self.stream.writeln(' SKIP %s\n%s'
525
578
                % (self._testTimeString(test), reason))
526
579
 
527
 
    def report_not_applicable(self, test, skip_excinfo):
528
 
        self.stream.writeln('  N/A %s\n%s'
529
 
                % (self._testTimeString(test),
530
 
                   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))
531
583
 
532
584
    def report_unsupported(self, test, feature):
533
585
        """test cannot be run because feature is missing."""
543
595
                 descriptions=0,
544
596
                 verbosity=1,
545
597
                 bench_history=None,
546
 
                 list_only=False,
547
598
                 strict=False,
 
599
                 result_decorators=None,
548
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
549
621
        self.stream = unittest._WritelnDecorator(stream)
550
622
        self.descriptions = descriptions
551
623
        self.verbosity = verbosity
552
624
        self._bench_history = bench_history
553
 
        self.list_only = list_only
554
625
        self._strict = strict
 
626
        self._result_decorators = result_decorators or []
555
627
 
556
628
    def run(self, test):
557
629
        "Run the given test case or test suite."
558
 
        startTime = time.time()
559
630
        if self.verbosity == 1:
560
631
            result_class = TextTestResult
561
632
        elif self.verbosity >= 2:
562
633
            result_class = VerboseTestResult
563
 
        result = result_class(self.stream,
 
634
        original_result = result_class(self.stream,
564
635
                              self.descriptions,
565
636
                              self.verbosity,
566
637
                              bench_history=self._bench_history,
567
 
                              num_tests=test.countTestCases(),
568
638
                              strict=self._strict,
569
639
                              )
570
 
        result.stop_early = self.stop_on_failure
571
 
        result.report_starting()
572
 
        if self.list_only:
573
 
            if self.verbosity >= 2:
574
 
                self.stream.writeln("Listing tests only ...\n")
575
 
            run = 0
576
 
            for t in iter_suite_tests(test):
577
 
                self.stream.writeln("%s" % (t.id()))
578
 
                run += 1
579
 
            return None
580
 
        else:
581
 
            try:
582
 
                import testtools
583
 
            except ImportError:
584
 
                test.run(result)
585
 
            else:
586
 
                if isinstance(test, testtools.ConcurrentTestSuite):
587
 
                    # We need to catch bzr specific behaviors
588
 
                    test.run(BZRTransformingResult(result))
589
 
                else:
590
 
                    test.run(result)
591
 
            run = result.testsRun
592
 
            actionTaken = "Ran"
593
 
        stopTime = time.time()
594
 
        timeTaken = stopTime - startTime
595
 
        result.printErrors()
596
 
        self.stream.writeln(result.separator2)
597
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
598
 
                            run, run != 1 and "s" or "", timeTaken))
599
 
        self.stream.writeln()
600
 
        if not result.wasSuccessful():
601
 
            self.stream.write("FAILED (")
602
 
            failed, errored = map(len, (result.failures, result.errors))
603
 
            if failed:
604
 
                self.stream.write("failures=%d" % failed)
605
 
            if errored:
606
 
                if failed: self.stream.write(", ")
607
 
                self.stream.write("errors=%d" % errored)
608
 
            if result.known_failure_count:
609
 
                if failed or errored: self.stream.write(", ")
610
 
                self.stream.write("known_failure_count=%d" %
611
 
                    result.known_failure_count)
612
 
            self.stream.writeln(")")
613
 
        else:
614
 
            if result.known_failure_count:
615
 
                self.stream.writeln("OK (known_failures=%d)" %
616
 
                    result.known_failure_count)
617
 
            else:
618
 
                self.stream.writeln("OK")
619
 
        if result.skip_count > 0:
620
 
            skipped = result.skip_count
621
 
            self.stream.writeln('%d test%s skipped' %
622
 
                                (skipped, skipped != 1 and "s" or ""))
623
 
        if result.unsupported:
624
 
            for feature, count in sorted(result.unsupported.items()):
625
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
626
 
                    (feature, count))
627
 
        result.finished()
628
 
        return result
 
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:
 
648
            test.run(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
629
654
 
630
655
 
631
656
def iter_suite_tests(suite):
641
666
                        % (type(suite), suite))
642
667
 
643
668
 
644
 
class TestSkipped(Exception):
645
 
    """Indicates that a test was intentionally skipped, rather than failing."""
 
669
TestSkipped = testtools.testcase.TestSkipped
646
670
 
647
671
 
648
672
class TestNotApplicable(TestSkipped):
654
678
    """
655
679
 
656
680
 
657
 
class KnownFailure(AssertionError):
658
 
    """Indicates that a test failed in a precisely expected manner.
659
 
 
660
 
    Such failures dont block the whole test suite from passing because they are
661
 
    indicators of partially completed code or of future work. We have an
662
 
    explicit error for them so that we can ensure that they are always visible:
663
 
    KnownFailures are always shown in the output of bzr selftest.
664
 
    """
 
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
665
698
 
666
699
 
667
700
class UnavailableFeature(Exception):
668
701
    """A feature required for this test was not available.
669
702
 
 
703
    This can be considered a specialised form of SkippedTest.
 
704
 
670
705
    The feature should be used to construct the exception.
671
706
    """
672
707
 
673
708
 
674
 
class CommandFailed(Exception):
675
 
    pass
676
 
 
677
 
 
678
709
class StringIOWrapper(object):
679
710
    """A wrapper around cStringIO which just adds an encoding attribute.
680
711
 
701
732
            return setattr(self._cstring, name, val)
702
733
 
703
734
 
704
 
class TestUIFactory(ui.CLIUIFactory):
 
735
class TestUIFactory(TextUIFactory):
705
736
    """A UI Factory for testing.
706
737
 
707
738
    Hide the progress bar but emit note()s.
708
739
    Redirect stdin.
709
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.
710
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.launchpad.net/bzr/+bug/408213
711
752
 
712
753
    def __init__(self, stdout=None, stderr=None, stdin=None):
713
754
        if stdin is not None:
718
759
            stdin = StringIOWrapper(stdin)
719
760
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
720
761
 
721
 
    def clear(self):
722
 
        """See progress.ProgressBar.clear()."""
723
 
 
724
 
    def clear_term(self):
725
 
        """See progress.ProgressBar.clear_term()."""
726
 
 
727
 
    def finished(self):
728
 
        """See progress.ProgressBar.finished()."""
729
 
 
730
 
    def note(self, fmt_string, *args, **kwargs):
731
 
        """See progress.ProgressBar.note()."""
732
 
        self.stdout.write((fmt_string + "\n") % args)
733
 
 
734
 
    def progress_bar(self):
735
 
        return self
736
 
 
737
 
    def nested_progress_bar(self):
738
 
        return self
739
 
 
740
 
    def update(self, message, count=None, total=None):
741
 
        """See progress.ProgressBar.update()."""
742
 
 
743
762
    def get_non_echoed_password(self):
744
763
        """Get password from stdin without trying to handle the echo mode"""
745
764
        password = self.stdin.readline()
749
768
            password = password[:-1]
750
769
        return password
751
770
 
752
 
 
753
 
class TestCase(unittest.TestCase):
 
771
    def make_progress_view(self):
 
772
        return NullProgressView()
 
773
 
 
774
 
 
775
class TestCase(testtools.TestCase):
754
776
    """Base class for bzr unit tests.
755
777
 
756
778
    Tests that need access to disk resources should subclass
775
797
    _leaking_threads_tests = 0
776
798
    _first_thread_leaker_id = None
777
799
    _log_file_name = None
778
 
    _log_contents = ''
779
 
    _keep_log_file = False
780
800
    # record lsprof data when performing benchmark calls.
781
801
    _gather_lsprof_in_benchmarks = False
782
 
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
783
 
                     '_log_contents', '_log_file_name', '_benchtime',
784
 
                     '_TestCase__testMethodName')
785
802
 
786
803
    def __init__(self, methodName='testMethod'):
787
804
        super(TestCase, self).__init__(methodName)
788
805
        self._cleanups = []
789
 
        self._bzr_test_setUp_run = False
790
 
        self._bzr_test_tearDown_run = False
 
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))
791
811
 
792
812
    def setUp(self):
793
 
        unittest.TestCase.setUp(self)
794
 
        self._bzr_test_setUp_run = True
 
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)]))
795
820
        self._cleanEnvironment()
796
821
        self._silenceUI()
797
822
        self._startLogFile()
798
823
        self._benchcalls = []
799
824
        self._benchtime = None
800
825
        self._clear_hooks()
 
826
        self._track_transports()
 
827
        self._track_locks()
801
828
        self._clear_debug_flags()
802
829
        TestCase._active_threads = threading.activeCount()
803
830
        self.addCleanup(self._check_leaked_threads)
811
838
        active = threading.activeCount()
812
839
        leaked_threads = active - TestCase._active_threads
813
840
        TestCase._active_threads = active
814
 
        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:
815
848
            TestCase._leaking_threads_tests += 1
816
849
            if TestCase._first_thread_leaker_id is None:
817
850
                TestCase._first_thread_leaker_id = self.id()
822
855
        Tests that want to use debug flags can just set them in the
823
856
        debug_flags set during setup/teardown.
824
857
        """
825
 
        self._preserved_debug_flags = set(debug.debug_flags)
 
858
        # Start with a copy of the current debug flags we can safely modify.
 
859
        self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
826
860
        if 'allow_debug' not in selftest_debug_flags:
827
861
            debug.debug_flags.clear()
828
 
        self.addCleanup(self._restore_debug_flags)
 
862
        if 'disable_lock_checks' not in selftest_debug_flags:
 
863
            debug.debug_flags.add('strict_locks')
829
864
 
830
865
    def _clear_hooks(self):
831
866
        # prevent hooks affecting tests
841
876
        # this hook should always be installed
842
877
        request._install_hook()
843
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
 
886
 
844
887
    def _silenceUI(self):
845
888
        """Turn off UI for duration of test"""
846
889
        # by default the UI is off; tests can turn it on if they want it.
847
 
        saved = ui.ui_factory
848
 
        def _restore():
849
 
            ui.ui_factory = saved
850
 
        ui.ui_factory = ui.SilentUIFactory()
851
 
        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 = _mod_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 = _mod_transport.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.")
852
1069
 
853
1070
    def _ndiff_strings(self, a, b):
854
1071
        """Return ndiff between two strings containing lines.
877
1094
            message += '\n'
878
1095
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
879
1096
            % (message,
880
 
               pformat(a), pformat(b)))
 
1097
               pprint.pformat(a), pprint.pformat(b)))
881
1098
 
882
1099
    assertEquals = assertEqual
883
1100
 
892
1109
            return
893
1110
        if message is None:
894
1111
            message = "texts not equal:\n"
 
1112
        if a + '\n' == b:
 
1113
            message = 'first string is missing a final newline.\n'
895
1114
        if a == b + '\n':
896
 
            message = 'first string is missing a final newline.\n'
897
 
        if a + '\n' == b:
898
1115
            message = 'second string is missing a final newline.\n'
899
1116
        raise AssertionError(message +
900
1117
                             self._ndiff_strings(a, b))
911
1128
        :raises AssertionError: If the expected and actual stat values differ
912
1129
            other than by atime.
913
1130
        """
914
 
        self.assertEqual(expected.st_size, actual.st_size)
915
 
        self.assertEqual(expected.st_mtime, actual.st_mtime)
916
 
        self.assertEqual(expected.st_ctime, actual.st_ctime)
917
 
        self.assertEqual(expected.st_dev, actual.st_dev)
918
 
        self.assertEqual(expected.st_ino, actual.st_ino)
919
 
        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')
920
1148
 
921
1149
    def assertLength(self, length, obj_with_len):
922
1150
        """Assert that obj_with_len is of length length."""
924
1152
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
925
1153
                length, len(obj_with_len), obj_with_len))
926
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
 
1173
 
927
1174
    def assertPositive(self, val):
928
1175
        """Assert that val is greater than 0."""
929
1176
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
959
1206
            raise AssertionError('pattern "%s" found in "%s"'
960
1207
                    % (needle_re, haystack))
961
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
 
962
1213
    def assertSubset(self, sublist, superlist):
963
1214
        """Assert that every entry in sublist is present in superlist."""
964
1215
        missing = set(sublist) - set(superlist)
1039
1290
                         osutils.realpath(path2),
1040
1291
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1041
1292
 
1042
 
    def assertIsInstance(self, obj, kls):
1043
 
        """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
        """
1044
1298
        if not isinstance(obj, kls):
1045
 
            self.fail("%r is an instance of %s rather than %s" % (
1046
 
                obj, obj.__class__, kls))
1047
 
 
1048
 
    def expectFailure(self, reason, assertion, *args, **kwargs):
1049
 
        """Invoke a test, expecting it to fail for the given reason.
1050
 
 
1051
 
        This is for assertions that ought to succeed, but currently fail.
1052
 
        (The failure is *expected* but not *wanted*.)  Please be very precise
1053
 
        about the failure you're expecting.  If a new bug is introduced,
1054
 
        AssertionError should be raised, not KnownFailure.
1055
 
 
1056
 
        Frequently, expectFailure should be followed by an opposite assertion.
1057
 
        See example below.
1058
 
 
1059
 
        Intended to be used with a callable that raises AssertionError as the
1060
 
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
1061
 
 
1062
 
        Raises KnownFailure if the test fails.  Raises AssertionError if the
1063
 
        test succeeds.
1064
 
 
1065
 
        example usage::
1066
 
 
1067
 
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
1068
 
                             dynamic_val)
1069
 
          self.assertEqual(42, dynamic_val)
1070
 
 
1071
 
          This means that a dynamic_val of 54 will cause the test to raise
1072
 
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
1073
 
          only a dynamic_val of 42 will allow the test to pass.  Anything other
1074
 
          than 54 or 42 will cause an AssertionError.
1075
 
        """
1076
 
        try:
1077
 
            assertion(*args, **kwargs)
1078
 
        except AssertionError:
1079
 
            raise KnownFailure(reason)
1080
 
        else:
1081
 
            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)
1082
1304
 
1083
1305
    def assertFileEqual(self, content, path):
1084
1306
        """Fail if path does not contain 'content'."""
1090
1312
            f.close()
1091
1313
        self.assertEqualDiff(content, s)
1092
1314
 
 
1315
    def assertDocstring(self, expected_docstring, obj):
 
1316
        """Fail if obj does not have expected_docstring"""
 
1317
        if __doc__ is None:
 
1318
            # With -OO the docstring should be None instead
 
1319
            self.assertIs(obj.__doc__, None)
 
1320
        else:
 
1321
            self.assertEqual(expected_docstring, obj.__doc__)
 
1322
 
1093
1323
    def failUnlessExists(self, path):
1094
1324
        """Fail unless path or paths, which may be abs or relative, exist."""
1095
1325
        if not isinstance(path, basestring):
1235
1465
 
1236
1466
        Close the file and delete it, unless setKeepLogfile was called.
1237
1467
        """
1238
 
        if self._log_file is None:
1239
 
            return
 
1468
        if bzrlib.trace._trace_file:
 
1469
            # flush the log file, to get all content
 
1470
            bzrlib.trace._trace_file.flush()
1240
1471
        bzrlib.trace.pop_log_file(self._log_memento)
1241
 
        self._log_file.close()
1242
 
        self._log_file = None
1243
 
        if not self._keep_log_file:
1244
 
            os.remove(self._log_file_name)
1245
 
            self._log_file_name = None
1246
 
 
1247
 
    def setKeepLogfile(self):
1248
 
        """Make the logfile not be deleted when _finishLogFile is called."""
1249
 
        self._keep_log_file = True
 
1472
        # Cache the log result and delete the file on disk
 
1473
        self._get_log(False)
 
1474
 
 
1475
    def thisFailsStrictLockCheck(self):
 
1476
        """It is known that this test would fail with -Dstrict_locks.
 
1477
 
 
1478
        By default, all tests are run with strict lock checking unless
 
1479
        -Edisable_lock_checks is supplied. However there are some tests which
 
1480
        we know fail strict locks at this point that have not been fixed.
 
1481
        They should call this function to disable the strict checking.
 
1482
 
 
1483
        This should be used sparingly, it is much better to fix the locking
 
1484
        issues rather than papering over the problem by calling this function.
 
1485
        """
 
1486
        debug.debug_flags.discard('strict_locks')
1250
1487
 
1251
1488
    def addCleanup(self, callable, *args, **kwargs):
1252
1489
        """Arrange to run a callable when this case is torn down.
1256
1493
        """
1257
1494
        self._cleanups.append((callable, args, kwargs))
1258
1495
 
 
1496
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
 
1497
        """Overrides an object attribute restoring it after the test.
 
1498
 
 
1499
        :param obj: The object that will be mutated.
 
1500
 
 
1501
        :param attr_name: The attribute name we want to preserve/override in
 
1502
            the object.
 
1503
 
 
1504
        :param new: The optional value we want to set the attribute to.
 
1505
 
 
1506
        :returns: The actual attr value.
 
1507
        """
 
1508
        value = getattr(obj, attr_name)
 
1509
        # The actual value is captured by the call below
 
1510
        self.addCleanup(setattr, obj, attr_name, value)
 
1511
        if new is not _unitialized_attr:
 
1512
            setattr(obj, attr_name, new)
 
1513
        return value
 
1514
 
1259
1515
    def _cleanEnvironment(self):
1260
1516
        new_env = {
1261
1517
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1267
1523
            'EDITOR': None,
1268
1524
            'BZR_EMAIL': None,
1269
1525
            'BZREMAIL': None, # may still be present in the environment
1270
 
            'EMAIL': None,
 
1526
            'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
1271
1527
            'BZR_PROGRESS_BAR': None,
1272
1528
            'BZR_LOG': None,
1273
1529
            'BZR_PLUGIN_PATH': None,
 
1530
            'BZR_DISABLE_PLUGINS': None,
 
1531
            'BZR_PLUGINS_AT': None,
 
1532
            'BZR_CONCURRENCY': None,
 
1533
            # Make sure that any text ui tests are consistent regardless of
 
1534
            # the environment the test case is run in; you may want tests that
 
1535
            # test other combinations.  'dumb' is a reasonable guess for tests
 
1536
            # going to a pipe or a StringIO.
 
1537
            'TERM': 'dumb',
 
1538
            'LINES': '25',
 
1539
            'COLUMNS': '80',
 
1540
            'BZR_COLUMNS': '80',
1274
1541
            # SSH Agent
1275
1542
            'SSH_AUTH_SOCK': None,
1276
1543
            # Proxies
1288
1555
            'ftp_proxy': None,
1289
1556
            'FTP_PROXY': None,
1290
1557
            'BZR_REMOTE_PATH': None,
 
1558
            # Generally speaking, we don't want apport reporting on crashes in
 
1559
            # the test envirnoment unless we're specifically testing apport,
 
1560
            # so that it doesn't leak into the real system environment.  We
 
1561
            # use an env var so it propagates to subprocesses.
 
1562
            'APPORT_DISABLE': '1',
1291
1563
        }
1292
 
        self.__old_env = {}
 
1564
        self._old_env = {}
1293
1565
        self.addCleanup(self._restoreEnvironment)
1294
1566
        for name, value in new_env.iteritems():
1295
1567
            self._captureVar(name, value)
1296
1568
 
1297
1569
    def _captureVar(self, name, newvalue):
1298
1570
        """Set an environment variable, and reset it when finished."""
1299
 
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1300
 
 
1301
 
    def _restore_debug_flags(self):
1302
 
        debug.debug_flags.clear()
1303
 
        debug.debug_flags.update(self._preserved_debug_flags)
 
1571
        self._old_env[name] = osutils.set_or_unset_env(name, newvalue)
1304
1572
 
1305
1573
    def _restoreEnvironment(self):
1306
 
        for name, value in self.__old_env.iteritems():
 
1574
        for name, value in self._old_env.iteritems():
1307
1575
            osutils.set_or_unset_env(name, value)
1308
1576
 
1309
1577
    def _restoreHooks(self):
1317
1585
    def _do_skip(self, result, reason):
1318
1586
        addSkip = getattr(result, 'addSkip', None)
1319
1587
        if not callable(addSkip):
1320
 
            result.addError(self, sys.exc_info())
 
1588
            result.addSuccess(result)
1321
1589
        else:
1322
1590
            addSkip(self, reason)
1323
1591
 
1324
 
    def run(self, result=None):
1325
 
        if result is None: result = self.defaultTestResult()
1326
 
        for feature in getattr(self, '_test_needs_features', []):
1327
 
            if not feature.available():
1328
 
                result.startTest(self)
1329
 
                if getattr(result, 'addNotSupported', None):
1330
 
                    result.addNotSupported(self, feature)
1331
 
                else:
1332
 
                    result.addSuccess(self)
1333
 
                result.stopTest(self)
1334
 
                return
1335
 
        try:
1336
 
            try:
1337
 
                result.startTest(self)
1338
 
                absent_attr = object()
1339
 
                # Python 2.5
1340
 
                method_name = getattr(self, '_testMethodName', absent_attr)
1341
 
                if method_name is absent_attr:
1342
 
                    # Python 2.4
1343
 
                    method_name = getattr(self, '_TestCase__testMethodName')
1344
 
                testMethod = getattr(self, method_name)
1345
 
                try:
1346
 
                    try:
1347
 
                        self.setUp()
1348
 
                        if not self._bzr_test_setUp_run:
1349
 
                            self.fail(
1350
 
                                "test setUp did not invoke "
1351
 
                                "bzrlib.tests.TestCase's setUp")
1352
 
                    except KeyboardInterrupt:
1353
 
                        raise
1354
 
                    except TestSkipped, e:
1355
 
                        self._do_skip(result, e.args[0])
1356
 
                        self.tearDown()
1357
 
                        return
1358
 
                    except:
1359
 
                        result.addError(self, sys.exc_info())
1360
 
                        return
1361
 
 
1362
 
                    ok = False
1363
 
                    try:
1364
 
                        testMethod()
1365
 
                        ok = True
1366
 
                    except self.failureException:
1367
 
                        result.addFailure(self, sys.exc_info())
1368
 
                    except TestSkipped, e:
1369
 
                        if not e.args:
1370
 
                            reason = "No reason given."
1371
 
                        else:
1372
 
                            reason = e.args[0]
1373
 
                        self._do_skip(result, reason)
1374
 
                    except KeyboardInterrupt:
1375
 
                        raise
1376
 
                    except:
1377
 
                        result.addError(self, sys.exc_info())
1378
 
 
1379
 
                    try:
1380
 
                        self.tearDown()
1381
 
                        if not self._bzr_test_tearDown_run:
1382
 
                            self.fail(
1383
 
                                "test tearDown did not invoke "
1384
 
                                "bzrlib.tests.TestCase's tearDown")
1385
 
                    except KeyboardInterrupt:
1386
 
                        raise
1387
 
                    except:
1388
 
                        result.addError(self, sys.exc_info())
1389
 
                        ok = False
1390
 
                    if ok: result.addSuccess(self)
1391
 
                finally:
1392
 
                    result.stopTest(self)
1393
 
                return
1394
 
            except TestNotApplicable:
1395
 
                # Not moved from the result [yet].
1396
 
                raise
1397
 
            except KeyboardInterrupt:
1398
 
                raise
1399
 
        finally:
1400
 
            saved_attrs = {}
1401
 
            absent_attr = object()
1402
 
            for attr_name in self.attrs_to_keep:
1403
 
                attr = getattr(self, attr_name, absent_attr)
1404
 
                if attr is not absent_attr:
1405
 
                    saved_attrs[attr_name] = attr
1406
 
            self.__dict__ = saved_attrs
1407
 
 
1408
 
    def tearDown(self):
1409
 
        self._bzr_test_tearDown_run = True
1410
 
        self._runCleanups()
1411
 
        self._log_contents = ''
1412
 
        unittest.TestCase.tearDown(self)
 
1592
    @staticmethod
 
1593
    def _do_known_failure(self, result, e):
 
1594
        err = sys.exc_info()
 
1595
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
 
1596
        if addExpectedFailure is not None:
 
1597
            addExpectedFailure(self, err)
 
1598
        else:
 
1599
            result.addSuccess(self)
 
1600
 
 
1601
    @staticmethod
 
1602
    def _do_not_applicable(self, result, e):
 
1603
        if not e.args:
 
1604
            reason = 'No reason given'
 
1605
        else:
 
1606
            reason = e.args[0]
 
1607
        addNotApplicable = getattr(result, 'addNotApplicable', None)
 
1608
        if addNotApplicable is not None:
 
1609
            result.addNotApplicable(self, reason)
 
1610
        else:
 
1611
            self._do_skip(result, reason)
 
1612
 
 
1613
    @staticmethod
 
1614
    def _do_unsupported_or_skip(self, result, e):
 
1615
        reason = e.args[0]
 
1616
        addNotSupported = getattr(result, 'addNotSupported', None)
 
1617
        if addNotSupported is not None:
 
1618
            result.addNotSupported(self, reason)
 
1619
        else:
 
1620
            self._do_skip(result, reason)
1413
1621
 
1414
1622
    def time(self, callable, *args, **kwargs):
1415
1623
        """Run callable and accrue the time it takes to the benchmark time.
1419
1627
        self._benchcalls.
1420
1628
        """
1421
1629
        if self._benchtime is None:
 
1630
            self.addDetail('benchtime', content.Content(content.ContentType(
 
1631
                "text", "plain"), lambda:[str(self._benchtime)]))
1422
1632
            self._benchtime = 0
1423
1633
        start = time.time()
1424
1634
        try:
1433
1643
        finally:
1434
1644
            self._benchtime += time.time() - start
1435
1645
 
1436
 
    def _runCleanups(self):
1437
 
        """Run registered cleanup functions.
1438
 
 
1439
 
        This should only be called from TestCase.tearDown.
1440
 
        """
1441
 
        # TODO: Perhaps this should keep running cleanups even if
1442
 
        # one of them fails?
1443
 
 
1444
 
        # Actually pop the cleanups from the list so tearDown running
1445
 
        # twice is safe (this happens for skipped tests).
1446
 
        while self._cleanups:
1447
 
            cleanup, args, kwargs = self._cleanups.pop()
1448
 
            cleanup(*args, **kwargs)
1449
 
 
1450
1646
    def log(self, *args):
1451
1647
        mutter(*args)
1452
1648
 
1453
1649
    def _get_log(self, keep_log_file=False):
1454
 
        """Get the log from bzrlib.trace calls from this test.
 
1650
        """Internal helper to get the log from bzrlib.trace for this test.
 
1651
 
 
1652
        Please use self.getDetails, or self.get_log to access this in test case
 
1653
        code.
1455
1654
 
1456
1655
        :param keep_log_file: When True, if the log is still a file on disk
1457
1656
            leave it as a file on disk. When False, if the log is still a file
1459
1658
            self._log_contents.
1460
1659
        :return: A string containing the log.
1461
1660
        """
1462
 
        # flush the log file, to get all content
 
1661
        if self._log_contents is not None:
 
1662
            try:
 
1663
                self._log_contents.decode('utf8')
 
1664
            except UnicodeDecodeError:
 
1665
                unicodestr = self._log_contents.decode('utf8', 'replace')
 
1666
                self._log_contents = unicodestr.encode('utf8')
 
1667
            return self._log_contents
1463
1668
        import bzrlib.trace
1464
1669
        if bzrlib.trace._trace_file:
 
1670
            # flush the log file, to get all content
1465
1671
            bzrlib.trace._trace_file.flush()
1466
 
        if self._log_contents:
1467
 
            # XXX: this can hardly contain the content flushed above --vila
1468
 
            # 20080128
1469
 
            return self._log_contents
1470
1672
        if self._log_file_name is not None:
1471
1673
            logfile = open(self._log_file_name)
1472
1674
            try:
1473
1675
                log_contents = logfile.read()
1474
1676
            finally:
1475
1677
                logfile.close()
 
1678
            try:
 
1679
                log_contents.decode('utf8')
 
1680
            except UnicodeDecodeError:
 
1681
                unicodestr = log_contents.decode('utf8', 'replace')
 
1682
                log_contents = unicodestr.encode('utf8')
1476
1683
            if not keep_log_file:
 
1684
                close_attempts = 0
 
1685
                max_close_attempts = 100
 
1686
                first_close_error = None
 
1687
                while close_attempts < max_close_attempts:
 
1688
                    close_attempts += 1
 
1689
                    try:
 
1690
                        self._log_file.close()
 
1691
                    except IOError, ioe:
 
1692
                        if ioe.errno is None:
 
1693
                            # No errno implies 'close() called during
 
1694
                            # concurrent operation on the same file object', so
 
1695
                            # retry.  Probably a thread is trying to write to
 
1696
                            # the log file.
 
1697
                            if first_close_error is None:
 
1698
                                first_close_error = ioe
 
1699
                            continue
 
1700
                        raise
 
1701
                    else:
 
1702
                        break
 
1703
                if close_attempts > 1:
 
1704
                    sys.stderr.write(
 
1705
                        'Unable to close log file on first attempt, '
 
1706
                        'will retry: %s\n' % (first_close_error,))
 
1707
                    if close_attempts == max_close_attempts:
 
1708
                        sys.stderr.write(
 
1709
                            'Unable to close log file after %d attempts.\n'
 
1710
                            % (max_close_attempts,))
 
1711
                self._log_file = None
 
1712
                # Permit multiple calls to get_log until we clean it up in
 
1713
                # finishLogFile
1477
1714
                self._log_contents = log_contents
1478
1715
                try:
1479
1716
                    os.remove(self._log_file_name)
1483
1720
                                             ' %r\n' % self._log_file_name))
1484
1721
                    else:
1485
1722
                        raise
 
1723
                self._log_file_name = None
1486
1724
            return log_contents
1487
1725
        else:
1488
 
            return "DELETED log file to reduce memory footprint"
 
1726
            return "No log file content and no log file name."
 
1727
 
 
1728
    def get_log(self):
 
1729
        """Get a unicode string containing the log from bzrlib.trace.
 
1730
 
 
1731
        Undecodable characters are replaced.
 
1732
        """
 
1733
        return u"".join(self.getDetails()['log'].iter_text())
1489
1734
 
1490
1735
    def requireFeature(self, feature):
1491
1736
        """This test requires a specific feature is available.
1508
1753
 
1509
1754
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1510
1755
            working_dir):
 
1756
        # Clear chk_map page cache, because the contents are likely to mask
 
1757
        # locking errors.
 
1758
        chk_map.clear_cache()
1511
1759
        if encoding is None:
1512
1760
            encoding = osutils.get_user_encoding()
1513
1761
        stdout = StringIOWrapper()
1530
1778
            os.chdir(working_dir)
1531
1779
 
1532
1780
        try:
1533
 
            result = self.apply_redirected(ui.ui_factory.stdin,
1534
 
                stdout, stderr,
1535
 
                bzrlib.commands.run_bzr_catch_user_errors,
1536
 
                args)
 
1781
            try:
 
1782
                result = self.apply_redirected(ui.ui_factory.stdin,
 
1783
                    stdout, stderr,
 
1784
                    bzrlib.commands.run_bzr_catch_user_errors,
 
1785
                    args)
 
1786
            except KeyboardInterrupt:
 
1787
                # Reraise KeyboardInterrupt with contents of redirected stdout
 
1788
                # and stderr as arguments, for tests which are interested in
 
1789
                # stdout and stderr and are expecting the exception.
 
1790
                out = stdout.getvalue()
 
1791
                err = stderr.getvalue()
 
1792
                if out:
 
1793
                    self.log('output:\n%r', out)
 
1794
                if err:
 
1795
                    self.log('errors:\n%r', err)
 
1796
                raise KeyboardInterrupt(out, err)
1537
1797
        finally:
1538
1798
            logger.removeHandler(handler)
1539
1799
            ui.ui_factory = old_ui_factory
1549
1809
        if retcode is not None:
1550
1810
            self.assertEquals(retcode, result,
1551
1811
                              message='Unexpected return code')
1552
 
        return out, err
 
1812
        return result, out, err
1553
1813
 
1554
1814
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1555
1815
                working_dir=None, error_regexes=[], output_encoding=None):
1584
1844
        :keyword error_regexes: A list of expected error messages.  If
1585
1845
            specified they must be seen in the error output of the command.
1586
1846
        """
1587
 
        out, err = self._run_bzr_autosplit(
 
1847
        retcode, out, err = self._run_bzr_autosplit(
1588
1848
            args=args,
1589
1849
            retcode=retcode,
1590
1850
            encoding=encoding,
1591
1851
            stdin=stdin,
1592
1852
            working_dir=working_dir,
1593
1853
            )
 
1854
        self.assertIsInstance(error_regexes, (list, tuple))
1594
1855
        for regex in error_regexes:
1595
1856
            self.assertContainsRe(err, regex)
1596
1857
        return out, err
1724
1985
            if not allow_plugins:
1725
1986
                command.append('--no-plugins')
1726
1987
            command.extend(process_args)
1727
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
1988
            process = self._popen(command, stdin=subprocess.PIPE,
 
1989
                                  stdout=subprocess.PIPE,
 
1990
                                  stderr=subprocess.PIPE)
1728
1991
        finally:
1729
1992
            restore_environment()
1730
1993
            if cwd is not None:
1738
2001
        Allows tests to override this method to intercept the calls made to
1739
2002
        Popen for introspection.
1740
2003
        """
1741
 
        return Popen(*args, **kwargs)
 
2004
        return subprocess.Popen(*args, **kwargs)
 
2005
 
 
2006
    def get_source_path(self):
 
2007
        """Return the path of the directory containing bzrlib."""
 
2008
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
1742
2009
 
1743
2010
    def get_bzr_path(self):
1744
2011
        """Return the path of the 'bzr' executable for this test suite."""
1745
 
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
2012
        bzr_path = self.get_source_path()+'/bzr'
1746
2013
        if not os.path.isfile(bzr_path):
1747
2014
            # We are probably installed. Assume sys.argv is the right file
1748
2015
            bzr_path = sys.argv[0]
1834
2101
 
1835
2102
        Tests that expect to provoke LockContention errors should call this.
1836
2103
        """
1837
 
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
1838
 
        def resetTimeout():
1839
 
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
1840
 
        self.addCleanup(resetTimeout)
1841
 
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
2104
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
1842
2105
 
1843
2106
    def make_utf8_encoded_stringio(self, encoding_type=None):
1844
2107
        """Return a StringIOWrapper instance, that will encode Unicode
1852
2115
        sio.encoding = output_encoding
1853
2116
        return sio
1854
2117
 
 
2118
    def disable_verb(self, verb):
 
2119
        """Disable a smart server verb for one test."""
 
2120
        from bzrlib.smart import request
 
2121
        request_handlers = request.request_handlers
 
2122
        orig_method = request_handlers.get(verb)
 
2123
        request_handlers.remove(verb)
 
2124
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2125
 
1855
2126
 
1856
2127
class CapturedCall(object):
1857
2128
    """A helper for capturing smart server calls for easy debug analysis."""
1916
2187
 
1917
2188
        :param relpath: a path relative to the base url.
1918
2189
        """
1919
 
        t = get_transport(self.get_url(relpath))
 
2190
        t = _mod_transport.get_transport(self.get_url(relpath))
1920
2191
        self.assertFalse(t.is_readonly())
1921
2192
        return t
1922
2193
 
1928
2199
 
1929
2200
        :param relpath: a path relative to the base url.
1930
2201
        """
1931
 
        t = get_transport(self.get_readonly_url(relpath))
 
2202
        t = _mod_transport.get_transport(self.get_readonly_url(relpath))
1932
2203
        self.assertTrue(t.is_readonly())
1933
2204
        return t
1934
2205
 
1947
2218
        if self.__readonly_server is None:
1948
2219
            if self.transport_readonly_server is None:
1949
2220
                # readonly decorator requested
1950
 
                # bring up the server
1951
 
                self.__readonly_server = ReadonlyServer()
1952
 
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
2221
                self.__readonly_server = test_server.ReadonlyServer()
1953
2222
            else:
 
2223
                # explicit readonly transport.
1954
2224
                self.__readonly_server = self.create_transport_readonly_server()
1955
 
                self.__readonly_server.setUp(self.get_vfs_only_server())
1956
 
            self.addCleanup(self.__readonly_server.tearDown)
 
2225
            self.start_server(self.__readonly_server,
 
2226
                self.get_vfs_only_server())
1957
2227
        return self.__readonly_server
1958
2228
 
1959
2229
    def get_readonly_url(self, relpath=None):
1977
2247
        is no means to override it.
1978
2248
        """
1979
2249
        if self.__vfs_server is None:
1980
 
            self.__vfs_server = MemoryServer()
1981
 
            self.__vfs_server.setUp()
1982
 
            self.addCleanup(self.__vfs_server.tearDown)
 
2250
            self.__vfs_server = memory.MemoryServer()
 
2251
            self.start_server(self.__vfs_server)
1983
2252
        return self.__vfs_server
1984
2253
 
1985
2254
    def get_server(self):
1992
2261
        then the self.get_vfs_server is returned.
1993
2262
        """
1994
2263
        if self.__server is None:
1995
 
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
1996
 
                return self.get_vfs_only_server()
 
2264
            if (self.transport_server is None or self.transport_server is
 
2265
                self.vfs_transport_factory):
 
2266
                self.__server = self.get_vfs_only_server()
1997
2267
            else:
1998
2268
                # bring up a decorated means of access to the vfs only server.
1999
2269
                self.__server = self.transport_server()
2000
 
                try:
2001
 
                    self.__server.setUp(self.get_vfs_only_server())
2002
 
                except TypeError, e:
2003
 
                    # This should never happen; the try:Except here is to assist
2004
 
                    # developers having to update code rather than seeing an
2005
 
                    # uninformative TypeError.
2006
 
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
2007
 
            self.addCleanup(self.__server.tearDown)
 
2270
                self.start_server(self.__server, self.get_vfs_only_server())
2008
2271
        return self.__server
2009
2272
 
2010
2273
    def _adjust_url(self, base, relpath):
2072
2335
        propagating. This method ensures than a test did not leaked.
2073
2336
        """
2074
2337
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
2338
        self.permit_url(_mod_transport.get_transport(root).base)
2075
2339
        wt = workingtree.WorkingTree.open(root)
2076
2340
        last_rev = wt.last_revision()
2077
2341
        if last_rev != 'null:':
2079
2343
            # recreate a new one or all the followng tests will fail.
2080
2344
            # If you need to inspect its content uncomment the following line
2081
2345
            # import pdb; pdb.set_trace()
2082
 
            _rmtree_temp_dir(root + '/.bzr')
 
2346
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
2083
2347
            self._create_safety_net()
2084
2348
            raise AssertionError('%s/.bzr should not be modified' % root)
2085
2349
 
2086
2350
    def _make_test_root(self):
2087
2351
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
2088
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
2352
            # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
2353
            root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
 
2354
                                                    suffix='.tmp'))
2089
2355
            TestCaseWithMemoryTransport.TEST_ROOT = root
2090
2356
 
2091
2357
            self._create_safety_net()
2094
2360
            # specifically told when all tests are finished.  This will do.
2095
2361
            atexit.register(_rmtree_temp_dir, root)
2096
2362
 
 
2363
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2097
2364
        self.addCleanup(self._check_safety_net)
2098
2365
 
2099
2366
    def makeAndChdirToTestDir(self):
2107
2374
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2108
2375
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2109
2376
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
 
2377
        self.permit_dir(self.test_dir)
2110
2378
 
2111
2379
    def make_branch(self, relpath, format=None):
2112
2380
        """Create a branch on the transport at relpath."""
2118
2386
            # might be a relative or absolute path
2119
2387
            maybe_a_url = self.get_url(relpath)
2120
2388
            segments = maybe_a_url.rsplit('/', 1)
2121
 
            t = get_transport(maybe_a_url)
 
2389
            t = _mod_transport.get_transport(maybe_a_url)
2122
2390
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2123
2391
                t.ensure_base()
2124
2392
            if format is None:
2141
2409
        made_control = self.make_bzrdir(relpath, format=format)
2142
2410
        return made_control.create_repository(shared=shared)
2143
2411
 
2144
 
    def make_smart_server(self, path):
2145
 
        smart_server = server.SmartTCPServer_for_testing()
2146
 
        smart_server.setUp(self.get_server())
2147
 
        remote_transport = get_transport(smart_server.get_url()).clone(path)
2148
 
        self.addCleanup(smart_server.tearDown)
 
2412
    def make_smart_server(self, path, backing_server=None):
 
2413
        if backing_server is None:
 
2414
            backing_server = self.get_server()
 
2415
        smart_server = test_server.SmartTCPServer_for_testing()
 
2416
        self.start_server(smart_server, backing_server)
 
2417
        remote_transport = _mod_transport.get_transport(smart_server.get_url()
 
2418
                                                   ).clone(path)
2149
2419
        return remote_transport
2150
2420
 
2151
2421
    def make_branch_and_memory_tree(self, relpath, format=None):
2154
2424
        return memorytree.MemoryTree.create_on_branch(b)
2155
2425
 
2156
2426
    def make_branch_builder(self, relpath, format=None):
2157
 
        return branchbuilder.BranchBuilder(self.get_transport(relpath),
2158
 
            format=format)
 
2427
        branch = self.make_branch(relpath, format=format)
 
2428
        return branchbuilder.BranchBuilder(branch=branch)
2159
2429
 
2160
2430
    def overrideEnvironmentForTesting(self):
2161
 
        os.environ['HOME'] = self.test_home_dir
2162
 
        os.environ['BZR_HOME'] = self.test_home_dir
 
2431
        test_home_dir = self.test_home_dir
 
2432
        if isinstance(test_home_dir, unicode):
 
2433
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
 
2434
        os.environ['HOME'] = test_home_dir
 
2435
        os.environ['BZR_HOME'] = test_home_dir
2163
2436
 
2164
2437
    def setUp(self):
2165
2438
        super(TestCaseWithMemoryTransport, self).setUp()
2166
2439
        self._make_test_root()
2167
 
        _currentdir = os.getcwdu()
2168
 
        def _leaveDirectory():
2169
 
            os.chdir(_currentdir)
2170
 
        self.addCleanup(_leaveDirectory)
 
2440
        self.addCleanup(os.chdir, os.getcwdu())
2171
2441
        self.makeAndChdirToTestDir()
2172
2442
        self.overrideEnvironmentForTesting()
2173
2443
        self.__readonly_server = None
2176
2446
 
2177
2447
    def setup_smart_server_with_call_log(self):
2178
2448
        """Sets up a smart server as the transport server with a call log."""
2179
 
        self.transport_server = server.SmartTCPServer_for_testing
 
2449
        self.transport_server = test_server.SmartTCPServer_for_testing
2180
2450
        self.hpss_calls = []
2181
2451
        import traceback
2182
2452
        # Skip the current stack down to the caller of
2216
2486
 
2217
2487
    def check_file_contents(self, filename, expect):
2218
2488
        self.log("check contents of file %s" % filename)
2219
 
        contents = file(filename, 'r').read()
 
2489
        f = file(filename)
 
2490
        try:
 
2491
            contents = f.read()
 
2492
        finally:
 
2493
            f.close()
2220
2494
        if contents != expect:
2221
2495
            self.log("expected: %r" % expect)
2222
2496
            self.log("actually: %r" % contents)
2224
2498
 
2225
2499
    def _getTestDirPrefix(self):
2226
2500
        # create a directory within the top level test directory
2227
 
        if sys.platform == 'win32':
 
2501
        if sys.platform in ('win32', 'cygwin'):
2228
2502
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2229
2503
            # windows is likely to have path-length limits so use a short name
2230
2504
            name_prefix = name_prefix[-30:]
2245
2519
            if os.path.exists(name):
2246
2520
                name = name_prefix + '_' + str(i)
2247
2521
            else:
2248
 
                os.mkdir(name)
 
2522
                # now create test and home directories within this dir
 
2523
                self.test_base_dir = name
 
2524
                self.addCleanup(self.deleteTestDir)
 
2525
                os.mkdir(self.test_base_dir)
2249
2526
                break
2250
 
        # now create test and home directories within this dir
2251
 
        self.test_base_dir = name
 
2527
        self.permit_dir(self.test_base_dir)
 
2528
        # 'sprouting' and 'init' of a branch both walk up the tree to find
 
2529
        # stacking policy to honour; create a bzr dir with an unshared
 
2530
        # repository (but not a branch - our code would be trying to escape
 
2531
        # then!) to stop them, and permit it to be read.
 
2532
        # control = bzrdir.BzrDir.create(self.test_base_dir)
 
2533
        # control.create_repository()
2252
2534
        self.test_home_dir = self.test_base_dir + '/home'
2253
2535
        os.mkdir(self.test_home_dir)
2254
2536
        self.test_dir = self.test_base_dir + '/work'
2260
2542
            f.write(self.id())
2261
2543
        finally:
2262
2544
            f.close()
2263
 
        self.addCleanup(self.deleteTestDir)
2264
2545
 
2265
2546
    def deleteTestDir(self):
2266
2547
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2267
 
        _rmtree_temp_dir(self.test_base_dir)
 
2548
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
2268
2549
 
2269
2550
    def build_tree(self, shape, line_endings='binary', transport=None):
2270
2551
        """Build a test tree according to a pattern.
2289
2570
                "a list or a tuple. Got %r instead" % (shape,))
2290
2571
        # It's OK to just create them using forward slashes on windows.
2291
2572
        if transport is None or transport.is_readonly():
2292
 
            transport = get_transport(".")
 
2573
            transport = _mod_transport.get_transport(".")
2293
2574
        for name in shape:
2294
2575
            self.assertIsInstance(name, basestring)
2295
2576
            if name[-1] == '/':
2305
2586
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2306
2587
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2307
2588
 
2308
 
    def build_tree_contents(self, shape):
2309
 
        build_tree_contents(shape)
 
2589
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2310
2590
 
2311
2591
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2312
2592
        """Assert whether path or paths are in the WorkingTree"""
2352
2632
        """
2353
2633
        if self.__vfs_server is None:
2354
2634
            self.__vfs_server = self.vfs_transport_factory()
2355
 
            self.__vfs_server.setUp()
2356
 
            self.addCleanup(self.__vfs_server.tearDown)
 
2635
            self.start_server(self.__vfs_server)
2357
2636
        return self.__vfs_server
2358
2637
 
2359
2638
    def make_branch_and_tree(self, relpath, format=None):
2366
2645
        repository will also be accessed locally. Otherwise a lightweight
2367
2646
        checkout is created and returned.
2368
2647
 
 
2648
        We do this because we can't physically create a tree in the local
 
2649
        path, with a branch reference to the transport_factory url, and
 
2650
        a branch + repository in the vfs_transport, unless the vfs_transport
 
2651
        namespace is distinct from the local disk - the two branch objects
 
2652
        would collide. While we could construct a tree with its branch object
 
2653
        pointing at the transport_factory transport in memory, reopening it
 
2654
        would behaving unexpectedly, and has in the past caused testing bugs
 
2655
        when we tried to do it that way.
 
2656
 
2369
2657
        :param format: The BzrDirFormat.
2370
2658
        :returns: the WorkingTree.
2371
2659
        """
2380
2668
            # We can only make working trees locally at the moment.  If the
2381
2669
            # transport can't support them, then we keep the non-disk-backed
2382
2670
            # branch and create a local checkout.
2383
 
            if self.vfs_transport_factory is LocalURLServer:
 
2671
            if self.vfs_transport_factory is test_server.LocalURLServer:
2384
2672
                # the branch is colocated on disk, we cannot create a checkout.
2385
2673
                # hopefully callers will expect this.
2386
2674
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2423
2711
        super(TestCaseWithTransport, self).setUp()
2424
2712
        self.__vfs_server = None
2425
2713
 
 
2714
    def disable_missing_extensions_warning(self):
 
2715
        """Some tests expect a precise stderr content.
 
2716
 
 
2717
        There is no point in forcing them to duplicate the extension related
 
2718
        warning.
 
2719
        """
 
2720
        config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
 
2721
 
2426
2722
 
2427
2723
class ChrootedTestCase(TestCaseWithTransport):
2428
2724
    """A support class that provides readonly urls outside the local namespace.
2438
2734
 
2439
2735
    def setUp(self):
2440
2736
        super(ChrootedTestCase, self).setUp()
2441
 
        if not self.vfs_transport_factory == MemoryServer:
 
2737
        if not self.vfs_transport_factory == memory.MemoryServer:
2442
2738
            self.transport_readonly_server = HttpServer
2443
2739
 
2444
2740
 
2448
2744
    :param pattern: A regular expression string.
2449
2745
    :return: A callable that returns True if the re matches.
2450
2746
    """
2451
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2452
 
        'test filter')
 
2747
    filter_re = re.compile(pattern, 0)
2453
2748
    def condition(test):
2454
2749
        test_id = test.id()
2455
2750
        return filter_re.search(test_id)
2642
2937
              strict=False,
2643
2938
              runner_class=None,
2644
2939
              suite_decorators=None,
2645
 
              stream=None):
 
2940
              stream=None,
 
2941
              result_decorators=None,
 
2942
              ):
2646
2943
    """Run a test suite for bzr selftest.
2647
2944
 
2648
2945
    :param runner_class: The class of runner to use. Must support the
2663
2960
                            descriptions=0,
2664
2961
                            verbosity=verbosity,
2665
2962
                            bench_history=bench_history,
2666
 
                            list_only=list_only,
2667
2963
                            strict=strict,
 
2964
                            result_decorators=result_decorators,
2668
2965
                            )
2669
2966
    runner.stop_on_failure=stop_on_failure
2670
2967
    # built in decorator factories:
2678
2975
        decorators.append(filter_tests(pattern))
2679
2976
    if suite_decorators:
2680
2977
        decorators.extend(suite_decorators)
 
2978
    # tell the result object how many tests will be running: (except if
 
2979
    # --parallel=fork is being used. Robert said he will provide a better
 
2980
    # progress design later -- vila 20090817)
 
2981
    if fork_decorator not in decorators:
 
2982
        decorators.append(CountingDecorator)
2681
2983
    for decorator in decorators:
2682
2984
        suite = decorator(suite)
 
2985
    if list_only:
 
2986
        # Done after test suite decoration to allow randomisation etc
 
2987
        # to take effect, though that is of marginal benefit.
 
2988
        if verbosity >= 2:
 
2989
            stream.write("Listing tests only ...\n")
 
2990
        for t in iter_suite_tests(suite):
 
2991
            stream.write("%s\n" % (t.id()))
 
2992
        return True
2683
2993
    result = runner.run(suite)
2684
 
    if list_only:
2685
 
        return True
2686
 
    result.done()
2687
2994
    if strict:
2688
2995
        return result.wasStrictlySuccessful()
2689
2996
    else:
2695
3002
 
2696
3003
 
2697
3004
def fork_decorator(suite):
2698
 
    concurrency = local_concurrency()
 
3005
    concurrency = osutils.local_concurrency()
2699
3006
    if concurrency == 1:
2700
3007
        return suite
2701
3008
    from testtools import ConcurrentTestSuite
2704
3011
 
2705
3012
 
2706
3013
def subprocess_decorator(suite):
2707
 
    concurrency = local_concurrency()
 
3014
    concurrency = osutils.local_concurrency()
2708
3015
    if concurrency == 1:
2709
3016
        return suite
2710
3017
    from testtools import ConcurrentTestSuite
2787
3094
        return result
2788
3095
 
2789
3096
 
 
3097
class CountingDecorator(TestDecorator):
 
3098
    """A decorator which calls result.progress(self.countTestCases)."""
 
3099
 
 
3100
    def run(self, result):
 
3101
        progress_method = getattr(result, 'progress', None)
 
3102
        if callable(progress_method):
 
3103
            progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
 
3104
        return super(CountingDecorator, self).run(result)
 
3105
 
 
3106
 
2790
3107
class ExcludeDecorator(TestDecorator):
2791
3108
    """A decorator which excludes test matching an exclude pattern."""
2792
3109
 
2836
3153
        if self.randomised:
2837
3154
            return iter(self._tests)
2838
3155
        self.randomised = True
2839
 
        self.stream.writeln("Randomizing test order using seed %s\n" %
 
3156
        self.stream.write("Randomizing test order using seed %s\n\n" %
2840
3157
            (self.actual_seed()))
2841
3158
        # Initialise the random number generator.
2842
3159
        random.seed(self.actual_seed())
2890
3207
    return result
2891
3208
 
2892
3209
 
 
3210
def workaround_zealous_crypto_random():
 
3211
    """Crypto.Random want to help us being secure, but we don't care here.
 
3212
 
 
3213
    This workaround some test failure related to the sftp server. Once paramiko
 
3214
    stop using the controversial API in Crypto.Random, we may get rid of it.
 
3215
    """
 
3216
    try:
 
3217
        from Crypto.Random import atfork
 
3218
        atfork()
 
3219
    except ImportError:
 
3220
        pass
 
3221
 
 
3222
 
2893
3223
def fork_for_tests(suite):
2894
3224
    """Take suite and start up one runner per CPU by forking()
2895
3225
 
2896
3226
    :return: An iterable of TestCase-like objects which can each have
2897
3227
        run(result) called on them to feed tests to result.
2898
3228
    """
2899
 
    concurrency = local_concurrency()
 
3229
    concurrency = osutils.local_concurrency()
2900
3230
    result = []
2901
3231
    from subunit import TestProtocolClient, ProtocolTestCase
 
3232
    from subunit.test_results import AutoTimingTestResultDecorator
2902
3233
    class TestInOtherProcess(ProtocolTestCase):
2903
3234
        # Should be in subunit, I think. RBC.
2904
3235
        def __init__(self, stream, pid):
2909
3240
            try:
2910
3241
                ProtocolTestCase.run(self, result)
2911
3242
            finally:
2912
 
                os.waitpid(self.pid, os.WNOHANG)
 
3243
                os.waitpid(self.pid, 0)
2913
3244
 
2914
3245
    test_blocks = partition_tests(suite, concurrency)
2915
3246
    for process_tests in test_blocks:
2918
3249
        c2pread, c2pwrite = os.pipe()
2919
3250
        pid = os.fork()
2920
3251
        if pid == 0:
 
3252
            workaround_zealous_crypto_random()
2921
3253
            try:
2922
3254
                os.close(c2pread)
2923
3255
                # Leave stderr and stdout open so we can see test noise
2927
3259
                sys.stdin.close()
2928
3260
                sys.stdin = None
2929
3261
                stream = os.fdopen(c2pwrite, 'wb', 1)
2930
 
                subunit_result = TestProtocolClient(stream)
 
3262
                subunit_result = AutoTimingTestResultDecorator(
 
3263
                    TestProtocolClient(stream))
2931
3264
                process_suite.run(subunit_result)
2932
3265
            finally:
2933
3266
                os._exit(0)
2945
3278
    :return: An iterable of TestCase-like objects which can each have
2946
3279
        run(result) called on them to feed tests to result.
2947
3280
    """
2948
 
    concurrency = local_concurrency()
 
3281
    concurrency = osutils.local_concurrency()
2949
3282
    result = []
2950
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3283
    from subunit import ProtocolTestCase
2951
3284
    class TestInSubprocess(ProtocolTestCase):
2952
3285
        def __init__(self, process, name):
2953
3286
            ProtocolTestCase.__init__(self, process.stdout)
2969
3302
        if not os.path.isfile(bzr_path):
2970
3303
            # We are probably installed. Assume sys.argv is the right file
2971
3304
            bzr_path = sys.argv[0]
 
3305
        bzr_path = [bzr_path]
 
3306
        if sys.platform == "win32":
 
3307
            # if we're on windows, we can't execute the bzr script directly
 
3308
            bzr_path = [sys.executable] + bzr_path
2972
3309
        fd, test_list_file_name = tempfile.mkstemp()
2973
3310
        test_list_file = os.fdopen(fd, 'wb', 1)
2974
3311
        for test in process_tests:
2975
3312
            test_list_file.write(test.id() + '\n')
2976
3313
        test_list_file.close()
2977
3314
        try:
2978
 
            argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
 
3315
            argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
2979
3316
                '--subunit']
2980
3317
            if '--no-plugins' in sys.argv:
2981
3318
                argv.append('--no-plugins')
2982
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
2983
 
            # stderr it can interrupt the subunit protocol.
2984
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
2985
 
                bufsize=1)
 
3319
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3320
            # noise on stderr it can interrupt the subunit protocol.
 
3321
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3322
                                      stdout=subprocess.PIPE,
 
3323
                                      stderr=subprocess.PIPE,
 
3324
                                      bufsize=1)
2986
3325
            test = TestInSubprocess(process, test_list_file_name)
2987
3326
            result.append(test)
2988
3327
        except:
2991
3330
    return result
2992
3331
 
2993
3332
 
2994
 
def cpucount(content):
2995
 
    lines = content.splitlines()
2996
 
    prefix = 'processor'
2997
 
    for line in lines:
2998
 
        if line.startswith(prefix):
2999
 
            concurrency = int(line[line.find(':')+1:]) + 1
3000
 
    return concurrency
3001
 
 
3002
 
 
3003
 
def local_concurrency():
3004
 
    try:
3005
 
        content = file('/proc/cpuinfo', 'rb').read()
3006
 
        concurrency = cpucount(content)
3007
 
    except Exception, e:
3008
 
        concurrency = 1
3009
 
    return concurrency
3010
 
 
3011
 
 
3012
 
class BZRTransformingResult(unittest.TestResult):
 
3333
class ForwardingResult(unittest.TestResult):
3013
3334
 
3014
3335
    def __init__(self, target):
3015
3336
        unittest.TestResult.__init__(self)
3021
3342
    def stopTest(self, test):
3022
3343
        self.result.stopTest(test)
3023
3344
 
3024
 
    def addError(self, test, err):
3025
 
        feature = self._error_looks_like('UnavailableFeature: ', err)
3026
 
        if feature is not None:
3027
 
            self.result.addNotSupported(test, feature)
3028
 
        else:
3029
 
            self.result.addError(test, err)
 
3345
    def startTestRun(self):
 
3346
        self.result.startTestRun()
3030
3347
 
3031
 
    def addFailure(self, test, err):
3032
 
        known = self._error_looks_like('KnownFailure: ', err)
3033
 
        if known is not None:
3034
 
            self.result._addKnownFailure(test, [KnownFailure,
3035
 
                                                KnownFailure(known), None])
3036
 
        else:
3037
 
            self.result.addFailure(test, err)
 
3348
    def stopTestRun(self):
 
3349
        self.result.stopTestRun()
3038
3350
 
3039
3351
    def addSkip(self, test, reason):
3040
3352
        self.result.addSkip(test, reason)
3042
3354
    def addSuccess(self, test):
3043
3355
        self.result.addSuccess(test)
3044
3356
 
3045
 
    def _error_looks_like(self, prefix, err):
3046
 
        """Deserialize exception and returns the stringify value."""
3047
 
        import subunit
3048
 
        value = None
3049
 
        typ, exc, _ = err
3050
 
        if isinstance(exc, subunit.RemoteException):
3051
 
            # stringify the exception gives access to the remote traceback
3052
 
            # We search the last line for 'prefix'
3053
 
            lines = str(exc).split('\n')
3054
 
            while lines and not lines[-1]:
3055
 
                lines.pop(-1)
3056
 
            if lines:
3057
 
                if lines[-1].startswith(prefix):
3058
 
                    value = lines[-1][len(prefix):]
3059
 
        return value
 
3357
    def addError(self, test, err):
 
3358
        self.result.addError(test, err)
 
3359
 
 
3360
    def addFailure(self, test, err):
 
3361
        self.result.addFailure(test, err)
 
3362
ForwardingResult = testtools.ExtendedToOriginalDecorator
 
3363
 
 
3364
 
 
3365
class ProfileResult(ForwardingResult):
 
3366
    """Generate profiling data for all activity between start and success.
 
3367
    
 
3368
    The profile data is appended to the test's _benchcalls attribute and can
 
3369
    be accessed by the forwarded-to TestResult.
 
3370
 
 
3371
    While it might be cleaner do accumulate this in stopTest, addSuccess is
 
3372
    where our existing output support for lsprof is, and this class aims to
 
3373
    fit in with that: while it could be moved it's not necessary to accomplish
 
3374
    test profiling, nor would it be dramatically cleaner.
 
3375
    """
 
3376
 
 
3377
    def startTest(self, test):
 
3378
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3379
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3380
        # unavoidably fail.
 
3381
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
 
3382
        self.profiler.start()
 
3383
        ForwardingResult.startTest(self, test)
 
3384
 
 
3385
    def addSuccess(self, test):
 
3386
        stats = self.profiler.stop()
 
3387
        try:
 
3388
            calls = test._benchcalls
 
3389
        except AttributeError:
 
3390
            test._benchcalls = []
 
3391
            calls = test._benchcalls
 
3392
        calls.append(((test.id(), "", ""), stats))
 
3393
        ForwardingResult.addSuccess(self, test)
 
3394
 
 
3395
    def stopTest(self, test):
 
3396
        ForwardingResult.stopTest(self, test)
 
3397
        self.profiler = None
3060
3398
 
3061
3399
 
3062
3400
# Controlled by "bzr selftest -E=..." option
 
3401
# Currently supported:
 
3402
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
 
3403
#                           preserves any flags supplied at the command line.
 
3404
#   -Edisable_lock_checks   Turns errors in mismatched locks into simple prints
 
3405
#                           rather than failing tests. And no longer raise
 
3406
#                           LockContention when fctnl locks are not being used
 
3407
#                           with proper exclusion rules.
3063
3408
selftest_debug_flags = set()
3064
3409
 
3065
3410
 
3078
3423
             starting_with=None,
3079
3424
             runner_class=None,
3080
3425
             suite_decorators=None,
 
3426
             stream=None,
 
3427
             lsprof_tests=False,
3081
3428
             ):
3082
3429
    """Run the whole test suite under the enhanced runner"""
3083
3430
    # XXX: Very ugly way to do this...
3100
3447
            keep_only = None
3101
3448
        else:
3102
3449
            keep_only = load_test_id_list(load_list)
 
3450
        if starting_with:
 
3451
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
 
3452
                             for start in starting_with]
3103
3453
        if test_suite_factory is None:
 
3454
            # Reduce loading time by loading modules based on the starting_with
 
3455
            # patterns.
3104
3456
            suite = test_suite(keep_only, starting_with)
3105
3457
        else:
3106
3458
            suite = test_suite_factory()
 
3459
        if starting_with:
 
3460
            # But always filter as requested.
 
3461
            suite = filter_suite_by_id_startswith(suite, starting_with)
 
3462
        result_decorators = []
 
3463
        if lsprof_tests:
 
3464
            result_decorators.append(ProfileResult)
3107
3465
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3108
3466
                     stop_on_failure=stop_on_failure,
3109
3467
                     transport=transport,
3116
3474
                     strict=strict,
3117
3475
                     runner_class=runner_class,
3118
3476
                     suite_decorators=suite_decorators,
 
3477
                     stream=stream,
 
3478
                     result_decorators=result_decorators,
3119
3479
                     )
3120
3480
    finally:
3121
3481
        default_transport = old_transport
3269
3629
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3270
3630
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3271
3631
 
3272
 
# Obvious higest levels prefixes, feel free to add your own via a plugin
 
3632
# Obvious highest levels prefixes, feel free to add your own via a plugin
3273
3633
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3274
3634
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3275
3635
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3277
3637
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3278
3638
 
3279
3639
 
 
3640
def _test_suite_testmod_names():
 
3641
    """Return the standard list of test module names to test."""
 
3642
    return [
 
3643
        'bzrlib.doc',
 
3644
        'bzrlib.tests.blackbox',
 
3645
        'bzrlib.tests.commands',
 
3646
        'bzrlib.tests.per_branch',
 
3647
        'bzrlib.tests.per_bzrdir',
 
3648
        'bzrlib.tests.per_bzrdir_colo',
 
3649
        'bzrlib.tests.per_foreign_vcs',
 
3650
        'bzrlib.tests.per_interrepository',
 
3651
        'bzrlib.tests.per_intertree',
 
3652
        'bzrlib.tests.per_inventory',
 
3653
        'bzrlib.tests.per_interbranch',
 
3654
        'bzrlib.tests.per_lock',
 
3655
        'bzrlib.tests.per_merger',
 
3656
        'bzrlib.tests.per_transport',
 
3657
        'bzrlib.tests.per_tree',
 
3658
        'bzrlib.tests.per_pack_repository',
 
3659
        'bzrlib.tests.per_repository',
 
3660
        'bzrlib.tests.per_repository_chk',
 
3661
        'bzrlib.tests.per_repository_reference',
 
3662
        'bzrlib.tests.per_uifactory',
 
3663
        'bzrlib.tests.per_versionedfile',
 
3664
        'bzrlib.tests.per_workingtree',
 
3665
        'bzrlib.tests.test__annotator',
 
3666
        'bzrlib.tests.test__bencode',
 
3667
        'bzrlib.tests.test__chk_map',
 
3668
        'bzrlib.tests.test__dirstate_helpers',
 
3669
        'bzrlib.tests.test__groupcompress',
 
3670
        'bzrlib.tests.test__known_graph',
 
3671
        'bzrlib.tests.test__rio',
 
3672
        'bzrlib.tests.test__simple_set',
 
3673
        'bzrlib.tests.test__static_tuple',
 
3674
        'bzrlib.tests.test__walkdirs_win32',
 
3675
        'bzrlib.tests.test_ancestry',
 
3676
        'bzrlib.tests.test_annotate',
 
3677
        'bzrlib.tests.test_api',
 
3678
        'bzrlib.tests.test_atomicfile',
 
3679
        'bzrlib.tests.test_bad_files',
 
3680
        'bzrlib.tests.test_bisect_multi',
 
3681
        'bzrlib.tests.test_branch',
 
3682
        'bzrlib.tests.test_branchbuilder',
 
3683
        'bzrlib.tests.test_btree_index',
 
3684
        'bzrlib.tests.test_bugtracker',
 
3685
        'bzrlib.tests.test_bundle',
 
3686
        'bzrlib.tests.test_bzrdir',
 
3687
        'bzrlib.tests.test__chunks_to_lines',
 
3688
        'bzrlib.tests.test_cache_utf8',
 
3689
        'bzrlib.tests.test_chk_map',
 
3690
        'bzrlib.tests.test_chk_serializer',
 
3691
        'bzrlib.tests.test_chunk_writer',
 
3692
        'bzrlib.tests.test_clean_tree',
 
3693
        'bzrlib.tests.test_cleanup',
 
3694
        'bzrlib.tests.test_cmdline',
 
3695
        'bzrlib.tests.test_commands',
 
3696
        'bzrlib.tests.test_commit',
 
3697
        'bzrlib.tests.test_commit_merge',
 
3698
        'bzrlib.tests.test_config',
 
3699
        'bzrlib.tests.test_conflicts',
 
3700
        'bzrlib.tests.test_counted_lock',
 
3701
        'bzrlib.tests.test_crash',
 
3702
        'bzrlib.tests.test_decorators',
 
3703
        'bzrlib.tests.test_delta',
 
3704
        'bzrlib.tests.test_debug',
 
3705
        'bzrlib.tests.test_deprecated_graph',
 
3706
        'bzrlib.tests.test_diff',
 
3707
        'bzrlib.tests.test_directory_service',
 
3708
        'bzrlib.tests.test_dirstate',
 
3709
        'bzrlib.tests.test_email_message',
 
3710
        'bzrlib.tests.test_eol_filters',
 
3711
        'bzrlib.tests.test_errors',
 
3712
        'bzrlib.tests.test_export',
 
3713
        'bzrlib.tests.test_extract',
 
3714
        'bzrlib.tests.test_fetch',
 
3715
        'bzrlib.tests.test_fixtures',
 
3716
        'bzrlib.tests.test_fifo_cache',
 
3717
        'bzrlib.tests.test_filters',
 
3718
        'bzrlib.tests.test_ftp_transport',
 
3719
        'bzrlib.tests.test_foreign',
 
3720
        'bzrlib.tests.test_generate_docs',
 
3721
        'bzrlib.tests.test_generate_ids',
 
3722
        'bzrlib.tests.test_globbing',
 
3723
        'bzrlib.tests.test_gpg',
 
3724
        'bzrlib.tests.test_graph',
 
3725
        'bzrlib.tests.test_groupcompress',
 
3726
        'bzrlib.tests.test_hashcache',
 
3727
        'bzrlib.tests.test_help',
 
3728
        'bzrlib.tests.test_hooks',
 
3729
        'bzrlib.tests.test_http',
 
3730
        'bzrlib.tests.test_http_response',
 
3731
        'bzrlib.tests.test_https_ca_bundle',
 
3732
        'bzrlib.tests.test_identitymap',
 
3733
        'bzrlib.tests.test_ignores',
 
3734
        'bzrlib.tests.test_index',
 
3735
        'bzrlib.tests.test_import_tariff',
 
3736
        'bzrlib.tests.test_info',
 
3737
        'bzrlib.tests.test_inv',
 
3738
        'bzrlib.tests.test_inventory_delta',
 
3739
        'bzrlib.tests.test_knit',
 
3740
        'bzrlib.tests.test_lazy_import',
 
3741
        'bzrlib.tests.test_lazy_regex',
 
3742
        'bzrlib.tests.test_library_state',
 
3743
        'bzrlib.tests.test_lock',
 
3744
        'bzrlib.tests.test_lockable_files',
 
3745
        'bzrlib.tests.test_lockdir',
 
3746
        'bzrlib.tests.test_log',
 
3747
        'bzrlib.tests.test_lru_cache',
 
3748
        'bzrlib.tests.test_lsprof',
 
3749
        'bzrlib.tests.test_mail_client',
 
3750
        'bzrlib.tests.test_matchers',
 
3751
        'bzrlib.tests.test_memorytree',
 
3752
        'bzrlib.tests.test_merge',
 
3753
        'bzrlib.tests.test_merge3',
 
3754
        'bzrlib.tests.test_merge_core',
 
3755
        'bzrlib.tests.test_merge_directive',
 
3756
        'bzrlib.tests.test_missing',
 
3757
        'bzrlib.tests.test_msgeditor',
 
3758
        'bzrlib.tests.test_multiparent',
 
3759
        'bzrlib.tests.test_mutabletree',
 
3760
        'bzrlib.tests.test_nonascii',
 
3761
        'bzrlib.tests.test_options',
 
3762
        'bzrlib.tests.test_osutils',
 
3763
        'bzrlib.tests.test_osutils_encodings',
 
3764
        'bzrlib.tests.test_pack',
 
3765
        'bzrlib.tests.test_patch',
 
3766
        'bzrlib.tests.test_patches',
 
3767
        'bzrlib.tests.test_permissions',
 
3768
        'bzrlib.tests.test_plugins',
 
3769
        'bzrlib.tests.test_progress',
 
3770
        'bzrlib.tests.test_read_bundle',
 
3771
        'bzrlib.tests.test_reconcile',
 
3772
        'bzrlib.tests.test_reconfigure',
 
3773
        'bzrlib.tests.test_registry',
 
3774
        'bzrlib.tests.test_remote',
 
3775
        'bzrlib.tests.test_rename_map',
 
3776
        'bzrlib.tests.test_repository',
 
3777
        'bzrlib.tests.test_revert',
 
3778
        'bzrlib.tests.test_revision',
 
3779
        'bzrlib.tests.test_revisionspec',
 
3780
        'bzrlib.tests.test_revisiontree',
 
3781
        'bzrlib.tests.test_rio',
 
3782
        'bzrlib.tests.test_rules',
 
3783
        'bzrlib.tests.test_sampler',
 
3784
        'bzrlib.tests.test_script',
 
3785
        'bzrlib.tests.test_selftest',
 
3786
        'bzrlib.tests.test_serializer',
 
3787
        'bzrlib.tests.test_setup',
 
3788
        'bzrlib.tests.test_sftp_transport',
 
3789
        'bzrlib.tests.test_shelf',
 
3790
        'bzrlib.tests.test_shelf_ui',
 
3791
        'bzrlib.tests.test_smart',
 
3792
        'bzrlib.tests.test_smart_add',
 
3793
        'bzrlib.tests.test_smart_request',
 
3794
        'bzrlib.tests.test_smart_transport',
 
3795
        'bzrlib.tests.test_smtp_connection',
 
3796
        'bzrlib.tests.test_source',
 
3797
        'bzrlib.tests.test_ssh_transport',
 
3798
        'bzrlib.tests.test_status',
 
3799
        'bzrlib.tests.test_store',
 
3800
        'bzrlib.tests.test_strace',
 
3801
        'bzrlib.tests.test_subsume',
 
3802
        'bzrlib.tests.test_switch',
 
3803
        'bzrlib.tests.test_symbol_versioning',
 
3804
        'bzrlib.tests.test_tag',
 
3805
        'bzrlib.tests.test_testament',
 
3806
        'bzrlib.tests.test_textfile',
 
3807
        'bzrlib.tests.test_textmerge',
 
3808
        'bzrlib.tests.test_timestamp',
 
3809
        'bzrlib.tests.test_trace',
 
3810
        'bzrlib.tests.test_transactions',
 
3811
        'bzrlib.tests.test_transform',
 
3812
        'bzrlib.tests.test_transport',
 
3813
        'bzrlib.tests.test_transport_log',
 
3814
        'bzrlib.tests.test_tree',
 
3815
        'bzrlib.tests.test_treebuilder',
 
3816
        'bzrlib.tests.test_tsort',
 
3817
        'bzrlib.tests.test_tuned_gzip',
 
3818
        'bzrlib.tests.test_ui',
 
3819
        'bzrlib.tests.test_uncommit',
 
3820
        'bzrlib.tests.test_upgrade',
 
3821
        'bzrlib.tests.test_upgrade_stacked',
 
3822
        'bzrlib.tests.test_urlutils',
 
3823
        'bzrlib.tests.test_version',
 
3824
        'bzrlib.tests.test_version_info',
 
3825
        'bzrlib.tests.test_weave',
 
3826
        'bzrlib.tests.test_whitebox',
 
3827
        'bzrlib.tests.test_win32utils',
 
3828
        'bzrlib.tests.test_workingtree',
 
3829
        'bzrlib.tests.test_workingtree_4',
 
3830
        'bzrlib.tests.test_wsgi',
 
3831
        'bzrlib.tests.test_xml',
 
3832
        ]
 
3833
 
 
3834
 
 
3835
def _test_suite_modules_to_doctest():
 
3836
    """Return the list of modules to doctest."""
 
3837
    if __doc__ is None:
 
3838
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
 
3839
        return []
 
3840
    return [
 
3841
        'bzrlib',
 
3842
        'bzrlib.branchbuilder',
 
3843
        'bzrlib.decorators',
 
3844
        'bzrlib.export',
 
3845
        'bzrlib.inventory',
 
3846
        'bzrlib.iterablefile',
 
3847
        'bzrlib.lockdir',
 
3848
        'bzrlib.merge3',
 
3849
        'bzrlib.option',
 
3850
        'bzrlib.symbol_versioning',
 
3851
        'bzrlib.tests',
 
3852
        'bzrlib.tests.fixtures',
 
3853
        'bzrlib.timestamp',
 
3854
        'bzrlib.version_info_formats.format_custom',
 
3855
        ]
 
3856
 
 
3857
 
3280
3858
def test_suite(keep_only=None, starting_with=None):
3281
3859
    """Build and return TestSuite for the whole of bzrlib.
3282
3860
 
3288
3866
    This function can be replaced if you need to change the default test
3289
3867
    suite on a global basis, but it is not encouraged.
3290
3868
    """
3291
 
    testmod_names = [
3292
 
                   'bzrlib.doc',
3293
 
                   'bzrlib.tests.blackbox',
3294
 
                   'bzrlib.tests.branch_implementations',
3295
 
                   'bzrlib.tests.bzrdir_implementations',
3296
 
                   'bzrlib.tests.commands',
3297
 
                   'bzrlib.tests.interrepository_implementations',
3298
 
                   'bzrlib.tests.intertree_implementations',
3299
 
                   'bzrlib.tests.inventory_implementations',
3300
 
                   'bzrlib.tests.per_interbranch',
3301
 
                   'bzrlib.tests.per_lock',
3302
 
                   'bzrlib.tests.per_repository',
3303
 
                   'bzrlib.tests.per_repository_chk',
3304
 
                   'bzrlib.tests.per_repository_reference',
3305
 
                   'bzrlib.tests.test__chk_map',
3306
 
                   'bzrlib.tests.test__dirstate_helpers',
3307
 
                   'bzrlib.tests.test__groupcompress',
3308
 
                   'bzrlib.tests.test__walkdirs_win32',
3309
 
                   'bzrlib.tests.test_ancestry',
3310
 
                   'bzrlib.tests.test_annotate',
3311
 
                   'bzrlib.tests.test_api',
3312
 
                   'bzrlib.tests.test_atomicfile',
3313
 
                   'bzrlib.tests.test_bad_files',
3314
 
                   'bzrlib.tests.test_bisect_multi',
3315
 
                   'bzrlib.tests.test_branch',
3316
 
                   'bzrlib.tests.test_branchbuilder',
3317
 
                   'bzrlib.tests.test_btree_index',
3318
 
                   'bzrlib.tests.test_bugtracker',
3319
 
                   'bzrlib.tests.test_bundle',
3320
 
                   'bzrlib.tests.test_bzrdir',
3321
 
                   'bzrlib.tests.test__chunks_to_lines',
3322
 
                   'bzrlib.tests.test_cache_utf8',
3323
 
                   'bzrlib.tests.test_chk_map',
3324
 
                   'bzrlib.tests.test_chunk_writer',
3325
 
                   'bzrlib.tests.test_clean_tree',
3326
 
                   'bzrlib.tests.test_commands',
3327
 
                   'bzrlib.tests.test_commit',
3328
 
                   'bzrlib.tests.test_commit_merge',
3329
 
                   'bzrlib.tests.test_config',
3330
 
                   'bzrlib.tests.test_conflicts',
3331
 
                   'bzrlib.tests.test_counted_lock',
3332
 
                   'bzrlib.tests.test_decorators',
3333
 
                   'bzrlib.tests.test_delta',
3334
 
                   'bzrlib.tests.test_debug',
3335
 
                   'bzrlib.tests.test_deprecated_graph',
3336
 
                   'bzrlib.tests.test_diff',
3337
 
                   'bzrlib.tests.test_directory_service',
3338
 
                   'bzrlib.tests.test_dirstate',
3339
 
                   'bzrlib.tests.test_email_message',
3340
 
                   'bzrlib.tests.test_eol_filters',
3341
 
                   'bzrlib.tests.test_errors',
3342
 
                   'bzrlib.tests.test_export',
3343
 
                   'bzrlib.tests.test_extract',
3344
 
                   'bzrlib.tests.test_fetch',
3345
 
                   'bzrlib.tests.test_fifo_cache',
3346
 
                   'bzrlib.tests.test_filters',
3347
 
                   'bzrlib.tests.test_ftp_transport',
3348
 
                   'bzrlib.tests.test_foreign',
3349
 
                   'bzrlib.tests.test_generate_docs',
3350
 
                   'bzrlib.tests.test_generate_ids',
3351
 
                   'bzrlib.tests.test_globbing',
3352
 
                   'bzrlib.tests.test_gpg',
3353
 
                   'bzrlib.tests.test_graph',
3354
 
                   'bzrlib.tests.test_groupcompress',
3355
 
                   'bzrlib.tests.test_hashcache',
3356
 
                   'bzrlib.tests.test_help',
3357
 
                   'bzrlib.tests.test_hooks',
3358
 
                   'bzrlib.tests.test_http',
3359
 
                   'bzrlib.tests.test_http_implementations',
3360
 
                   'bzrlib.tests.test_http_response',
3361
 
                   'bzrlib.tests.test_https_ca_bundle',
3362
 
                   'bzrlib.tests.test_identitymap',
3363
 
                   'bzrlib.tests.test_ignores',
3364
 
                   'bzrlib.tests.test_index',
3365
 
                   'bzrlib.tests.test_info',
3366
 
                   'bzrlib.tests.test_inv',
3367
 
                   'bzrlib.tests.test_inventory_delta',
3368
 
                   'bzrlib.tests.test_knit',
3369
 
                   'bzrlib.tests.test_lazy_import',
3370
 
                   'bzrlib.tests.test_lazy_regex',
3371
 
                   'bzrlib.tests.test_lockable_files',
3372
 
                   'bzrlib.tests.test_lockdir',
3373
 
                   'bzrlib.tests.test_log',
3374
 
                   'bzrlib.tests.test_lru_cache',
3375
 
                   'bzrlib.tests.test_lsprof',
3376
 
                   'bzrlib.tests.test_mail_client',
3377
 
                   'bzrlib.tests.test_memorytree',
3378
 
                   'bzrlib.tests.test_merge',
3379
 
                   'bzrlib.tests.test_merge3',
3380
 
                   'bzrlib.tests.test_merge_core',
3381
 
                   'bzrlib.tests.test_merge_directive',
3382
 
                   'bzrlib.tests.test_missing',
3383
 
                   'bzrlib.tests.test_msgeditor',
3384
 
                   'bzrlib.tests.test_multiparent',
3385
 
                   'bzrlib.tests.test_mutabletree',
3386
 
                   'bzrlib.tests.test_nonascii',
3387
 
                   'bzrlib.tests.test_options',
3388
 
                   'bzrlib.tests.test_osutils',
3389
 
                   'bzrlib.tests.test_osutils_encodings',
3390
 
                   'bzrlib.tests.test_pack',
3391
 
                   'bzrlib.tests.test_pack_repository',
3392
 
                   'bzrlib.tests.test_patch',
3393
 
                   'bzrlib.tests.test_patches',
3394
 
                   'bzrlib.tests.test_permissions',
3395
 
                   'bzrlib.tests.test_plugins',
3396
 
                   'bzrlib.tests.test_progress',
3397
 
                   'bzrlib.tests.test_read_bundle',
3398
 
                   'bzrlib.tests.test_reconcile',
3399
 
                   'bzrlib.tests.test_reconfigure',
3400
 
                   'bzrlib.tests.test_registry',
3401
 
                   'bzrlib.tests.test_remote',
3402
 
                   'bzrlib.tests.test_rename_map',
3403
 
                   'bzrlib.tests.test_repository',
3404
 
                   'bzrlib.tests.test_revert',
3405
 
                   'bzrlib.tests.test_revision',
3406
 
                   'bzrlib.tests.test_revisionspec',
3407
 
                   'bzrlib.tests.test_revisiontree',
3408
 
                   'bzrlib.tests.test_rio',
3409
 
                   'bzrlib.tests.test_rules',
3410
 
                   'bzrlib.tests.test_sampler',
3411
 
                   'bzrlib.tests.test_selftest',
3412
 
                   'bzrlib.tests.test_serializer',
3413
 
                   'bzrlib.tests.test_setup',
3414
 
                   'bzrlib.tests.test_sftp_transport',
3415
 
                   'bzrlib.tests.test_shelf',
3416
 
                   'bzrlib.tests.test_shelf_ui',
3417
 
                   'bzrlib.tests.test_smart',
3418
 
                   'bzrlib.tests.test_smart_add',
3419
 
                   'bzrlib.tests.test_smart_request',
3420
 
                   'bzrlib.tests.test_smart_transport',
3421
 
                   'bzrlib.tests.test_smtp_connection',
3422
 
                   'bzrlib.tests.test_source',
3423
 
                   'bzrlib.tests.test_ssh_transport',
3424
 
                   'bzrlib.tests.test_status',
3425
 
                   'bzrlib.tests.test_store',
3426
 
                   'bzrlib.tests.test_strace',
3427
 
                   'bzrlib.tests.test_subsume',
3428
 
                   'bzrlib.tests.test_switch',
3429
 
                   'bzrlib.tests.test_symbol_versioning',
3430
 
                   'bzrlib.tests.test_tag',
3431
 
                   'bzrlib.tests.test_testament',
3432
 
                   'bzrlib.tests.test_textfile',
3433
 
                   'bzrlib.tests.test_textmerge',
3434
 
                   'bzrlib.tests.test_timestamp',
3435
 
                   'bzrlib.tests.test_trace',
3436
 
                   'bzrlib.tests.test_transactions',
3437
 
                   'bzrlib.tests.test_transform',
3438
 
                   'bzrlib.tests.test_transport',
3439
 
                   'bzrlib.tests.test_transport_implementations',
3440
 
                   'bzrlib.tests.test_transport_log',
3441
 
                   'bzrlib.tests.test_tree',
3442
 
                   'bzrlib.tests.test_treebuilder',
3443
 
                   'bzrlib.tests.test_tsort',
3444
 
                   'bzrlib.tests.test_tuned_gzip',
3445
 
                   'bzrlib.tests.test_ui',
3446
 
                   'bzrlib.tests.test_uncommit',
3447
 
                   'bzrlib.tests.test_upgrade',
3448
 
                   'bzrlib.tests.test_upgrade_stacked',
3449
 
                   'bzrlib.tests.test_urlutils',
3450
 
                   'bzrlib.tests.test_version',
3451
 
                   'bzrlib.tests.test_version_info',
3452
 
                   'bzrlib.tests.test_versionedfile',
3453
 
                   'bzrlib.tests.test_weave',
3454
 
                   'bzrlib.tests.test_whitebox',
3455
 
                   'bzrlib.tests.test_win32utils',
3456
 
                   'bzrlib.tests.test_workingtree',
3457
 
                   'bzrlib.tests.test_workingtree_4',
3458
 
                   'bzrlib.tests.test_wsgi',
3459
 
                   'bzrlib.tests.test_xml',
3460
 
                   'bzrlib.tests.tree_implementations',
3461
 
                   'bzrlib.tests.workingtree_implementations',
3462
 
                   'bzrlib.util.tests.test_bencode',
3463
 
                   ]
3464
3869
 
3465
3870
    loader = TestUtil.TestLoader()
3466
3871
 
 
3872
    if keep_only is not None:
 
3873
        id_filter = TestIdList(keep_only)
3467
3874
    if starting_with:
3468
 
        starting_with = [test_prefix_alias_registry.resolve_alias(start)
3469
 
                         for start in starting_with]
3470
3875
        # We take precedence over keep_only because *at loading time* using
3471
3876
        # both options means we will load less tests for the same final result.
3472
3877
        def interesting_module(name):
3482
3887
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
3483
3888
 
3484
3889
    elif keep_only is not None:
3485
 
        id_filter = TestIdList(keep_only)
3486
3890
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3487
3891
        def interesting_module(name):
3488
3892
            return id_filter.refers_to(name)
3496
3900
    suite = loader.suiteClass()
3497
3901
 
3498
3902
    # modules building their suite with loadTestsFromModuleNames
3499
 
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
3500
 
 
3501
 
    modules_to_doctest = [
3502
 
        'bzrlib',
3503
 
        'bzrlib.branchbuilder',
3504
 
        'bzrlib.export',
3505
 
        'bzrlib.inventory',
3506
 
        'bzrlib.iterablefile',
3507
 
        'bzrlib.lockdir',
3508
 
        'bzrlib.merge3',
3509
 
        'bzrlib.option',
3510
 
        'bzrlib.symbol_versioning',
3511
 
        'bzrlib.tests',
3512
 
        'bzrlib.timestamp',
3513
 
        'bzrlib.version_info_formats.format_custom',
3514
 
        ]
3515
 
 
3516
 
    for mod in modules_to_doctest:
 
3903
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
 
3904
 
 
3905
    for mod in _test_suite_modules_to_doctest():
3517
3906
        if not interesting_module(mod):
3518
3907
            # No tests to keep here, move along
3519
3908
            continue
3548
3937
            reload(sys)
3549
3938
            sys.setdefaultencoding(default_encoding)
3550
3939
 
3551
 
    if starting_with:
3552
 
        suite = filter_suite_by_id_startswith(suite, starting_with)
3553
 
 
3554
3940
    if keep_only is not None:
3555
3941
        # Now that the referred modules have loaded their tests, keep only the
3556
3942
        # requested ones.
3663
4049
    :param new_id: The id to assign to it.
3664
4050
    :return: The new test.
3665
4051
    """
3666
 
    from copy import deepcopy
3667
 
    new_test = deepcopy(test)
 
4052
    new_test = copy.copy(test)
3668
4053
    new_test.id = lambda: new_id
3669
4054
    return new_test
3670
4055
 
3671
4056
 
3672
 
def _rmtree_temp_dir(dirname):
 
4057
def permute_tests_for_extension(standard_tests, loader, py_module_name,
 
4058
                                ext_module_name):
 
4059
    """Helper for permutating tests against an extension module.
 
4060
 
 
4061
    This is meant to be used inside a modules 'load_tests()' function. It will
 
4062
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
 
4063
    against both implementations. Setting 'test.module' to the appropriate
 
4064
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
 
4065
 
 
4066
    :param standard_tests: A test suite to permute
 
4067
    :param loader: A TestLoader
 
4068
    :param py_module_name: The python path to a python module that can always
 
4069
        be loaded, and will be considered the 'python' implementation. (eg
 
4070
        'bzrlib._chk_map_py')
 
4071
    :param ext_module_name: The python path to an extension module. If the
 
4072
        module cannot be loaded, a single test will be added, which notes that
 
4073
        the module is not available. If it can be loaded, all standard_tests
 
4074
        will be run against that module.
 
4075
    :return: (suite, feature) suite is a test-suite that has all the permuted
 
4076
        tests. feature is the Feature object that can be used to determine if
 
4077
        the module is available.
 
4078
    """
 
4079
 
 
4080
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4081
    scenarios = [
 
4082
        ('python', {'module': py_module}),
 
4083
    ]
 
4084
    suite = loader.suiteClass()
 
4085
    feature = ModuleAvailableFeature(ext_module_name)
 
4086
    if feature.available():
 
4087
        scenarios.append(('C', {'module': feature.module}))
 
4088
    else:
 
4089
        # the compiled module isn't available, so we add a failing test
 
4090
        class FailWithoutFeature(TestCase):
 
4091
            def test_fail(self):
 
4092
                self.requireFeature(feature)
 
4093
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
 
4094
    result = multiply_tests(standard_tests, scenarios, suite)
 
4095
    return result, feature
 
4096
 
 
4097
 
 
4098
def _rmtree_temp_dir(dirname, test_id=None):
3673
4099
    # If LANG=C we probably have created some bogus paths
3674
4100
    # which rmtree(unicode) will fail to delete
3675
4101
    # so make sure we are using rmtree(str) to delete everything
3684
4110
    try:
3685
4111
        osutils.rmtree(dirname)
3686
4112
    except OSError, e:
3687
 
        if sys.platform == 'win32' and e.errno == errno.EACCES:
3688
 
            sys.stderr.write('Permission denied: '
3689
 
                             'unable to remove testing dir '
3690
 
                             '%s\n%s'
3691
 
                             % (os.path.basename(dirname), e))
3692
 
        else:
3693
 
            raise
 
4113
        # We don't want to fail here because some useful display will be lost
 
4114
        # otherwise. Polluting the tmp dir is bad, but not giving all the
 
4115
        # possible info to the test runner is even worse.
 
4116
        if test_id != None:
 
4117
            ui.ui_factory.clear_term()
 
4118
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4119
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4120
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4121
                                    ).encode('ascii', 'replace')
 
4122
        sys.stderr.write('Unable to remove testing dir %s\n%s'
 
4123
                         % (os.path.basename(dirname), printable_e))
3694
4124
 
3695
4125
 
3696
4126
class Feature(object):
3778
4208
UnicodeFilenameFeature = _UnicodeFilenameFeature()
3779
4209
 
3780
4210
 
 
4211
class _CompatabilityThunkFeature(Feature):
 
4212
    """This feature is just a thunk to another feature.
 
4213
 
 
4214
    It issues a deprecation warning if it is accessed, to let you know that you
 
4215
    should really use a different feature.
 
4216
    """
 
4217
 
 
4218
    def __init__(self, dep_version, module, name,
 
4219
                 replacement_name, replacement_module=None):
 
4220
        super(_CompatabilityThunkFeature, self).__init__()
 
4221
        self._module = module
 
4222
        if replacement_module is None:
 
4223
            replacement_module = module
 
4224
        self._replacement_module = replacement_module
 
4225
        self._name = name
 
4226
        self._replacement_name = replacement_name
 
4227
        self._dep_version = dep_version
 
4228
        self._feature = None
 
4229
 
 
4230
    def _ensure(self):
 
4231
        if self._feature is None:
 
4232
            depr_msg = self._dep_version % ('%s.%s'
 
4233
                                            % (self._module, self._name))
 
4234
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
 
4235
                                               self._replacement_name)
 
4236
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
 
4237
            # Import the new feature and use it as a replacement for the
 
4238
            # deprecated one.
 
4239
            mod = __import__(self._replacement_module, {}, {},
 
4240
                             [self._replacement_name])
 
4241
            self._feature = getattr(mod, self._replacement_name)
 
4242
 
 
4243
    def _probe(self):
 
4244
        self._ensure()
 
4245
        return self._feature._probe()
 
4246
 
 
4247
 
 
4248
class ModuleAvailableFeature(Feature):
 
4249
    """This is a feature than describes a module we want to be available.
 
4250
 
 
4251
    Declare the name of the module in __init__(), and then after probing, the
 
4252
    module will be available as 'self.module'.
 
4253
 
 
4254
    :ivar module: The module if it is available, else None.
 
4255
    """
 
4256
 
 
4257
    def __init__(self, module_name):
 
4258
        super(ModuleAvailableFeature, self).__init__()
 
4259
        self.module_name = module_name
 
4260
 
 
4261
    def _probe(self):
 
4262
        try:
 
4263
            self._module = __import__(self.module_name, {}, {}, [''])
 
4264
            return True
 
4265
        except ImportError:
 
4266
            return False
 
4267
 
 
4268
    @property
 
4269
    def module(self):
 
4270
        if self.available(): # Make sure the probe has been done
 
4271
            return self._module
 
4272
        return None
 
4273
 
 
4274
    def feature_name(self):
 
4275
        return self.module_name
 
4276
 
 
4277
 
 
4278
# This is kept here for compatibility, it is recommended to use
 
4279
# 'bzrlib.tests.feature.paramiko' instead
 
4280
ParamikoFeature = _CompatabilityThunkFeature(
 
4281
    deprecated_in((2,1,0)),
 
4282
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
 
4283
 
 
4284
 
3781
4285
def probe_unicode_in_user_encoding():
3782
4286
    """Try to encode several unicode strings to use in unicode-aware tests.
3783
4287
    Return first successfull match.
3852
4356
UnicodeFilename = _UnicodeFilename()
3853
4357
 
3854
4358
 
 
4359
class _ByteStringNamedFilesystem(Feature):
 
4360
    """Is the filesystem based on bytes?"""
 
4361
 
 
4362
    def _probe(self):
 
4363
        if os.name == "posix":
 
4364
            return True
 
4365
        return False
 
4366
 
 
4367
ByteStringNamedFilesystem = _ByteStringNamedFilesystem()
 
4368
 
 
4369
 
3855
4370
class _UTF8Filesystem(Feature):
3856
4371
    """Is the filesystem UTF-8?"""
3857
4372
 
3863
4378
UTF8Filesystem = _UTF8Filesystem()
3864
4379
 
3865
4380
 
 
4381
class _BreakinFeature(Feature):
 
4382
    """Does this platform support the breakin feature?"""
 
4383
 
 
4384
    def _probe(self):
 
4385
        from bzrlib import breakin
 
4386
        if breakin.determine_signal() is None:
 
4387
            return False
 
4388
        if sys.platform == 'win32':
 
4389
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
 
4390
            # We trigger SIGBREAK via a Console api so we need ctypes to
 
4391
            # access the function
 
4392
            try:
 
4393
                import ctypes
 
4394
            except OSError:
 
4395
                return False
 
4396
        return True
 
4397
 
 
4398
    def feature_name(self):
 
4399
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
 
4400
 
 
4401
 
 
4402
BreakinFeature = _BreakinFeature()
 
4403
 
 
4404
 
3866
4405
class _CaseInsCasePresFilenameFeature(Feature):
3867
4406
    """Is the file-system case insensitive, but case-preserving?"""
3868
4407
 
3918
4457
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
3919
4458
 
3920
4459
 
3921
 
class _SubUnitFeature(Feature):
3922
 
    """Check if subunit is available."""
 
4460
class _CaseSensitiveFilesystemFeature(Feature):
3923
4461
 
3924
4462
    def _probe(self):
3925
 
        try:
3926
 
            import subunit
 
4463
        if CaseInsCasePresFilenameFeature.available():
 
4464
            return False
 
4465
        elif CaseInsensitiveFilesystemFeature.available():
 
4466
            return False
 
4467
        else:
3927
4468
            return True
3928
 
        except ImportError:
3929
 
            return False
3930
4469
 
3931
4470
    def feature_name(self):
3932
 
        return 'subunit'
3933
 
 
3934
 
SubUnitFeature = _SubUnitFeature()
 
4471
        return 'case-sensitive filesystem'
 
4472
 
 
4473
# new coding style is for feature instances to be lowercase
 
4474
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
 
4475
 
 
4476
 
 
4477
# Kept for compatibility, use bzrlib.tests.features.subunit instead
 
4478
SubUnitFeature = _CompatabilityThunkFeature(
 
4479
    deprecated_in((2,1,0)),
 
4480
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
3935
4481
# Only define SubUnitBzrRunner if subunit is available.
3936
4482
try:
3937
4483
    from subunit import TestProtocolClient
 
4484
    from subunit.test_results import AutoTimingTestResultDecorator
3938
4485
    class SubUnitBzrRunner(TextTestRunner):
3939
4486
        def run(self, test):
3940
 
            result = TestProtocolClient(self.stream)
 
4487
            result = AutoTimingTestResultDecorator(
 
4488
                TestProtocolClient(self.stream))
3941
4489
            test.run(result)
3942
4490
            return result
3943
4491
except ImportError:
3944
4492
    pass
 
4493
 
 
4494
class _PosixPermissionsFeature(Feature):
 
4495
 
 
4496
    def _probe(self):
 
4497
        def has_perms():
 
4498
            # create temporary file and check if specified perms are maintained.
 
4499
            import tempfile
 
4500
 
 
4501
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
 
4502
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
 
4503
            fd, name = f
 
4504
            os.close(fd)
 
4505
            os.chmod(name, write_perms)
 
4506
 
 
4507
            read_perms = os.stat(name).st_mode & 0777
 
4508
            os.unlink(name)
 
4509
            return (write_perms == read_perms)
 
4510
 
 
4511
        return (os.name == 'posix') and has_perms()
 
4512
 
 
4513
    def feature_name(self):
 
4514
        return 'POSIX permissions support'
 
4515
 
 
4516
posix_permissions_feature = _PosixPermissionsFeature()