~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Martin Pool
  • Date: 2010-08-13 08:09:53 UTC
  • mto: (5050.17.6 2.2)
  • mto: This revision was merged to the branch mainline in revision 5379.
  • Revision ID: mbp@sourcefrog.net-20100813080953-c00cm9l3qgu2flj9
Remove spuriously-resurrected test

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,
62
74
    ui,
63
75
    urlutils,
64
76
    registry,
 
77
    transport as _mod_transport,
65
78
    workingtree,
66
79
    )
67
80
import bzrlib.branch
85
98
from bzrlib.symbol_versioning import (
86
99
    DEPRECATED_PARAMETER,
87
100
    deprecated_function,
 
101
    deprecated_in,
88
102
    deprecated_method,
89
103
    deprecated_passed,
90
104
    )
91
105
import bzrlib.trace
92
 
from bzrlib.transport import get_transport
93
 
import bzrlib.transport
94
 
from bzrlib.transport.local import LocalURLServer
95
 
from bzrlib.transport.memory import MemoryServer
96
 
from bzrlib.transport.readonly import ReadonlyServer
 
106
from bzrlib.transport import (
 
107
    memory,
 
108
    pathfilter,
 
109
    )
97
110
from bzrlib.trace import mutter, note
98
 
from bzrlib.tests import TestUtil
 
111
from bzrlib.tests import (
 
112
    test_server,
 
113
    TestUtil,
 
114
    treeshape,
 
115
    )
99
116
from bzrlib.tests.http_server import HttpServer
100
117
from bzrlib.tests.TestUtil import (
101
118
                          TestSuite,
102
119
                          TestLoader,
103
120
                          )
104
 
from bzrlib.tests.treeshape import build_tree_contents
105
121
from bzrlib.ui import NullProgressView
106
122
from bzrlib.ui.text import TextUIFactory
107
123
import bzrlib.version_info_formats.format_custom
112
128
# shown frame is the test code, not our assertXYZ.
113
129
__unittest = 1
114
130
 
115
 
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
 
116
137
 
117
138
# Subunit result codes, defined here to prevent a hard dependency on subunit.
118
139
SUBUNIT_SEEK_SET = 0
174
195
        self._overall_start_time = time.time()
175
196
        self._strict = strict
176
197
 
177
 
    def done(self):
178
 
        # nb: called stopTestRun in the version of this that Python merged
179
 
        # upstream, according to lifeless 20090803
 
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))
180
235
        if self._strict:
181
236
            ok = self.wasStrictlySuccessful()
182
237
        else:
183
238
            ok = self.wasSuccessful()
184
 
        if ok:
185
 
            self.stream.write('tests passed\n')
186
 
        else:
187
 
            self.stream.write('tests failed\n')
188
239
        if TestCase._first_thread_leaker_id:
189
240
            self.stream.write(
190
241
                '%s is leaking threads among %d leaking tests.\n' % (
191
242
                TestCase._first_thread_leaker_id,
192
243
                TestCase._leaking_threads_tests))
193
 
 
194
 
    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):
195
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()))
196
256
        return getattr(testCase, "_benchtime", None)
197
257
 
198
258
    def _elapsedTestTimeString(self):
214
274
 
215
275
    def _shortened_test_description(self, test):
216
276
        what = test.id()
217
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
277
        what = re.sub(r'^bzrlib\.tests\.', '', what)
218
278
        return what
219
279
 
220
280
    def startTest(self, test):
226
286
        self._recordTestStartTime()
227
287
 
228
288
    def startTests(self):
229
 
        self.stream.write(
230
 
            'testing: %s\n' % (osutils.realpath(sys.argv[0]),))
231
 
        self.stream.write(
232
 
            '   %s (%s python%s)\n' % (
233
 
                    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' % (
234
301
                    bzrlib.version_string,
235
302
                    bzrlib._format_version_tuple(sys.version_info),
 
303
                    platform.platform(aliased=1),
236
304
                    ))
237
305
        self.stream.write('\n')
238
306
 
253
321
        Called from the TestCase run() method when the test
254
322
        fails with an unexpected error.
255
323
        """
256
 
        self._testConcluded(test)
257
 
        if isinstance(err[1], TestNotApplicable):
258
 
            return self._addNotApplicable(test, err)
259
 
        elif isinstance(err[1], UnavailableFeature):
260
 
            return self.addNotSupported(test, err[1].args[0])
261
 
        else:
262
 
            unittest.TestResult.addError(self, test, err)
263
 
            self.error_count += 1
264
 
            self.report_error(test, err)
265
 
            if self.stop_early:
266
 
                self.stop()
267
 
            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)
268
331
 
269
332
    def addFailure(self, test, err):
270
333
        """Tell result that test failed.
272
335
        Called from the TestCase run() method when the test
273
336
        fails because e.g. an assert() method failed.
274
337
        """
275
 
        self._testConcluded(test)
276
 
        if isinstance(err[1], KnownFailure):
277
 
            return self._addKnownFailure(test, err)
278
 
        else:
279
 
            unittest.TestResult.addFailure(self, test, err)
280
 
            self.failure_count += 1
281
 
            self.report_failure(test, err)
282
 
            if self.stop_early:
283
 
                self.stop()
284
 
            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)
285
345
 
286
 
    def addSuccess(self, test):
 
346
    def addSuccess(self, test, details=None):
287
347
        """Tell result that test completed successfully.
288
348
 
289
349
        Called from the TestCase run()
290
350
        """
291
 
        self._testConcluded(test)
292
351
        if self._bench_history is not None:
293
 
            benchmark_time = self._extractBenchmarkTime(test)
 
352
            benchmark_time = self._extractBenchmarkTime(test, details)
294
353
            if benchmark_time is not None:
295
354
                self._bench_history.write("%s %s\n" % (
296
355
                    self._formatTime(benchmark_time),
300
359
        unittest.TestResult.addSuccess(self, test)
301
360
        test._log_contents = ''
302
361
 
303
 
    def _testConcluded(self, test):
304
 
        """Common code when a test has finished.
305
 
 
306
 
        Called regardless of whether it succeded, failed, etc.
307
 
        """
308
 
        pass
309
 
 
310
 
    def _addKnownFailure(self, test, err):
 
362
    def addExpectedFailure(self, test, err):
311
363
        self.known_failure_count += 1
312
364
        self.report_known_failure(test, err)
313
365
 
315
367
        """The test will not be run because of a missing feature.
316
368
        """
317
369
        # this can be called in two different ways: it may be that the
318
 
        # test started running, and then raised (through addError)
 
370
        # test started running, and then raised (through requireFeature)
319
371
        # UnavailableFeature.  Alternatively this method can be called
320
 
        # while probing for features before running the tests; in that
321
 
        # case we will see startTest and stopTest, but the test will never
322
 
        # 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.
323
375
        self.unsupported.setdefault(str(feature), 0)
324
376
        self.unsupported[str(feature)] += 1
325
377
        self.report_unsupported(test, feature)
329
381
        self.skip_count += 1
330
382
        self.report_skip(test, reason)
331
383
 
332
 
    def _addNotApplicable(self, test, skip_excinfo):
333
 
        if isinstance(skip_excinfo[1], TestNotApplicable):
334
 
            self.not_applicable_count += 1
335
 
            self.report_not_applicable(test, skip_excinfo)
336
 
        try:
337
 
            test.tearDown()
338
 
        except KeyboardInterrupt:
339
 
            raise
340
 
        except:
341
 
            self.addError(test, test.exc_info())
342
 
        else:
343
 
            # seems best to treat this as success from point-of-view of unittest
344
 
            # -- it actually does nothing so it barely matters :)
345
 
            unittest.TestResult.addSuccess(self, test)
346
 
            test._log_contents = ''
 
384
    def addNotApplicable(self, test, reason):
 
385
        self.not_applicable_count += 1
 
386
        self.report_not_applicable(test, reason)
347
387
 
348
 
    def printErrorList(self, flavour, errors):
349
 
        for test, err in errors:
350
 
            self.stream.writeln(self.separator1)
351
 
            self.stream.write("%s: " % flavour)
352
 
            self.stream.writeln(self.getDescription(test))
353
 
            if getattr(test, '_get_log', None) is not None:
354
 
                log_contents = test._get_log()
355
 
                if log_contents:
356
 
                    self.stream.write('\n')
357
 
                    self.stream.write(
358
 
                            ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
359
 
                    self.stream.write('\n')
360
 
                    self.stream.write(log_contents)
361
 
                    self.stream.write('\n')
362
 
                    self.stream.write(
363
 
                            ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
364
 
                    self.stream.write('\n')
365
 
            self.stream.writeln(self.separator2)
366
 
            self.stream.writeln("%s" % err)
 
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()
367
392
 
368
393
    def progress(self, offset, whence):
369
394
        """The test is adjusting the count of tests to run."""
374
399
        else:
375
400
            raise errors.BzrError("Unknown whence %r" % whence)
376
401
 
377
 
    def finished(self):
378
 
        pass
379
 
 
380
402
    def report_cleaning_up(self):
381
403
        pass
382
404
 
 
405
    def startTestRun(self):
 
406
        self.startTime = time.time()
 
407
 
383
408
    def report_success(self, test):
384
409
        pass
385
410
 
412
437
        self.pb.update_latency = 0
413
438
        self.pb.show_transport_activity = False
414
439
 
415
 
    def done(self):
 
440
    def stopTestRun(self):
416
441
        # called when the tests that are going to run have run
417
442
        self.pb.clear()
418
 
        super(TextTestResult, self).done()
419
 
 
420
 
    def finished(self):
421
443
        self.pb.finished()
 
444
        super(TextTestResult, self).stopTestRun()
422
445
 
423
 
    def report_starting(self):
 
446
    def startTestRun(self):
 
447
        super(TextTestResult, self).startTestRun()
424
448
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
425
449
 
426
450
    def printErrors(self):
446
470
            a += '%dm%ds' % (runtime / 60, runtime % 60)
447
471
        else:
448
472
            a += '%ds' % runtime
449
 
        if self.error_count:
450
 
            a += ', %d err' % self.error_count
451
 
        if self.failure_count:
452
 
            a += ', %d fail' % self.failure_count
453
 
        if self.unsupported:
454
 
            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)
455
478
        a += ']'
456
479
        return a
457
480
 
466
489
        return self._shortened_test_description(test)
467
490
 
468
491
    def report_error(self, test, err):
469
 
        self.pb.note('ERROR: %s\n    %s\n',
 
492
        self.stream.write('ERROR: %s\n    %s\n' % (
470
493
            self._test_description(test),
471
494
            err[1],
472
 
            )
 
495
            ))
473
496
 
474
497
    def report_failure(self, test, err):
475
 
        self.pb.note('FAIL: %s\n    %s\n',
 
498
        self.stream.write('FAIL: %s\n    %s\n' % (
476
499
            self._test_description(test),
477
500
            err[1],
478
 
            )
 
501
            ))
479
502
 
480
503
    def report_known_failure(self, test, err):
481
 
        self.pb.note('XFAIL: %s\n%s\n',
482
 
            self._test_description(test), err[1])
 
504
        pass
483
505
 
484
506
    def report_skip(self, test, reason):
485
507
        pass
486
508
 
487
 
    def report_not_applicable(self, test, skip_excinfo):
 
509
    def report_not_applicable(self, test, reason):
488
510
        pass
489
511
 
490
512
    def report_unsupported(self, test, feature):
505
527
            result = a_string
506
528
        return result.ljust(final_width)
507
529
 
508
 
    def report_starting(self):
 
530
    def startTestRun(self):
 
531
        super(VerboseTestResult, self).startTestRun()
509
532
        self.stream.write('running %d tests...\n' % self.num_tests)
510
533
 
511
534
    def report_test_start(self, test):
512
535
        self.count += 1
513
536
        name = self._shortened_test_description(test)
514
 
        # width needs space for 6 char status, plus 1 for slash, plus an
515
 
        # 11-char time string, plus a trailing blank
516
 
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
517
 
        self.stream.write(self._ellipsize_to_right(name,
518
 
                          osutils.terminal_width()-18))
 
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)
519
546
        self.stream.flush()
520
547
 
521
548
    def _error_summary(self, err):
550
577
        self.stream.writeln(' SKIP %s\n%s'
551
578
                % (self._testTimeString(test), reason))
552
579
 
553
 
    def report_not_applicable(self, test, skip_excinfo):
554
 
        self.stream.writeln('  N/A %s\n%s'
555
 
                % (self._testTimeString(test),
556
 
                   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))
557
583
 
558
584
    def report_unsupported(self, test, feature):
559
585
        """test cannot be run because feature is missing."""
569
595
                 descriptions=0,
570
596
                 verbosity=1,
571
597
                 bench_history=None,
572
 
                 list_only=False,
573
598
                 strict=False,
 
599
                 result_decorators=None,
574
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
575
621
        self.stream = unittest._WritelnDecorator(stream)
576
622
        self.descriptions = descriptions
577
623
        self.verbosity = verbosity
578
624
        self._bench_history = bench_history
579
 
        self.list_only = list_only
580
625
        self._strict = strict
 
626
        self._result_decorators = result_decorators or []
581
627
 
582
628
    def run(self, test):
583
629
        "Run the given test case or test suite."
584
 
        startTime = time.time()
585
630
        if self.verbosity == 1:
586
631
            result_class = TextTestResult
587
632
        elif self.verbosity >= 2:
588
633
            result_class = VerboseTestResult
589
 
        result = result_class(self.stream,
 
634
        original_result = result_class(self.stream,
590
635
                              self.descriptions,
591
636
                              self.verbosity,
592
637
                              bench_history=self._bench_history,
593
638
                              strict=self._strict,
594
639
                              )
595
 
        result.stop_early = self.stop_on_failure
596
 
        result.report_starting()
597
 
        if self.list_only:
598
 
            if self.verbosity >= 2:
599
 
                self.stream.writeln("Listing tests only ...\n")
600
 
            run = 0
601
 
            for t in iter_suite_tests(test):
602
 
                self.stream.writeln("%s" % (t.id()))
603
 
                run += 1
604
 
            return None
605
 
        else:
606
 
            try:
607
 
                import testtools
608
 
            except ImportError:
609
 
                test.run(result)
610
 
            else:
611
 
                if isinstance(test, testtools.ConcurrentTestSuite):
612
 
                    # We need to catch bzr specific behaviors
613
 
                    test.run(BZRTransformingResult(result))
614
 
                else:
615
 
                    test.run(result)
616
 
            run = result.testsRun
617
 
            actionTaken = "Ran"
618
 
        stopTime = time.time()
619
 
        timeTaken = stopTime - startTime
620
 
        result.printErrors()
621
 
        self.stream.writeln(result.separator2)
622
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
623
 
                            run, run != 1 and "s" or "", timeTaken))
624
 
        self.stream.writeln()
625
 
        if not result.wasSuccessful():
626
 
            self.stream.write("FAILED (")
627
 
            failed, errored = map(len, (result.failures, result.errors))
628
 
            if failed:
629
 
                self.stream.write("failures=%d" % failed)
630
 
            if errored:
631
 
                if failed: self.stream.write(", ")
632
 
                self.stream.write("errors=%d" % errored)
633
 
            if result.known_failure_count:
634
 
                if failed or errored: self.stream.write(", ")
635
 
                self.stream.write("known_failure_count=%d" %
636
 
                    result.known_failure_count)
637
 
            self.stream.writeln(")")
638
 
        else:
639
 
            if result.known_failure_count:
640
 
                self.stream.writeln("OK (known_failures=%d)" %
641
 
                    result.known_failure_count)
642
 
            else:
643
 
                self.stream.writeln("OK")
644
 
        if result.skip_count > 0:
645
 
            skipped = result.skip_count
646
 
            self.stream.writeln('%d test%s skipped' %
647
 
                                (skipped, skipped != 1 and "s" or ""))
648
 
        if result.unsupported:
649
 
            for feature, count in sorted(result.unsupported.items()):
650
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
651
 
                    (feature, count))
652
 
        result.finished()
653
 
        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
654
654
 
655
655
 
656
656
def iter_suite_tests(suite):
666
666
                        % (type(suite), suite))
667
667
 
668
668
 
669
 
class TestSkipped(Exception):
670
 
    """Indicates that a test was intentionally skipped, rather than failing."""
 
669
TestSkipped = testtools.testcase.TestSkipped
671
670
 
672
671
 
673
672
class TestNotApplicable(TestSkipped):
679
678
    """
680
679
 
681
680
 
682
 
class KnownFailure(AssertionError):
683
 
    """Indicates that a test failed in a precisely expected manner.
684
 
 
685
 
    Such failures dont block the whole test suite from passing because they are
686
 
    indicators of partially completed code or of future work. We have an
687
 
    explicit error for them so that we can ensure that they are always visible:
688
 
    KnownFailures are always shown in the output of bzr selftest.
689
 
    """
 
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
690
698
 
691
699
 
692
700
class UnavailableFeature(Exception):
693
701
    """A feature required for this test was not available.
694
702
 
 
703
    This can be considered a specialised form of SkippedTest.
 
704
 
695
705
    The feature should be used to construct the exception.
696
706
    """
697
707
 
698
708
 
699
 
class CommandFailed(Exception):
700
 
    pass
701
 
 
702
 
 
703
709
class StringIOWrapper(object):
704
710
    """A wrapper around cStringIO which just adds an encoding attribute.
705
711
 
742
748
    # XXX: Should probably unify more with CannedInputUIFactory or a
743
749
    # particular configuration of TextUIFactory, or otherwise have a clearer
744
750
    # idea of how they're supposed to be different.
745
 
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
 
751
    # See https://bugs.launchpad.net/bzr/+bug/408213
746
752
 
747
753
    def __init__(self, stdout=None, stderr=None, stdin=None):
748
754
        if stdin is not None:
766
772
        return NullProgressView()
767
773
 
768
774
 
769
 
class TestCase(unittest.TestCase):
 
775
class TestCase(testtools.TestCase):
770
776
    """Base class for bzr unit tests.
771
777
 
772
778
    Tests that need access to disk resources should subclass
791
797
    _leaking_threads_tests = 0
792
798
    _first_thread_leaker_id = None
793
799
    _log_file_name = None
794
 
    _log_contents = ''
795
 
    _keep_log_file = False
796
800
    # record lsprof data when performing benchmark calls.
797
801
    _gather_lsprof_in_benchmarks = False
798
 
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
799
 
                     '_log_contents', '_log_file_name', '_benchtime',
800
 
                     '_TestCase__testMethodName', '_TestCase__testMethodDoc',)
801
802
 
802
803
    def __init__(self, methodName='testMethod'):
803
804
        super(TestCase, self).__init__(methodName)
804
805
        self._cleanups = []
805
 
        self._bzr_test_setUp_run = False
806
 
        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))
807
811
 
808
812
    def setUp(self):
809
 
        unittest.TestCase.setUp(self)
810
 
        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)]))
811
820
        self._cleanEnvironment()
812
821
        self._silenceUI()
813
822
        self._startLogFile()
814
823
        self._benchcalls = []
815
824
        self._benchtime = None
816
825
        self._clear_hooks()
817
 
        # Track locks - needs to be called before _clear_debug_flags.
 
826
        self._track_transports()
818
827
        self._track_locks()
819
828
        self._clear_debug_flags()
820
829
        TestCase._active_threads = threading.activeCount()
829
838
        active = threading.activeCount()
830
839
        leaked_threads = active - TestCase._active_threads
831
840
        TestCase._active_threads = active
832
 
        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:
833
848
            TestCase._leaking_threads_tests += 1
834
849
            if TestCase._first_thread_leaker_id is None:
835
850
                TestCase._first_thread_leaker_id = self.id()
840
855
        Tests that want to use debug flags can just set them in the
841
856
        debug_flags set during setup/teardown.
842
857
        """
843
 
        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))
844
860
        if 'allow_debug' not in selftest_debug_flags:
845
861
            debug.debug_flags.clear()
846
 
        self.addCleanup(self._restore_debug_flags)
 
862
        if 'disable_lock_checks' not in selftest_debug_flags:
 
863
            debug.debug_flags.add('strict_locks')
847
864
 
848
865
    def _clear_hooks(self):
849
866
        # prevent hooks affecting tests
859
876
        # this hook should always be installed
860
877
        request._install_hook()
861
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
 
862
887
    def _silenceUI(self):
863
888
        """Turn off UI for duration of test"""
864
889
        # by default the UI is off; tests can turn it on if they want it.
865
 
        saved = ui.ui_factory
866
 
        def _restore():
867
 
            ui.ui_factory = saved
868
 
        ui.ui_factory = ui.SilentUIFactory()
869
 
        self.addCleanup(_restore)
 
890
        self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
870
891
 
871
892
    def _check_locks(self):
872
893
        """Check that all lock take/release actions have been paired."""
873
 
        # once we have fixed all the current lock problems, we can change the
874
 
        # following code to always check for mismatched locks, but only do
875
 
        # traceback showing with -Dlock (self._lock_check_thorough is True).
876
 
        # For now, because the test suite will fail, we only assert that lock
877
 
        # matching has occured with -Dlock.
 
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.
878
897
        # unhook:
879
898
        acquired_locks = [lock for action, lock in self._lock_actions
880
899
                          if action == 'acquired']
899
918
    def _track_locks(self):
900
919
        """Track lock activity during tests."""
901
920
        self._lock_actions = []
902
 
        self._lock_check_thorough = 'lock' not in debug.debug_flags
 
921
        if 'disable_lock_checks' in selftest_debug_flags:
 
922
            self._lock_check_thorough = False
 
923
        else:
 
924
            self._lock_check_thorough = True
 
925
 
903
926
        self.addCleanup(self._check_locks)
904
927
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
905
928
                                                self._lock_acquired, None)
917
940
    def _lock_broken(self, result):
918
941
        self._lock_actions.append(('broken', result))
919
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.")
 
1069
 
920
1070
    def _ndiff_strings(self, a, b):
921
1071
        """Return ndiff between two strings containing lines.
922
1072
 
944
1094
            message += '\n'
945
1095
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
946
1096
            % (message,
947
 
               pformat(a), pformat(b)))
 
1097
               pprint.pformat(a), pprint.pformat(b)))
948
1098
 
949
1099
    assertEquals = assertEqual
950
1100
 
959
1109
            return
960
1110
        if message is None:
961
1111
            message = "texts not equal:\n"
 
1112
        if a + '\n' == b:
 
1113
            message = 'first string is missing a final newline.\n'
962
1114
        if a == b + '\n':
963
 
            message = 'first string is missing a final newline.\n'
964
 
        if a + '\n' == b:
965
1115
            message = 'second string is missing a final newline.\n'
966
1116
        raise AssertionError(message +
967
1117
                             self._ndiff_strings(a, b))
978
1128
        :raises AssertionError: If the expected and actual stat values differ
979
1129
            other than by atime.
980
1130
        """
981
 
        self.assertEqual(expected.st_size, actual.st_size)
982
 
        self.assertEqual(expected.st_mtime, actual.st_mtime)
983
 
        self.assertEqual(expected.st_ctime, actual.st_ctime)
984
 
        self.assertEqual(expected.st_dev, actual.st_dev)
985
 
        self.assertEqual(expected.st_ino, actual.st_ino)
986
 
        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')
987
1148
 
988
1149
    def assertLength(self, length, obj_with_len):
989
1150
        """Assert that obj_with_len is of length length."""
991
1152
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
992
1153
                length, len(obj_with_len), obj_with_len))
993
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
 
994
1174
    def assertPositive(self, val):
995
1175
        """Assert that val is greater than 0."""
996
1176
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
1026
1206
            raise AssertionError('pattern "%s" found in "%s"'
1027
1207
                    % (needle_re, haystack))
1028
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
 
1029
1213
    def assertSubset(self, sublist, superlist):
1030
1214
        """Assert that every entry in sublist is present in superlist."""
1031
1215
        missing = set(sublist) - set(superlist)
1118
1302
                m += ": " + msg
1119
1303
            self.fail(m)
1120
1304
 
1121
 
    def expectFailure(self, reason, assertion, *args, **kwargs):
1122
 
        """Invoke a test, expecting it to fail for the given reason.
1123
 
 
1124
 
        This is for assertions that ought to succeed, but currently fail.
1125
 
        (The failure is *expected* but not *wanted*.)  Please be very precise
1126
 
        about the failure you're expecting.  If a new bug is introduced,
1127
 
        AssertionError should be raised, not KnownFailure.
1128
 
 
1129
 
        Frequently, expectFailure should be followed by an opposite assertion.
1130
 
        See example below.
1131
 
 
1132
 
        Intended to be used with a callable that raises AssertionError as the
1133
 
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
1134
 
 
1135
 
        Raises KnownFailure if the test fails.  Raises AssertionError if the
1136
 
        test succeeds.
1137
 
 
1138
 
        example usage::
1139
 
 
1140
 
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
1141
 
                             dynamic_val)
1142
 
          self.assertEqual(42, dynamic_val)
1143
 
 
1144
 
          This means that a dynamic_val of 54 will cause the test to raise
1145
 
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
1146
 
          only a dynamic_val of 42 will allow the test to pass.  Anything other
1147
 
          than 54 or 42 will cause an AssertionError.
1148
 
        """
1149
 
        try:
1150
 
            assertion(*args, **kwargs)
1151
 
        except AssertionError:
1152
 
            raise KnownFailure(reason)
1153
 
        else:
1154
 
            self.fail('Unexpected success.  Should have failed: %s' % reason)
1155
 
 
1156
1305
    def assertFileEqual(self, content, path):
1157
1306
        """Fail if path does not contain 'content'."""
1158
1307
        self.failUnlessExists(path)
1163
1312
            f.close()
1164
1313
        self.assertEqualDiff(content, s)
1165
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
 
1166
1323
    def failUnlessExists(self, path):
1167
1324
        """Fail unless path or paths, which may be abs or relative, exist."""
1168
1325
        if not isinstance(path, basestring):
1308
1465
 
1309
1466
        Close the file and delete it, unless setKeepLogfile was called.
1310
1467
        """
1311
 
        if self._log_file is None:
1312
 
            return
 
1468
        if bzrlib.trace._trace_file:
 
1469
            # flush the log file, to get all content
 
1470
            bzrlib.trace._trace_file.flush()
1313
1471
        bzrlib.trace.pop_log_file(self._log_memento)
1314
 
        self._log_file.close()
1315
 
        self._log_file = None
1316
 
        if not self._keep_log_file:
1317
 
            os.remove(self._log_file_name)
1318
 
            self._log_file_name = None
1319
 
 
1320
 
    def setKeepLogfile(self):
1321
 
        """Make the logfile not be deleted when _finishLogFile is called."""
1322
 
        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')
1323
1487
 
1324
1488
    def addCleanup(self, callable, *args, **kwargs):
1325
1489
        """Arrange to run a callable when this case is torn down.
1329
1493
        """
1330
1494
        self._cleanups.append((callable, args, kwargs))
1331
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
 
1332
1515
    def _cleanEnvironment(self):
1333
1516
        new_env = {
1334
1517
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1340
1523
            'EDITOR': None,
1341
1524
            'BZR_EMAIL': None,
1342
1525
            'BZREMAIL': None, # may still be present in the environment
1343
 
            'EMAIL': None,
 
1526
            'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
1344
1527
            'BZR_PROGRESS_BAR': None,
1345
1528
            'BZR_LOG': None,
1346
1529
            'BZR_PLUGIN_PATH': None,
 
1530
            'BZR_DISABLE_PLUGINS': None,
 
1531
            'BZR_PLUGINS_AT': None,
 
1532
            'BZR_CONCURRENCY': None,
1347
1533
            # Make sure that any text ui tests are consistent regardless of
1348
1534
            # the environment the test case is run in; you may want tests that
1349
1535
            # test other combinations.  'dumb' is a reasonable guess for tests
1351
1537
            'TERM': 'dumb',
1352
1538
            'LINES': '25',
1353
1539
            'COLUMNS': '80',
 
1540
            'BZR_COLUMNS': '80',
1354
1541
            # SSH Agent
1355
1542
            'SSH_AUTH_SOCK': None,
1356
1543
            # Proxies
1368
1555
            'ftp_proxy': None,
1369
1556
            'FTP_PROXY': None,
1370
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',
1371
1563
        }
1372
 
        self.__old_env = {}
 
1564
        self._old_env = {}
1373
1565
        self.addCleanup(self._restoreEnvironment)
1374
1566
        for name, value in new_env.iteritems():
1375
1567
            self._captureVar(name, value)
1376
1568
 
1377
1569
    def _captureVar(self, name, newvalue):
1378
1570
        """Set an environment variable, and reset it when finished."""
1379
 
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1380
 
 
1381
 
    def _restore_debug_flags(self):
1382
 
        debug.debug_flags.clear()
1383
 
        debug.debug_flags.update(self._preserved_debug_flags)
 
1571
        self._old_env[name] = osutils.set_or_unset_env(name, newvalue)
1384
1572
 
1385
1573
    def _restoreEnvironment(self):
1386
 
        for name, value in self.__old_env.iteritems():
 
1574
        for name, value in self._old_env.iteritems():
1387
1575
            osutils.set_or_unset_env(name, value)
1388
1576
 
1389
1577
    def _restoreHooks(self):
1397
1585
    def _do_skip(self, result, reason):
1398
1586
        addSkip = getattr(result, 'addSkip', None)
1399
1587
        if not callable(addSkip):
1400
 
            result.addError(self, sys.exc_info())
 
1588
            result.addSuccess(result)
1401
1589
        else:
1402
1590
            addSkip(self, reason)
1403
1591
 
1404
 
    def run(self, result=None):
1405
 
        if result is None: result = self.defaultTestResult()
1406
 
        for feature in getattr(self, '_test_needs_features', []):
1407
 
            if not feature.available():
1408
 
                result.startTest(self)
1409
 
                if getattr(result, 'addNotSupported', None):
1410
 
                    result.addNotSupported(self, feature)
1411
 
                else:
1412
 
                    result.addSuccess(self)
1413
 
                result.stopTest(self)
1414
 
                return result
1415
 
        try:
1416
 
            try:
1417
 
                result.startTest(self)
1418
 
                absent_attr = object()
1419
 
                # Python 2.5
1420
 
                method_name = getattr(self, '_testMethodName', absent_attr)
1421
 
                if method_name is absent_attr:
1422
 
                    # Python 2.4
1423
 
                    method_name = getattr(self, '_TestCase__testMethodName')
1424
 
                testMethod = getattr(self, method_name)
1425
 
                try:
1426
 
                    try:
1427
 
                        self.setUp()
1428
 
                        if not self._bzr_test_setUp_run:
1429
 
                            self.fail(
1430
 
                                "test setUp did not invoke "
1431
 
                                "bzrlib.tests.TestCase's setUp")
1432
 
                    except KeyboardInterrupt:
1433
 
                        self._runCleanups()
1434
 
                        raise
1435
 
                    except TestSkipped, e:
1436
 
                        self._do_skip(result, e.args[0])
1437
 
                        self.tearDown()
1438
 
                        return result
1439
 
                    except:
1440
 
                        result.addError(self, sys.exc_info())
1441
 
                        self._runCleanups()
1442
 
                        return result
1443
 
 
1444
 
                    ok = False
1445
 
                    try:
1446
 
                        testMethod()
1447
 
                        ok = True
1448
 
                    except self.failureException:
1449
 
                        result.addFailure(self, sys.exc_info())
1450
 
                    except TestSkipped, e:
1451
 
                        if not e.args:
1452
 
                            reason = "No reason given."
1453
 
                        else:
1454
 
                            reason = e.args[0]
1455
 
                        self._do_skip(result, reason)
1456
 
                    except KeyboardInterrupt:
1457
 
                        self._runCleanups()
1458
 
                        raise
1459
 
                    except:
1460
 
                        result.addError(self, sys.exc_info())
1461
 
 
1462
 
                    try:
1463
 
                        self.tearDown()
1464
 
                        if not self._bzr_test_tearDown_run:
1465
 
                            self.fail(
1466
 
                                "test tearDown did not invoke "
1467
 
                                "bzrlib.tests.TestCase's tearDown")
1468
 
                    except KeyboardInterrupt:
1469
 
                        self._runCleanups()
1470
 
                        raise
1471
 
                    except:
1472
 
                        result.addError(self, sys.exc_info())
1473
 
                        self._runCleanups()
1474
 
                        ok = False
1475
 
                    if ok: result.addSuccess(self)
1476
 
                finally:
1477
 
                    result.stopTest(self)
1478
 
                return result
1479
 
            except TestNotApplicable:
1480
 
                # Not moved from the result [yet].
1481
 
                self._runCleanups()
1482
 
                raise
1483
 
            except KeyboardInterrupt:
1484
 
                self._runCleanups()
1485
 
                raise
1486
 
        finally:
1487
 
            saved_attrs = {}
1488
 
            for attr_name in self.attrs_to_keep:
1489
 
                if attr_name in self.__dict__:
1490
 
                    saved_attrs[attr_name] = self.__dict__[attr_name]
1491
 
            self.__dict__ = saved_attrs
1492
 
 
1493
 
    def tearDown(self):
1494
 
        self._runCleanups()
1495
 
        self._log_contents = ''
1496
 
        self._bzr_test_tearDown_run = True
1497
 
        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)
1498
1621
 
1499
1622
    def time(self, callable, *args, **kwargs):
1500
1623
        """Run callable and accrue the time it takes to the benchmark time.
1504
1627
        self._benchcalls.
1505
1628
        """
1506
1629
        if self._benchtime is None:
 
1630
            self.addDetail('benchtime', content.Content(content.ContentType(
 
1631
                "text", "plain"), lambda:[str(self._benchtime)]))
1507
1632
            self._benchtime = 0
1508
1633
        start = time.time()
1509
1634
        try:
1518
1643
        finally:
1519
1644
            self._benchtime += time.time() - start
1520
1645
 
1521
 
    def _runCleanups(self):
1522
 
        """Run registered cleanup functions.
1523
 
 
1524
 
        This should only be called from TestCase.tearDown.
1525
 
        """
1526
 
        # TODO: Perhaps this should keep running cleanups even if
1527
 
        # one of them fails?
1528
 
 
1529
 
        # Actually pop the cleanups from the list so tearDown running
1530
 
        # twice is safe (this happens for skipped tests).
1531
 
        while self._cleanups:
1532
 
            cleanup, args, kwargs = self._cleanups.pop()
1533
 
            cleanup(*args, **kwargs)
1534
 
 
1535
1646
    def log(self, *args):
1536
1647
        mutter(*args)
1537
1648
 
1538
1649
    def _get_log(self, keep_log_file=False):
1539
 
        """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.
1540
1654
 
1541
1655
        :param keep_log_file: When True, if the log is still a file on disk
1542
1656
            leave it as a file on disk. When False, if the log is still a file
1544
1658
            self._log_contents.
1545
1659
        :return: A string containing the log.
1546
1660
        """
1547
 
        # 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
1548
1668
        import bzrlib.trace
1549
1669
        if bzrlib.trace._trace_file:
 
1670
            # flush the log file, to get all content
1550
1671
            bzrlib.trace._trace_file.flush()
1551
 
        if self._log_contents:
1552
 
            # XXX: this can hardly contain the content flushed above --vila
1553
 
            # 20080128
1554
 
            return self._log_contents
1555
1672
        if self._log_file_name is not None:
1556
1673
            logfile = open(self._log_file_name)
1557
1674
            try:
1558
1675
                log_contents = logfile.read()
1559
1676
            finally:
1560
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')
1561
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
1562
1714
                self._log_contents = log_contents
1563
1715
                try:
1564
1716
                    os.remove(self._log_file_name)
1568
1720
                                             ' %r\n' % self._log_file_name))
1569
1721
                    else:
1570
1722
                        raise
 
1723
                self._log_file_name = None
1571
1724
            return log_contents
1572
1725
        else:
1573
 
            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())
1574
1734
 
1575
1735
    def requireFeature(self, feature):
1576
1736
        """This test requires a specific feature is available.
1593
1753
 
1594
1754
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1595
1755
            working_dir):
 
1756
        # Clear chk_map page cache, because the contents are likely to mask
 
1757
        # locking errors.
 
1758
        chk_map.clear_cache()
1596
1759
        if encoding is None:
1597
1760
            encoding = osutils.get_user_encoding()
1598
1761
        stdout = StringIOWrapper()
1615
1778
            os.chdir(working_dir)
1616
1779
 
1617
1780
        try:
1618
 
            result = self.apply_redirected(ui.ui_factory.stdin,
1619
 
                stdout, stderr,
1620
 
                bzrlib.commands.run_bzr_catch_user_errors,
1621
 
                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)
1622
1797
        finally:
1623
1798
            logger.removeHandler(handler)
1624
1799
            ui.ui_factory = old_ui_factory
1634
1809
        if retcode is not None:
1635
1810
            self.assertEquals(retcode, result,
1636
1811
                              message='Unexpected return code')
1637
 
        return out, err
 
1812
        return result, out, err
1638
1813
 
1639
1814
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1640
1815
                working_dir=None, error_regexes=[], output_encoding=None):
1669
1844
        :keyword error_regexes: A list of expected error messages.  If
1670
1845
            specified they must be seen in the error output of the command.
1671
1846
        """
1672
 
        out, err = self._run_bzr_autosplit(
 
1847
        retcode, out, err = self._run_bzr_autosplit(
1673
1848
            args=args,
1674
1849
            retcode=retcode,
1675
1850
            encoding=encoding,
1810
1985
            if not allow_plugins:
1811
1986
                command.append('--no-plugins')
1812
1987
            command.extend(process_args)
1813
 
            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)
1814
1991
        finally:
1815
1992
            restore_environment()
1816
1993
            if cwd is not None:
1824
2001
        Allows tests to override this method to intercept the calls made to
1825
2002
        Popen for introspection.
1826
2003
        """
1827
 
        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__))
1828
2009
 
1829
2010
    def get_bzr_path(self):
1830
2011
        """Return the path of the 'bzr' executable for this test suite."""
1831
 
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
2012
        bzr_path = self.get_source_path()+'/bzr'
1832
2013
        if not os.path.isfile(bzr_path):
1833
2014
            # We are probably installed. Assume sys.argv is the right file
1834
2015
            bzr_path = sys.argv[0]
1920
2101
 
1921
2102
        Tests that expect to provoke LockContention errors should call this.
1922
2103
        """
1923
 
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
1924
 
        def resetTimeout():
1925
 
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
1926
 
        self.addCleanup(resetTimeout)
1927
 
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
2104
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
1928
2105
 
1929
2106
    def make_utf8_encoded_stringio(self, encoding_type=None):
1930
2107
        """Return a StringIOWrapper instance, that will encode Unicode
1944
2121
        request_handlers = request.request_handlers
1945
2122
        orig_method = request_handlers.get(verb)
1946
2123
        request_handlers.remove(verb)
1947
 
        def restoreVerb():
1948
 
            request_handlers.register(verb, orig_method)
1949
 
        self.addCleanup(restoreVerb)
 
2124
        self.addCleanup(request_handlers.register, verb, orig_method)
1950
2125
 
1951
2126
 
1952
2127
class CapturedCall(object):
2012
2187
 
2013
2188
        :param relpath: a path relative to the base url.
2014
2189
        """
2015
 
        t = get_transport(self.get_url(relpath))
 
2190
        t = _mod_transport.get_transport(self.get_url(relpath))
2016
2191
        self.assertFalse(t.is_readonly())
2017
2192
        return t
2018
2193
 
2024
2199
 
2025
2200
        :param relpath: a path relative to the base url.
2026
2201
        """
2027
 
        t = get_transport(self.get_readonly_url(relpath))
 
2202
        t = _mod_transport.get_transport(self.get_readonly_url(relpath))
2028
2203
        self.assertTrue(t.is_readonly())
2029
2204
        return t
2030
2205
 
2043
2218
        if self.__readonly_server is None:
2044
2219
            if self.transport_readonly_server is None:
2045
2220
                # readonly decorator requested
2046
 
                # bring up the server
2047
 
                self.__readonly_server = ReadonlyServer()
2048
 
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
2221
                self.__readonly_server = test_server.ReadonlyServer()
2049
2222
            else:
 
2223
                # explicit readonly transport.
2050
2224
                self.__readonly_server = self.create_transport_readonly_server()
2051
 
                self.__readonly_server.setUp(self.get_vfs_only_server())
2052
 
            self.addCleanup(self.__readonly_server.tearDown)
 
2225
            self.start_server(self.__readonly_server,
 
2226
                self.get_vfs_only_server())
2053
2227
        return self.__readonly_server
2054
2228
 
2055
2229
    def get_readonly_url(self, relpath=None):
2073
2247
        is no means to override it.
2074
2248
        """
2075
2249
        if self.__vfs_server is None:
2076
 
            self.__vfs_server = MemoryServer()
2077
 
            self.__vfs_server.setUp()
2078
 
            self.addCleanup(self.__vfs_server.tearDown)
 
2250
            self.__vfs_server = memory.MemoryServer()
 
2251
            self.start_server(self.__vfs_server)
2079
2252
        return self.__vfs_server
2080
2253
 
2081
2254
    def get_server(self):
2088
2261
        then the self.get_vfs_server is returned.
2089
2262
        """
2090
2263
        if self.__server is None:
2091
 
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
2092
 
                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()
2093
2267
            else:
2094
2268
                # bring up a decorated means of access to the vfs only server.
2095
2269
                self.__server = self.transport_server()
2096
 
                try:
2097
 
                    self.__server.setUp(self.get_vfs_only_server())
2098
 
                except TypeError, e:
2099
 
                    # This should never happen; the try:Except here is to assist
2100
 
                    # developers having to update code rather than seeing an
2101
 
                    # uninformative TypeError.
2102
 
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
2103
 
            self.addCleanup(self.__server.tearDown)
 
2270
                self.start_server(self.__server, self.get_vfs_only_server())
2104
2271
        return self.__server
2105
2272
 
2106
2273
    def _adjust_url(self, base, relpath):
2168
2335
        propagating. This method ensures than a test did not leaked.
2169
2336
        """
2170
2337
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
2338
        self.permit_url(_mod_transport.get_transport(root).base)
2171
2339
        wt = workingtree.WorkingTree.open(root)
2172
2340
        last_rev = wt.last_revision()
2173
2341
        if last_rev != 'null:':
2175
2343
            # recreate a new one or all the followng tests will fail.
2176
2344
            # If you need to inspect its content uncomment the following line
2177
2345
            # import pdb; pdb.set_trace()
2178
 
            _rmtree_temp_dir(root + '/.bzr')
 
2346
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
2179
2347
            self._create_safety_net()
2180
2348
            raise AssertionError('%s/.bzr should not be modified' % root)
2181
2349
 
2182
2350
    def _make_test_root(self):
2183
2351
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
2184
 
            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'))
2185
2355
            TestCaseWithMemoryTransport.TEST_ROOT = root
2186
2356
 
2187
2357
            self._create_safety_net()
2190
2360
            # specifically told when all tests are finished.  This will do.
2191
2361
            atexit.register(_rmtree_temp_dir, root)
2192
2362
 
 
2363
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2193
2364
        self.addCleanup(self._check_safety_net)
2194
2365
 
2195
2366
    def makeAndChdirToTestDir(self):
2203
2374
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2204
2375
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2205
2376
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
 
2377
        self.permit_dir(self.test_dir)
2206
2378
 
2207
2379
    def make_branch(self, relpath, format=None):
2208
2380
        """Create a branch on the transport at relpath."""
2214
2386
            # might be a relative or absolute path
2215
2387
            maybe_a_url = self.get_url(relpath)
2216
2388
            segments = maybe_a_url.rsplit('/', 1)
2217
 
            t = get_transport(maybe_a_url)
 
2389
            t = _mod_transport.get_transport(maybe_a_url)
2218
2390
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2219
2391
                t.ensure_base()
2220
2392
            if format is None:
2237
2409
        made_control = self.make_bzrdir(relpath, format=format)
2238
2410
        return made_control.create_repository(shared=shared)
2239
2411
 
2240
 
    def make_smart_server(self, path):
2241
 
        smart_server = server.SmartTCPServer_for_testing()
2242
 
        smart_server.setUp(self.get_server())
2243
 
        remote_transport = get_transport(smart_server.get_url()).clone(path)
2244
 
        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)
2245
2419
        return remote_transport
2246
2420
 
2247
2421
    def make_branch_and_memory_tree(self, relpath, format=None):
2254
2428
        return branchbuilder.BranchBuilder(branch=branch)
2255
2429
 
2256
2430
    def overrideEnvironmentForTesting(self):
2257
 
        os.environ['HOME'] = self.test_home_dir
2258
 
        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
2259
2436
 
2260
2437
    def setUp(self):
2261
2438
        super(TestCaseWithMemoryTransport, self).setUp()
2262
2439
        self._make_test_root()
2263
 
        _currentdir = os.getcwdu()
2264
 
        def _leaveDirectory():
2265
 
            os.chdir(_currentdir)
2266
 
        self.addCleanup(_leaveDirectory)
 
2440
        self.addCleanup(os.chdir, os.getcwdu())
2267
2441
        self.makeAndChdirToTestDir()
2268
2442
        self.overrideEnvironmentForTesting()
2269
2443
        self.__readonly_server = None
2272
2446
 
2273
2447
    def setup_smart_server_with_call_log(self):
2274
2448
        """Sets up a smart server as the transport server with a call log."""
2275
 
        self.transport_server = server.SmartTCPServer_for_testing
 
2449
        self.transport_server = test_server.SmartTCPServer_for_testing
2276
2450
        self.hpss_calls = []
2277
2451
        import traceback
2278
2452
        # Skip the current stack down to the caller of
2312
2486
 
2313
2487
    def check_file_contents(self, filename, expect):
2314
2488
        self.log("check contents of file %s" % filename)
2315
 
        contents = file(filename, 'r').read()
 
2489
        f = file(filename)
 
2490
        try:
 
2491
            contents = f.read()
 
2492
        finally:
 
2493
            f.close()
2316
2494
        if contents != expect:
2317
2495
            self.log("expected: %r" % expect)
2318
2496
            self.log("actually: %r" % contents)
2320
2498
 
2321
2499
    def _getTestDirPrefix(self):
2322
2500
        # create a directory within the top level test directory
2323
 
        if sys.platform == 'win32':
 
2501
        if sys.platform in ('win32', 'cygwin'):
2324
2502
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2325
2503
            # windows is likely to have path-length limits so use a short name
2326
2504
            name_prefix = name_prefix[-30:]
2341
2519
            if os.path.exists(name):
2342
2520
                name = name_prefix + '_' + str(i)
2343
2521
            else:
2344
 
                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)
2345
2526
                break
2346
 
        # now create test and home directories within this dir
2347
 
        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()
2348
2534
        self.test_home_dir = self.test_base_dir + '/home'
2349
2535
        os.mkdir(self.test_home_dir)
2350
2536
        self.test_dir = self.test_base_dir + '/work'
2356
2542
            f.write(self.id())
2357
2543
        finally:
2358
2544
            f.close()
2359
 
        self.addCleanup(self.deleteTestDir)
2360
2545
 
2361
2546
    def deleteTestDir(self):
2362
2547
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2363
 
        _rmtree_temp_dir(self.test_base_dir)
 
2548
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
2364
2549
 
2365
2550
    def build_tree(self, shape, line_endings='binary', transport=None):
2366
2551
        """Build a test tree according to a pattern.
2385
2570
                "a list or a tuple. Got %r instead" % (shape,))
2386
2571
        # It's OK to just create them using forward slashes on windows.
2387
2572
        if transport is None or transport.is_readonly():
2388
 
            transport = get_transport(".")
 
2573
            transport = _mod_transport.get_transport(".")
2389
2574
        for name in shape:
2390
2575
            self.assertIsInstance(name, basestring)
2391
2576
            if name[-1] == '/':
2401
2586
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2402
2587
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2403
2588
 
2404
 
    def build_tree_contents(self, shape):
2405
 
        build_tree_contents(shape)
 
2589
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2406
2590
 
2407
2591
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2408
2592
        """Assert whether path or paths are in the WorkingTree"""
2448
2632
        """
2449
2633
        if self.__vfs_server is None:
2450
2634
            self.__vfs_server = self.vfs_transport_factory()
2451
 
            self.__vfs_server.setUp()
2452
 
            self.addCleanup(self.__vfs_server.tearDown)
 
2635
            self.start_server(self.__vfs_server)
2453
2636
        return self.__vfs_server
2454
2637
 
2455
2638
    def make_branch_and_tree(self, relpath, format=None):
2462
2645
        repository will also be accessed locally. Otherwise a lightweight
2463
2646
        checkout is created and returned.
2464
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
 
2465
2657
        :param format: The BzrDirFormat.
2466
2658
        :returns: the WorkingTree.
2467
2659
        """
2476
2668
            # We can only make working trees locally at the moment.  If the
2477
2669
            # transport can't support them, then we keep the non-disk-backed
2478
2670
            # branch and create a local checkout.
2479
 
            if self.vfs_transport_factory is LocalURLServer:
 
2671
            if self.vfs_transport_factory is test_server.LocalURLServer:
2480
2672
                # the branch is colocated on disk, we cannot create a checkout.
2481
2673
                # hopefully callers will expect this.
2482
2674
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2519
2711
        super(TestCaseWithTransport, self).setUp()
2520
2712
        self.__vfs_server = None
2521
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
 
2522
2722
 
2523
2723
class ChrootedTestCase(TestCaseWithTransport):
2524
2724
    """A support class that provides readonly urls outside the local namespace.
2534
2734
 
2535
2735
    def setUp(self):
2536
2736
        super(ChrootedTestCase, self).setUp()
2537
 
        if not self.vfs_transport_factory == MemoryServer:
 
2737
        if not self.vfs_transport_factory == memory.MemoryServer:
2538
2738
            self.transport_readonly_server = HttpServer
2539
2739
 
2540
2740
 
2544
2744
    :param pattern: A regular expression string.
2545
2745
    :return: A callable that returns True if the re matches.
2546
2746
    """
2547
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2548
 
        'test filter')
 
2747
    filter_re = re.compile(pattern, 0)
2549
2748
    def condition(test):
2550
2749
        test_id = test.id()
2551
2750
        return filter_re.search(test_id)
2738
2937
              strict=False,
2739
2938
              runner_class=None,
2740
2939
              suite_decorators=None,
2741
 
              stream=None):
 
2940
              stream=None,
 
2941
              result_decorators=None,
 
2942
              ):
2742
2943
    """Run a test suite for bzr selftest.
2743
2944
 
2744
2945
    :param runner_class: The class of runner to use. Must support the
2759
2960
                            descriptions=0,
2760
2961
                            verbosity=verbosity,
2761
2962
                            bench_history=bench_history,
2762
 
                            list_only=list_only,
2763
2963
                            strict=strict,
 
2964
                            result_decorators=result_decorators,
2764
2965
                            )
2765
2966
    runner.stop_on_failure=stop_on_failure
2766
2967
    # built in decorator factories:
2774
2975
        decorators.append(filter_tests(pattern))
2775
2976
    if suite_decorators:
2776
2977
        decorators.extend(suite_decorators)
2777
 
    # tell the result object how many tests will be running:
2778
 
    decorators.append(CountingDecorator)
 
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)
2779
2983
    for decorator in decorators:
2780
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
2781
2993
    result = runner.run(suite)
2782
 
    if list_only:
2783
 
        return True
2784
 
    result.done()
2785
2994
    if strict:
2786
2995
        return result.wasStrictlySuccessful()
2787
2996
    else:
2944
3153
        if self.randomised:
2945
3154
            return iter(self._tests)
2946
3155
        self.randomised = True
2947
 
        self.stream.writeln("Randomizing test order using seed %s\n" %
 
3156
        self.stream.write("Randomizing test order using seed %s\n\n" %
2948
3157
            (self.actual_seed()))
2949
3158
        # Initialise the random number generator.
2950
3159
        random.seed(self.actual_seed())
2998
3207
    return result
2999
3208
 
3000
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
 
3001
3223
def fork_for_tests(suite):
3002
3224
    """Take suite and start up one runner per CPU by forking()
3003
3225
 
3007
3229
    concurrency = osutils.local_concurrency()
3008
3230
    result = []
3009
3231
    from subunit import TestProtocolClient, ProtocolTestCase
3010
 
    try:
3011
 
        from subunit.test_results import AutoTimingTestResultDecorator
3012
 
    except ImportError:
3013
 
        AutoTimingTestResultDecorator = lambda x:x
 
3232
    from subunit.test_results import AutoTimingTestResultDecorator
3014
3233
    class TestInOtherProcess(ProtocolTestCase):
3015
3234
        # Should be in subunit, I think. RBC.
3016
3235
        def __init__(self, stream, pid):
3021
3240
            try:
3022
3241
                ProtocolTestCase.run(self, result)
3023
3242
            finally:
3024
 
                os.waitpid(self.pid, os.WNOHANG)
 
3243
                os.waitpid(self.pid, 0)
3025
3244
 
3026
3245
    test_blocks = partition_tests(suite, concurrency)
3027
3246
    for process_tests in test_blocks:
3030
3249
        c2pread, c2pwrite = os.pipe()
3031
3250
        pid = os.fork()
3032
3251
        if pid == 0:
 
3252
            workaround_zealous_crypto_random()
3033
3253
            try:
3034
3254
                os.close(c2pread)
3035
3255
                # Leave stderr and stdout open so we can see test noise
3082
3302
        if not os.path.isfile(bzr_path):
3083
3303
            # We are probably installed. Assume sys.argv is the right file
3084
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
3085
3309
        fd, test_list_file_name = tempfile.mkstemp()
3086
3310
        test_list_file = os.fdopen(fd, 'wb', 1)
3087
3311
        for test in process_tests:
3088
3312
            test_list_file.write(test.id() + '\n')
3089
3313
        test_list_file.close()
3090
3314
        try:
3091
 
            argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
 
3315
            argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
3092
3316
                '--subunit']
3093
3317
            if '--no-plugins' in sys.argv:
3094
3318
                argv.append('--no-plugins')
3095
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
3096
 
            # stderr it can interrupt the subunit protocol.
3097
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3098
 
                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)
3099
3325
            test = TestInSubprocess(process, test_list_file_name)
3100
3326
            result.append(test)
3101
3327
        except:
3104
3330
    return result
3105
3331
 
3106
3332
 
3107
 
class BZRTransformingResult(unittest.TestResult):
 
3333
class ForwardingResult(unittest.TestResult):
3108
3334
 
3109
3335
    def __init__(self, target):
3110
3336
        unittest.TestResult.__init__(self)
3116
3342
    def stopTest(self, test):
3117
3343
        self.result.stopTest(test)
3118
3344
 
3119
 
    def addError(self, test, err):
3120
 
        feature = self._error_looks_like('UnavailableFeature: ', err)
3121
 
        if feature is not None:
3122
 
            self.result.addNotSupported(test, feature)
3123
 
        else:
3124
 
            self.result.addError(test, err)
 
3345
    def startTestRun(self):
 
3346
        self.result.startTestRun()
3125
3347
 
3126
 
    def addFailure(self, test, err):
3127
 
        known = self._error_looks_like('KnownFailure: ', err)
3128
 
        if known is not None:
3129
 
            self.result._addKnownFailure(test, [KnownFailure,
3130
 
                                                KnownFailure(known), None])
3131
 
        else:
3132
 
            self.result.addFailure(test, err)
 
3348
    def stopTestRun(self):
 
3349
        self.result.stopTestRun()
3133
3350
 
3134
3351
    def addSkip(self, test, reason):
3135
3352
        self.result.addSkip(test, reason)
3137
3354
    def addSuccess(self, test):
3138
3355
        self.result.addSuccess(test)
3139
3356
 
3140
 
    def _error_looks_like(self, prefix, err):
3141
 
        """Deserialize exception and returns the stringify value."""
3142
 
        import subunit
3143
 
        value = None
3144
 
        typ, exc, _ = err
3145
 
        if isinstance(exc, subunit.RemoteException):
3146
 
            # stringify the exception gives access to the remote traceback
3147
 
            # We search the last line for 'prefix'
3148
 
            lines = str(exc).split('\n')
3149
 
            while lines and not lines[-1]:
3150
 
                lines.pop(-1)
3151
 
            if lines:
3152
 
                if lines[-1].startswith(prefix):
3153
 
                    value = lines[-1][len(prefix):]
3154
 
        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
3155
3398
 
3156
3399
 
3157
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.
3158
3408
selftest_debug_flags = set()
3159
3409
 
3160
3410
 
3173
3423
             starting_with=None,
3174
3424
             runner_class=None,
3175
3425
             suite_decorators=None,
 
3426
             stream=None,
 
3427
             lsprof_tests=False,
3176
3428
             ):
3177
3429
    """Run the whole test suite under the enhanced runner"""
3178
3430
    # XXX: Very ugly way to do this...
3195
3447
            keep_only = None
3196
3448
        else:
3197
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]
3198
3453
        if test_suite_factory is None:
 
3454
            # Reduce loading time by loading modules based on the starting_with
 
3455
            # patterns.
3199
3456
            suite = test_suite(keep_only, starting_with)
3200
3457
        else:
3201
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)
3202
3465
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3203
3466
                     stop_on_failure=stop_on_failure,
3204
3467
                     transport=transport,
3211
3474
                     strict=strict,
3212
3475
                     runner_class=runner_class,
3213
3476
                     suite_decorators=suite_decorators,
 
3477
                     stream=stream,
 
3478
                     result_decorators=result_decorators,
3214
3479
                     )
3215
3480
    finally:
3216
3481
        default_transport = old_transport
3364
3629
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3365
3630
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3366
3631
 
3367
 
# 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
3368
3633
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3369
3634
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3370
3635
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3372
3637
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3373
3638
 
3374
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_treeshape',
 
3817
        'bzrlib.tests.test_tsort',
 
3818
        'bzrlib.tests.test_tuned_gzip',
 
3819
        'bzrlib.tests.test_ui',
 
3820
        'bzrlib.tests.test_uncommit',
 
3821
        'bzrlib.tests.test_upgrade',
 
3822
        'bzrlib.tests.test_upgrade_stacked',
 
3823
        'bzrlib.tests.test_urlutils',
 
3824
        'bzrlib.tests.test_version',
 
3825
        'bzrlib.tests.test_version_info',
 
3826
        'bzrlib.tests.test_weave',
 
3827
        'bzrlib.tests.test_whitebox',
 
3828
        'bzrlib.tests.test_win32utils',
 
3829
        'bzrlib.tests.test_workingtree',
 
3830
        'bzrlib.tests.test_workingtree_4',
 
3831
        'bzrlib.tests.test_wsgi',
 
3832
        'bzrlib.tests.test_xml',
 
3833
        ]
 
3834
 
 
3835
 
 
3836
def _test_suite_modules_to_doctest():
 
3837
    """Return the list of modules to doctest."""
 
3838
    if __doc__ is None:
 
3839
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
 
3840
        return []
 
3841
    return [
 
3842
        'bzrlib',
 
3843
        'bzrlib.branchbuilder',
 
3844
        'bzrlib.decorators',
 
3845
        'bzrlib.export',
 
3846
        'bzrlib.inventory',
 
3847
        'bzrlib.iterablefile',
 
3848
        'bzrlib.lockdir',
 
3849
        'bzrlib.merge3',
 
3850
        'bzrlib.option',
 
3851
        'bzrlib.symbol_versioning',
 
3852
        'bzrlib.tests',
 
3853
        'bzrlib.tests.fixtures',
 
3854
        'bzrlib.timestamp',
 
3855
        'bzrlib.version_info_formats.format_custom',
 
3856
        ]
 
3857
 
 
3858
 
3375
3859
def test_suite(keep_only=None, starting_with=None):
3376
3860
    """Build and return TestSuite for the whole of bzrlib.
3377
3861
 
3383
3867
    This function can be replaced if you need to change the default test
3384
3868
    suite on a global basis, but it is not encouraged.
3385
3869
    """
3386
 
    testmod_names = [
3387
 
                   'bzrlib.doc',
3388
 
                   'bzrlib.tests.blackbox',
3389
 
                   'bzrlib.tests.commands',
3390
 
                   'bzrlib.tests.per_branch',
3391
 
                   'bzrlib.tests.per_bzrdir',
3392
 
                   'bzrlib.tests.per_interrepository',
3393
 
                   'bzrlib.tests.per_intertree',
3394
 
                   'bzrlib.tests.per_inventory',
3395
 
                   'bzrlib.tests.per_interbranch',
3396
 
                   'bzrlib.tests.per_lock',
3397
 
                   'bzrlib.tests.per_transport',
3398
 
                   'bzrlib.tests.per_tree',
3399
 
                   'bzrlib.tests.per_pack_repository',
3400
 
                   'bzrlib.tests.per_repository',
3401
 
                   'bzrlib.tests.per_repository_chk',
3402
 
                   'bzrlib.tests.per_repository_reference',
3403
 
                   'bzrlib.tests.per_workingtree',
3404
 
                   'bzrlib.tests.test__annotator',
3405
 
                   'bzrlib.tests.test__chk_map',
3406
 
                   'bzrlib.tests.test__dirstate_helpers',
3407
 
                   'bzrlib.tests.test__groupcompress',
3408
 
                   'bzrlib.tests.test__known_graph',
3409
 
                   'bzrlib.tests.test__rio',
3410
 
                   'bzrlib.tests.test__walkdirs_win32',
3411
 
                   'bzrlib.tests.test_ancestry',
3412
 
                   'bzrlib.tests.test_annotate',
3413
 
                   'bzrlib.tests.test_api',
3414
 
                   'bzrlib.tests.test_atomicfile',
3415
 
                   'bzrlib.tests.test_bad_files',
3416
 
                   'bzrlib.tests.test_bencode',
3417
 
                   'bzrlib.tests.test_bisect_multi',
3418
 
                   'bzrlib.tests.test_branch',
3419
 
                   'bzrlib.tests.test_branchbuilder',
3420
 
                   'bzrlib.tests.test_btree_index',
3421
 
                   'bzrlib.tests.test_bugtracker',
3422
 
                   'bzrlib.tests.test_bundle',
3423
 
                   'bzrlib.tests.test_bzrdir',
3424
 
                   'bzrlib.tests.test__chunks_to_lines',
3425
 
                   'bzrlib.tests.test_cache_utf8',
3426
 
                   'bzrlib.tests.test_chk_map',
3427
 
                   'bzrlib.tests.test_chk_serializer',
3428
 
                   'bzrlib.tests.test_chunk_writer',
3429
 
                   'bzrlib.tests.test_clean_tree',
3430
 
                   'bzrlib.tests.test_commands',
3431
 
                   'bzrlib.tests.test_commit',
3432
 
                   'bzrlib.tests.test_commit_merge',
3433
 
                   'bzrlib.tests.test_config',
3434
 
                   'bzrlib.tests.test_conflicts',
3435
 
                   'bzrlib.tests.test_counted_lock',
3436
 
                   'bzrlib.tests.test_decorators',
3437
 
                   'bzrlib.tests.test_delta',
3438
 
                   'bzrlib.tests.test_debug',
3439
 
                   'bzrlib.tests.test_deprecated_graph',
3440
 
                   'bzrlib.tests.test_diff',
3441
 
                   'bzrlib.tests.test_directory_service',
3442
 
                   'bzrlib.tests.test_dirstate',
3443
 
                   'bzrlib.tests.test_email_message',
3444
 
                   'bzrlib.tests.test_eol_filters',
3445
 
                   'bzrlib.tests.test_errors',
3446
 
                   'bzrlib.tests.test_export',
3447
 
                   'bzrlib.tests.test_extract',
3448
 
                   'bzrlib.tests.test_fetch',
3449
 
                   'bzrlib.tests.test_fifo_cache',
3450
 
                   'bzrlib.tests.test_filters',
3451
 
                   'bzrlib.tests.test_ftp_transport',
3452
 
                   'bzrlib.tests.test_foreign',
3453
 
                   'bzrlib.tests.test_generate_docs',
3454
 
                   'bzrlib.tests.test_generate_ids',
3455
 
                   'bzrlib.tests.test_globbing',
3456
 
                   'bzrlib.tests.test_gpg',
3457
 
                   'bzrlib.tests.test_graph',
3458
 
                   'bzrlib.tests.test_groupcompress',
3459
 
                   'bzrlib.tests.test_hashcache',
3460
 
                   'bzrlib.tests.test_help',
3461
 
                   'bzrlib.tests.test_hooks',
3462
 
                   'bzrlib.tests.test_http',
3463
 
                   'bzrlib.tests.test_http_response',
3464
 
                   'bzrlib.tests.test_https_ca_bundle',
3465
 
                   'bzrlib.tests.test_identitymap',
3466
 
                   'bzrlib.tests.test_ignores',
3467
 
                   'bzrlib.tests.test_index',
3468
 
                   'bzrlib.tests.test_info',
3469
 
                   'bzrlib.tests.test_inv',
3470
 
                   'bzrlib.tests.test_inventory_delta',
3471
 
                   'bzrlib.tests.test_knit',
3472
 
                   'bzrlib.tests.test_lazy_import',
3473
 
                   'bzrlib.tests.test_lazy_regex',
3474
 
                   'bzrlib.tests.test_lockable_files',
3475
 
                   'bzrlib.tests.test_lockdir',
3476
 
                   'bzrlib.tests.test_log',
3477
 
                   'bzrlib.tests.test_lru_cache',
3478
 
                   'bzrlib.tests.test_lsprof',
3479
 
                   'bzrlib.tests.test_mail_client',
3480
 
                   'bzrlib.tests.test_memorytree',
3481
 
                   'bzrlib.tests.test_merge',
3482
 
                   'bzrlib.tests.test_merge3',
3483
 
                   'bzrlib.tests.test_merge_core',
3484
 
                   'bzrlib.tests.test_merge_directive',
3485
 
                   'bzrlib.tests.test_missing',
3486
 
                   'bzrlib.tests.test_msgeditor',
3487
 
                   'bzrlib.tests.test_multiparent',
3488
 
                   'bzrlib.tests.test_mutabletree',
3489
 
                   'bzrlib.tests.test_nonascii',
3490
 
                   'bzrlib.tests.test_options',
3491
 
                   'bzrlib.tests.test_osutils',
3492
 
                   'bzrlib.tests.test_osutils_encodings',
3493
 
                   'bzrlib.tests.test_pack',
3494
 
                   'bzrlib.tests.test_patch',
3495
 
                   'bzrlib.tests.test_patches',
3496
 
                   'bzrlib.tests.test_permissions',
3497
 
                   'bzrlib.tests.test_plugins',
3498
 
                   'bzrlib.tests.test_progress',
3499
 
                   'bzrlib.tests.test_read_bundle',
3500
 
                   'bzrlib.tests.test_reconcile',
3501
 
                   'bzrlib.tests.test_reconfigure',
3502
 
                   'bzrlib.tests.test_registry',
3503
 
                   'bzrlib.tests.test_remote',
3504
 
                   'bzrlib.tests.test_rename_map',
3505
 
                   'bzrlib.tests.test_repository',
3506
 
                   'bzrlib.tests.test_revert',
3507
 
                   'bzrlib.tests.test_revision',
3508
 
                   'bzrlib.tests.test_revisionspec',
3509
 
                   'bzrlib.tests.test_revisiontree',
3510
 
                   'bzrlib.tests.test_rio',
3511
 
                   'bzrlib.tests.test_rules',
3512
 
                   'bzrlib.tests.test_sampler',
3513
 
                   'bzrlib.tests.test_selftest',
3514
 
                   'bzrlib.tests.test_serializer',
3515
 
                   'bzrlib.tests.test_setup',
3516
 
                   'bzrlib.tests.test_sftp_transport',
3517
 
                   'bzrlib.tests.test_shelf',
3518
 
                   'bzrlib.tests.test_shelf_ui',
3519
 
                   'bzrlib.tests.test_smart',
3520
 
                   'bzrlib.tests.test_smart_add',
3521
 
                   'bzrlib.tests.test_smart_request',
3522
 
                   'bzrlib.tests.test_smart_transport',
3523
 
                   'bzrlib.tests.test_smtp_connection',
3524
 
                   'bzrlib.tests.test_source',
3525
 
                   'bzrlib.tests.test_ssh_transport',
3526
 
                   'bzrlib.tests.test_status',
3527
 
                   'bzrlib.tests.test_store',
3528
 
                   'bzrlib.tests.test_strace',
3529
 
                   'bzrlib.tests.test_subsume',
3530
 
                   'bzrlib.tests.test_switch',
3531
 
                   'bzrlib.tests.test_symbol_versioning',
3532
 
                   'bzrlib.tests.test_tag',
3533
 
                   'bzrlib.tests.test_testament',
3534
 
                   'bzrlib.tests.test_textfile',
3535
 
                   'bzrlib.tests.test_textmerge',
3536
 
                   'bzrlib.tests.test_timestamp',
3537
 
                   'bzrlib.tests.test_trace',
3538
 
                   'bzrlib.tests.test_transactions',
3539
 
                   'bzrlib.tests.test_transform',
3540
 
                   'bzrlib.tests.test_transport',
3541
 
                   'bzrlib.tests.test_transport_log',
3542
 
                   'bzrlib.tests.test_tree',
3543
 
                   'bzrlib.tests.test_treebuilder',
3544
 
                   'bzrlib.tests.test_tsort',
3545
 
                   'bzrlib.tests.test_tuned_gzip',
3546
 
                   'bzrlib.tests.test_ui',
3547
 
                   'bzrlib.tests.test_uncommit',
3548
 
                   'bzrlib.tests.test_upgrade',
3549
 
                   'bzrlib.tests.test_upgrade_stacked',
3550
 
                   'bzrlib.tests.test_urlutils',
3551
 
                   'bzrlib.tests.test_version',
3552
 
                   'bzrlib.tests.test_version_info',
3553
 
                   'bzrlib.tests.test_versionedfile',
3554
 
                   'bzrlib.tests.test_weave',
3555
 
                   'bzrlib.tests.test_whitebox',
3556
 
                   'bzrlib.tests.test_win32utils',
3557
 
                   'bzrlib.tests.test_workingtree',
3558
 
                   'bzrlib.tests.test_workingtree_4',
3559
 
                   'bzrlib.tests.test_wsgi',
3560
 
                   'bzrlib.tests.test_xml',
3561
 
                   ]
3562
3870
 
3563
3871
    loader = TestUtil.TestLoader()
3564
3872
 
3565
3873
    if keep_only is not None:
3566
3874
        id_filter = TestIdList(keep_only)
3567
3875
    if starting_with:
3568
 
        starting_with = [test_prefix_alias_registry.resolve_alias(start)
3569
 
                         for start in starting_with]
3570
3876
        # We take precedence over keep_only because *at loading time* using
3571
3877
        # both options means we will load less tests for the same final result.
3572
3878
        def interesting_module(name):
3595
3901
    suite = loader.suiteClass()
3596
3902
 
3597
3903
    # modules building their suite with loadTestsFromModuleNames
3598
 
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
3599
 
 
3600
 
    modules_to_doctest = [
3601
 
        'bzrlib',
3602
 
        'bzrlib.branchbuilder',
3603
 
        'bzrlib.export',
3604
 
        'bzrlib.inventory',
3605
 
        'bzrlib.iterablefile',
3606
 
        'bzrlib.lockdir',
3607
 
        'bzrlib.merge3',
3608
 
        'bzrlib.option',
3609
 
        'bzrlib.symbol_versioning',
3610
 
        'bzrlib.tests',
3611
 
        'bzrlib.timestamp',
3612
 
        'bzrlib.version_info_formats.format_custom',
3613
 
        ]
3614
 
 
3615
 
    for mod in modules_to_doctest:
 
3904
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
 
3905
 
 
3906
    for mod in _test_suite_modules_to_doctest():
3616
3907
        if not interesting_module(mod):
3617
3908
            # No tests to keep here, move along
3618
3909
            continue
3647
3938
            reload(sys)
3648
3939
            sys.setdefaultencoding(default_encoding)
3649
3940
 
3650
 
    if starting_with:
3651
 
        suite = filter_suite_by_id_startswith(suite, starting_with)
3652
 
 
3653
3941
    if keep_only is not None:
3654
3942
        # Now that the referred modules have loaded their tests, keep only the
3655
3943
        # requested ones.
3762
4050
    :param new_id: The id to assign to it.
3763
4051
    :return: The new test.
3764
4052
    """
3765
 
    from copy import deepcopy
3766
 
    new_test = deepcopy(test)
 
4053
    new_test = copy.copy(test)
3767
4054
    new_test.id = lambda: new_id
3768
4055
    return new_test
3769
4056
 
3770
4057
 
3771
 
def _rmtree_temp_dir(dirname):
 
4058
def permute_tests_for_extension(standard_tests, loader, py_module_name,
 
4059
                                ext_module_name):
 
4060
    """Helper for permutating tests against an extension module.
 
4061
 
 
4062
    This is meant to be used inside a modules 'load_tests()' function. It will
 
4063
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
 
4064
    against both implementations. Setting 'test.module' to the appropriate
 
4065
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
 
4066
 
 
4067
    :param standard_tests: A test suite to permute
 
4068
    :param loader: A TestLoader
 
4069
    :param py_module_name: The python path to a python module that can always
 
4070
        be loaded, and will be considered the 'python' implementation. (eg
 
4071
        'bzrlib._chk_map_py')
 
4072
    :param ext_module_name: The python path to an extension module. If the
 
4073
        module cannot be loaded, a single test will be added, which notes that
 
4074
        the module is not available. If it can be loaded, all standard_tests
 
4075
        will be run against that module.
 
4076
    :return: (suite, feature) suite is a test-suite that has all the permuted
 
4077
        tests. feature is the Feature object that can be used to determine if
 
4078
        the module is available.
 
4079
    """
 
4080
 
 
4081
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4082
    scenarios = [
 
4083
        ('python', {'module': py_module}),
 
4084
    ]
 
4085
    suite = loader.suiteClass()
 
4086
    feature = ModuleAvailableFeature(ext_module_name)
 
4087
    if feature.available():
 
4088
        scenarios.append(('C', {'module': feature.module}))
 
4089
    else:
 
4090
        # the compiled module isn't available, so we add a failing test
 
4091
        class FailWithoutFeature(TestCase):
 
4092
            def test_fail(self):
 
4093
                self.requireFeature(feature)
 
4094
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
 
4095
    result = multiply_tests(standard_tests, scenarios, suite)
 
4096
    return result, feature
 
4097
 
 
4098
 
 
4099
def _rmtree_temp_dir(dirname, test_id=None):
3772
4100
    # If LANG=C we probably have created some bogus paths
3773
4101
    # which rmtree(unicode) will fail to delete
3774
4102
    # so make sure we are using rmtree(str) to delete everything
3783
4111
    try:
3784
4112
        osutils.rmtree(dirname)
3785
4113
    except OSError, e:
3786
 
        if sys.platform == 'win32' and e.errno == errno.EACCES:
3787
 
            sys.stderr.write('Permission denied: '
3788
 
                             'unable to remove testing dir '
3789
 
                             '%s\n%s'
3790
 
                             % (os.path.basename(dirname), e))
3791
 
        else:
3792
 
            raise
 
4114
        # We don't want to fail here because some useful display will be lost
 
4115
        # otherwise. Polluting the tmp dir is bad, but not giving all the
 
4116
        # possible info to the test runner is even worse.
 
4117
        if test_id != None:
 
4118
            ui.ui_factory.clear_term()
 
4119
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4120
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4121
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4122
                                    ).encode('ascii', 'replace')
 
4123
        sys.stderr.write('Unable to remove testing dir %s\n%s'
 
4124
                         % (os.path.basename(dirname), printable_e))
3793
4125
 
3794
4126
 
3795
4127
class Feature(object):
3877
4209
UnicodeFilenameFeature = _UnicodeFilenameFeature()
3878
4210
 
3879
4211
 
 
4212
class _CompatabilityThunkFeature(Feature):
 
4213
    """This feature is just a thunk to another feature.
 
4214
 
 
4215
    It issues a deprecation warning if it is accessed, to let you know that you
 
4216
    should really use a different feature.
 
4217
    """
 
4218
 
 
4219
    def __init__(self, dep_version, module, name,
 
4220
                 replacement_name, replacement_module=None):
 
4221
        super(_CompatabilityThunkFeature, self).__init__()
 
4222
        self._module = module
 
4223
        if replacement_module is None:
 
4224
            replacement_module = module
 
4225
        self._replacement_module = replacement_module
 
4226
        self._name = name
 
4227
        self._replacement_name = replacement_name
 
4228
        self._dep_version = dep_version
 
4229
        self._feature = None
 
4230
 
 
4231
    def _ensure(self):
 
4232
        if self._feature is None:
 
4233
            depr_msg = self._dep_version % ('%s.%s'
 
4234
                                            % (self._module, self._name))
 
4235
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
 
4236
                                               self._replacement_name)
 
4237
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
 
4238
            # Import the new feature and use it as a replacement for the
 
4239
            # deprecated one.
 
4240
            mod = __import__(self._replacement_module, {}, {},
 
4241
                             [self._replacement_name])
 
4242
            self._feature = getattr(mod, self._replacement_name)
 
4243
 
 
4244
    def _probe(self):
 
4245
        self._ensure()
 
4246
        return self._feature._probe()
 
4247
 
 
4248
 
 
4249
class ModuleAvailableFeature(Feature):
 
4250
    """This is a feature than describes a module we want to be available.
 
4251
 
 
4252
    Declare the name of the module in __init__(), and then after probing, the
 
4253
    module will be available as 'self.module'.
 
4254
 
 
4255
    :ivar module: The module if it is available, else None.
 
4256
    """
 
4257
 
 
4258
    def __init__(self, module_name):
 
4259
        super(ModuleAvailableFeature, self).__init__()
 
4260
        self.module_name = module_name
 
4261
 
 
4262
    def _probe(self):
 
4263
        try:
 
4264
            self._module = __import__(self.module_name, {}, {}, [''])
 
4265
            return True
 
4266
        except ImportError:
 
4267
            return False
 
4268
 
 
4269
    @property
 
4270
    def module(self):
 
4271
        if self.available(): # Make sure the probe has been done
 
4272
            return self._module
 
4273
        return None
 
4274
 
 
4275
    def feature_name(self):
 
4276
        return self.module_name
 
4277
 
 
4278
 
 
4279
# This is kept here for compatibility, it is recommended to use
 
4280
# 'bzrlib.tests.feature.paramiko' instead
 
4281
ParamikoFeature = _CompatabilityThunkFeature(
 
4282
    deprecated_in((2,1,0)),
 
4283
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
 
4284
 
 
4285
 
3880
4286
def probe_unicode_in_user_encoding():
3881
4287
    """Try to encode several unicode strings to use in unicode-aware tests.
3882
4288
    Return first successfull match.
3951
4357
UnicodeFilename = _UnicodeFilename()
3952
4358
 
3953
4359
 
 
4360
class _ByteStringNamedFilesystem(Feature):
 
4361
    """Is the filesystem based on bytes?"""
 
4362
 
 
4363
    def _probe(self):
 
4364
        if os.name == "posix":
 
4365
            return True
 
4366
        return False
 
4367
 
 
4368
ByteStringNamedFilesystem = _ByteStringNamedFilesystem()
 
4369
 
 
4370
 
3954
4371
class _UTF8Filesystem(Feature):
3955
4372
    """Is the filesystem UTF-8?"""
3956
4373
 
3962
4379
UTF8Filesystem = _UTF8Filesystem()
3963
4380
 
3964
4381
 
 
4382
class _BreakinFeature(Feature):
 
4383
    """Does this platform support the breakin feature?"""
 
4384
 
 
4385
    def _probe(self):
 
4386
        from bzrlib import breakin
 
4387
        if breakin.determine_signal() is None:
 
4388
            return False
 
4389
        if sys.platform == 'win32':
 
4390
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
 
4391
            # We trigger SIGBREAK via a Console api so we need ctypes to
 
4392
            # access the function
 
4393
            try:
 
4394
                import ctypes
 
4395
            except OSError:
 
4396
                return False
 
4397
        return True
 
4398
 
 
4399
    def feature_name(self):
 
4400
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
 
4401
 
 
4402
 
 
4403
BreakinFeature = _BreakinFeature()
 
4404
 
 
4405
 
3965
4406
class _CaseInsCasePresFilenameFeature(Feature):
3966
4407
    """Is the file-system case insensitive, but case-preserving?"""
3967
4408
 
4017
4458
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4018
4459
 
4019
4460
 
4020
 
class _SubUnitFeature(Feature):
4021
 
    """Check if subunit is available."""
 
4461
class _CaseSensitiveFilesystemFeature(Feature):
4022
4462
 
4023
4463
    def _probe(self):
4024
 
        try:
4025
 
            import subunit
 
4464
        if CaseInsCasePresFilenameFeature.available():
 
4465
            return False
 
4466
        elif CaseInsensitiveFilesystemFeature.available():
 
4467
            return False
 
4468
        else:
4026
4469
            return True
4027
 
        except ImportError:
4028
 
            return False
4029
4470
 
4030
4471
    def feature_name(self):
4031
 
        return 'subunit'
4032
 
 
4033
 
SubUnitFeature = _SubUnitFeature()
 
4472
        return 'case-sensitive filesystem'
 
4473
 
 
4474
# new coding style is for feature instances to be lowercase
 
4475
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
 
4476
 
 
4477
 
 
4478
# Kept for compatibility, use bzrlib.tests.features.subunit instead
 
4479
SubUnitFeature = _CompatabilityThunkFeature(
 
4480
    deprecated_in((2,1,0)),
 
4481
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4034
4482
# Only define SubUnitBzrRunner if subunit is available.
4035
4483
try:
4036
4484
    from subunit import TestProtocolClient
4037
 
    try:
4038
 
        from subunit.test_results import AutoTimingTestResultDecorator
4039
 
    except ImportError:
4040
 
        AutoTimingTestResultDecorator = lambda x:x
 
4485
    from subunit.test_results import AutoTimingTestResultDecorator
4041
4486
    class SubUnitBzrRunner(TextTestRunner):
4042
4487
        def run(self, test):
4043
4488
            result = AutoTimingTestResultDecorator(
4046
4491
            return result
4047
4492
except ImportError:
4048
4493
    pass
 
4494
 
 
4495
class _PosixPermissionsFeature(Feature):
 
4496
 
 
4497
    def _probe(self):
 
4498
        def has_perms():
 
4499
            # create temporary file and check if specified perms are maintained.
 
4500
            import tempfile
 
4501
 
 
4502
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
 
4503
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
 
4504
            fd, name = f
 
4505
            os.close(fd)
 
4506
            os.chmod(name, write_perms)
 
4507
 
 
4508
            read_perms = os.stat(name).st_mode & 0777
 
4509
            os.unlink(name)
 
4510
            return (write_perms == read_perms)
 
4511
 
 
4512
        return (os.name == 'posix') and has_perms()
 
4513
 
 
4514
    def feature_name(self):
 
4515
        return 'POSIX permissions support'
 
4516
 
 
4517
posix_permissions_feature = _PosixPermissionsFeature()